Basic, basic query about For Loops

Hi all - I have what is probably a v basic question about for loops.

In a basic for loop such as…:

for (i = 0; i < 5; i++) {
console.log(i);
}

…It seems to me that the count (i) increases before reaching the log command - yet this loop will log 0 (or whatever ‘i’ is initialised as), as the first output.

To me it looks like ‘i’ should increase by 1 before being logged, hence the first output should be 1 - not zero.

I hope this makes sense. Be v pleased if anyone can offer this noob an explanation.

Best,
Andrew

Yes it does look like it should be incremented first and the first result should be 1…
but no. that’s not how for mechanism works.
the i++ in the final-expression will be evaluated at the end of each loop iteration.

the following document should explain more in detail

That’s v helpful thanks psyperl.

Glad to be of help, cheers

@messiosa, you might be interested in learning more about the pre vs post increment/decrement operators.

++i and --i (pre == before)

vs

i++ and i-- (post == after)

Where the arithmetic operators are placed tells the for loop whether to perform the operation (of adding/subtracting 1) before or after running the lines of code within the for loops curly braces.

also very helpful/interesting - cheers!