Ricky Ricky - 2 months ago 7
Javascript Question

Understanding assignment operators javascript

Okay, i have not found an answer to my question and have been thinking about it for weeks.

In javascript my understanding of the assignment operator is the = sign, this is because of variables i.e:

var randomVar = thisVar


but if you then wanted to do a for loop using this variable, you would normally shorten it for example:

for (i=1; i < thisVar; i++){}


so in these paranthesis,it appears that the < symbol is also an assignment operator, yet i cannot find anything to explain this, could someone explain more clarity on this or point me in the right direction, as most things i find shows this rightfully as the less than operator.

Answer

Your function myfunction (i=1; i < thisVar; i++) is a syntax error. We can't explain how that code works because it doesn't.

You may be thinking of the for loop:

for (i=1; i < thisVar; i++) {
}

The for loop has three expressions within its () that are separated with ;:

  1. An initialization (i=1 in your case) that occurs at the very beginning, before the first test (see #2)

  2. A test (i < thisVar in your case) that is performed prior to each iteration of the loop and determines whether the loop ends

  3. An update (i++ in your case) that occurs after each loop iteration, before the test

This is intrinsic to how for loops work, and is not general-purpose; you can't just do that within () anywhere you like, it has to be on a for loop.

The < in that, as you can see above, is part of the test — a condition that must be true for the loop to continue. It's not an assignment. It's a relational operator comparing i with thisVar to determine whether i is less than thisVar.

Comments