While Review


#1


So I have completed the while lesson, however, my code didn't work as I thought it would. I intended for the console to print 'the number is now i' only for 0, 1, and 2, however, it went ahead and printed out until 4. It seems to have disregarded the while part of the do, while function altogether. Any help appreciated, thanks.


var counter = 0
var finalFunction = function() {
    for (var i = counter; i < 5; i ++) {
        console.log(i);
    };
    do {
        console.log("The number is now" + " " + "i" + ".");
    } while(i < 3);
};
finalFunction();


#2

A do..while loop, will execute at least one iteration before testing the condition, hence the behavior you observed.


#3

Oh, of course, thank you. So how would I edit it so that it only went through until 3 on the second time? Or in other words, If I call this function, it seems every time it will do the same thing, but how would i be able to call it so that it ran through twice, the first time for the do, printing until 5, and the second time following the while, and printing only until 3? Thanks


#4

The for loop will print out, 0 1 2 3 4 as expected, since those are the values of i in the loop. In general programming terms this is known as a range. The parameters of a for statement describe a range. Think of it as an ordered list of values to iterate over.

Let's examine what happens to i after the for loop. When var is used in a for statement it goes to the top of the scope the for statement is in. (Scope is just another word for environment, or memory block accessible by a function.) So it is still accessible after the loop. This is known as leakage. The new ES6 keyword, LET elliminates that leakage, but that is for another discusssion. The point is that i has a value after the loop, 0.

The scariest part is the fact that i does not change value inside the do..while loop. That should be an infinite loop and crash your browser window. Lesson here: Never leave a control variable unchanged in a while loop (do while is a while loop.)

The neat thing about JS is that we change a value inside a statement.

console.log(i++)

It will print i and increment it in one stroke. Search `JS prefix and postfix addition and subtraction' for more detail on this. This is an efficient way to deal with the problem of change.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.