2

I am at a loss how best to approach for loops in JavaScript. Hopefully an understanding of for loops will help shed light on the other types of loops.

Sample code

for (var i=0; i < 10; i=i+1) {
    document.write("This is number " + i);
}

My understanding is that when i has been initialized, it starts with the value of 0 which then evaluated against the condition < 10. If it is less than 10, it the executes the statement document.write("This is number + i); Once it has executed the preceding statement, only then does it increment the next value by 1.

Guides I have consulted:

  1. http://www.functionx.com/javascript/Lesson11.htm
  2. http://www.cs.brown.edu/courses/bridge/1998/res/javascript/javascript-tutorial.html#10.1
  3. http://www.tizag.com/javascriptT/javascriptfor.php

Now the guide at http://www.functionx.com/javascript/Lesson11.htm seems to indicate otherwise i.e.

To execute this loop, the Start condition is checked. This is usually the initial value where the counting should start. Next, the Condition is tested; this test determines whether the loop should continue. If the test renders a true result, then the Expression is used to modify the loop and the Statement is executed. After the Statement has been executed, the loop restarts.

The line that throws me is "If the test renders a true result, then the Expression is used to modify the loop and the Statement is executed". It seems to imply that because 0 is less than 10, increment expression is modified which would be 0 + 1 and THEN the statement, e.g. document.write is executed.

My problem

What is the correct way to interpret for loops? Is my own comprehension correct? Is the same comprehension applicable to other programming languages e.g. PHP, Perl, Python, etc?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
PeanutsMonkey
  • 6,919
  • 23
  • 73
  • 103
  • It should work like how a for loop works in C and Java. I guess the last source is wrong? – nhahtdh Jun 20 '12 at 01:17
  • [here is a reference of how loops work](http://stackoverflow.com/a/6853283/497418). I know the linked question is about *Java* but they work the same way. There is a little more nuance when you add `continue` statements, but at least it's a start. – zzzzBov Jun 20 '12 at 01:17
  • Your primary reference for language issues should **always** be [ECMA-262](http://es5.github.com/#x12.6.3) (see Felix's answer). Other references might be helpful, but may also contain mistakes and errors. – RobG Jun 20 '12 at 01:28
  • Btw, you should already be able to confirm (or disprove) your understanding, but simply executing this statement. Which output do you get? http://jsfiddle.net/UJsfL/ – Felix Kling Jun 20 '12 at 02:07
  • P.S. http://www.functionx.com/ is a terrible resource. There example calls the variable `Number`,,, – Ross Jun 20 '12 at 02:10

6 Answers6

8

Think of a for loop as the following

for(initializers; condition; postexec) {
    execution
}
  1. When the loop is first started the code var i = 0 is run. This initializes the variable that you will be testing for inside the loop

  2. Next the loop evaluates the i < 10 expression. This returns a boolean value which will be true for the first 10 times it is run. While this expression keeps evaluating to true the code inside the loop is run.

    document.write("This is number " + i);

  3. Each time after this code is run the last part of the loop i++ is executed. This code in this example adds 1 to i after each execution.

After that code is executed the condition of the loop is check and steps 2 and 3 repeat until finally the condition is false in which case the loop is exited.

This the way loops work in the languages you mentioned.

Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
secretformula
  • 6,414
  • 3
  • 33
  • 56
  • 1
    You are correct, but why should the OP trust you more than the website they quoted? I don't want to devalue your answer, but you are only repeating what the OP already believes to know. – Felix Kling Jun 20 '12 at 01:41
  • 1
    I feel I am explaining what he knows in a different way. His interpretation of my explanation should corroborate with what he already believes. – secretformula Jun 20 '12 at 01:46
  • 1
    @FelixKling probably because SO has the voting system therefore SO has a form of peer review and the answer has been voted up. Perhaps the OP should not trust SO more than the website quoted. But that questions why the OP would ask the question here in the first place. : ) – Ross Jun 20 '12 at 02:04
5

Lets have a look at the corresponding section in the ECMAScript specification:

The production
IterationStatement : for ( var VariableDeclarationListNoIn ; Expressionopt ; Expressionopt) Statement
is evaluated as follows:

1. Evaluate VariableDeclarationListNoIn.
2. Let V = empty.
3. Repeat
  a. If the first Expression is present, then
     i. Let testExprRef be the result of evaluating the first Expression.
     ii. If ToBoolean(GetValue(testExprRef)) is false, 
         return (normal, V, empty).
  b. Let stmt be the result of evaluating Statement.
  ...
  f. If the second Expression is present, then
     i. Let incExprRef be the result of evaluating the second Expression.
     ii. Call GetValue(incExprRef). (This value is not used.)

As you can see, in step 1, the variable assignment is evaluated. In step 3a, the condition is tested. In step 3b, the loop body is evaluated, and after that the third expression is evaluated in step 3f.

Therefore your understanding of the for loop is correct.


It is to assume that it works the same way in other languages, since the for loop is such a common statement in programming languages (note that Python does not have such a statement). But if you want to be absolutely certain, you better consult their specification as well.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • @Felix Kling - I wouldn't mind referring to the specification however often than not the explanations are beyond what a newbie like me would grasp. I would have never comprehended the reference you cited unless someone like yourself would have explained it. – PeanutsMonkey Jun 20 '12 at 02:40
  • @PeanutsMonkey: Yes, I can understand that. But IMO you can only start to understand it if you have a look at it from time to time. It will get better. It took me a long while to comprehend it and there are certain sections which are still difficult. – Felix Kling Jun 20 '12 at 02:43
  • @Felix Kling - Can I safely assume that the same principle can be applied to other languages? – PeanutsMonkey Jun 20 '12 at 03:05
  • @FelixKling. I decided to write a [full answer](http://stackoverflow.com/q/11114622/601179) for the multiple elements with the same `id` repeated question. This question is asking here every day couple of times. Do you think it can be improved? if you do, I'll make it a community wiki. – gdoron Jun 20 '12 at 07:55
4

Your quoted source is wrong, and we can prove it...

The basis of the for loop has four separate blocks which may be executed:

for(initialise; condition; finishediteration) { iteration }

Fortunately we can execute a function in each of these blocks. Therefore we can create four functions which log to the console when they execute like so:

var initialise = function () { console.log("initialising"); i=0; }
var condition = function () { console.log("conditioning"); return i<5; }
var finishediteration = function () { console.log("finished an iteration"); i++; }
var doingiteration = function () { console.log("doing iteration when `i` is equal", i); }

Then we can run the following, which places the above functions into each block:

for (initialise(); condition(); finishediteration()) {
    doingiteration();
}

Kaboom. Works.

If you viewing this page using Safari on the Mac then you can AppleAlt + I and copy the above two snippets, in order, into the console and see the result.

EDIT, extra info....

Also... the finished iteration block is optional. For example:

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

does work.

Ross
  • 14,266
  • 12
  • 60
  • 91
  • Had no idea I could call on functions exemplified by you. – PeanutsMonkey Jun 20 '12 at 02:54
  • Would you mind elaborating on each function is being called into the `for loop`? For example, you have `var initialise = function () { console.log("initialising"); i=0; }`. Does this mean that `initialise()` takes on the value of `console.log("initialising"); i=0;`? – PeanutsMonkey Jun 20 '12 at 02:58
  • @PeanutsMonkey I'm not to sure what you question but I will try answer. Functions in javascript are variables and therefore can be stored like other things and called later. Therefore this `function initialise () { some code }` is the same as `var initialise = function () { some code }`. As this is so key to some later concepts of JavaScript that you may or may not cross, I believe it is good practice to write function like above. – Ross Jun 25 '12 at 14:07
  • @PeanutsMonkey so... when the variable `initialise` is told to execute with the `()` operator, it will trigger the block of code which is between `initialise`'s `{}`. Therefore when the browser reaches `initialise()` it executes `console.log("initialising"); i=0;` – Ross Jun 25 '12 at 14:10
2

The second reference is wrong. Your explanation is correct.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
1

Another way to think about it, if this helps you:

var i = 0;
while (i < 10) {
    document.write("This is number " + i);
    i++;
}
Evan Trimboli
  • 29,900
  • 6
  • 45
  • 66
0

This is for statement syntax:

for(initalize, condition, increment) {
    Do_some_things();
}

initalize Will executed only one time when for begin then it execute Do_some_things(); statement, and while condition still true it will execute increment and then Do_some_things();. if co condition false, for would exit.

for (var i=0; i < 10; i=i+1) {
    document.write("This is number " + i);
}

var i=0 will execute one time (initalize). i < 10 condition was always checked after a loop. i=i+1 will execute after check i < 10 and result is true. Value of i is: 0, 1, 3, 4, 5, 6, 7, 8, 9 (10 times loop)

Bình Nguyên
  • 2,252
  • 6
  • 32
  • 47
  • 1
    The "condition" (second expression) is tested **before** the the block is executed. If the condition is initially false, the block will not be executed. The "increment" (third expression) is always executed after the block is complete and before testing the condition again. Note that the "condition" and "increment" can be any valid expression, but the second must evaluate to true for the block to be executed. – RobG Jun 20 '12 at 01:36