Basic Syntax on for statements


#1

I notice that in the first few exercises teaching syntax, the last phrase within the parenthesis jumps from counter=++ to i=i+1. Now, i understand the substitution for counter with i, but why the change in the last phrase with no explanation? What does the change represent if anything at all?


#2

Basic for statement

for (var i = 1; i < 21; i++) {
    // loop code body
}

The statement takes three parameters:

1. iterator variable declaration and initialization => Start
2. conditional expression                           => End
3. increment/decrement expression                   => Step

Your question concerns #3, the Step. This can be any expression that modifies the iterator value, and it can be in either direction, up or down the number line.

We can start with a higher value, and work backwards through a set of numbers with a negative step.

// count down by 5's
for (var i = 50; i > 0; i -= 5) {
    console.log(i);
}

Output

50
45
40
35
30
25
20
15
10
5

We use a shorthand arithmetic assignment operator above, -=. The expression,

i -= 5

is the equivalent to,

i = i - 5

In both cases, i has 5 taken away.

This expression,

i++

is equivalent to,

i = i + 1

and this,

i--

is the same as,

i = i - 1

It is touched upon, but only briefly in the track. We do get plenty of practice though, so any confusion around this should clear up, presently. In the meantime, search for JavaScript arithmetic operators and visit the MDN link that comes up in the SERP.


#3

Thank you. I should have waited a few more lessons when this explained itself. Thank you for the response.