11. Not understanding why its acting this way


#1



https://www.codecademy.com/courses/javascript-beginner-en-ASGIv/2/4?curriculum_id=506324b3a7dffd00020bf661#


This works and gets me passed the exercise but it's not behaving how I would expect. I don't understand why the numbers don't come out in order, and why the do/while does not print twice. This is the result I am referencing
1
2
Cheese times 3 bby
Cheese times 3 bby
Cheese times 3 bby
imma just loop twice
3


var cheese = 0

for ( var i = 1; i < 3; i++) {
    console.log(i);
};

while ( cheese < 3) {
    console.log ("Cheese times 3 bby");
        cheese++;
};

do {
    console.log("imma just loop twice");
    cheese++;
}
while (cheese < 2);


#2

Remember to reset cheese to 0, (it is at 3 when starting the do..while). Or you could just make it < 5 to end the loop.


#3

What @mtf said, and remove the space between log and ("C here.


#4

Oh wow! I never even considered that it was staying at that number. That helps not just with this but that just like clicked a switch for how some of this stuff works for me, thanks a lot! :slight_smile:


#5

Technically, that space isn't hurting anything, so long as the code isn't being inspected directly by the SCT.


#6

So I changed reset the variable and that is all fine and dandy but still having trouble with the for loop. It's coming up out of order and not really sure why and also it's ending with 1 which is confusing. Thank you again in advance for the time

1
2
Cheese times 3 bby
Cheese times 3 bby
Cheese times 3 bby
imma just loop once
imma just loop once
1


#7

We are working in ECMAScript 5.x so loops and for statements share the scope they are in (meaning variables leak out of them). Once you start working in ES6, you will need to treat variables in block scope, meaning they do not share variables outside of their blocks unless declared outside beforehand.

ES5

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

ES6

for (var i = 0; i < 10; i++) {
    // do something
}
console.log(i);    // referenceError  (no leakage)

var k;
for (k = 0; k < 10; k++) {
    // do something
}
console.log(k);    // 10  (in scope)

#8

You for loop is working as expected. The number you are seeing is the console response at the end of the program run. This is normal behavior and can be ignored. To defeat it, just be sure the last executed command is console.log();.


#9

Ah excellent thank you very much you were a amazing help.


#10

3 posts were split to a new topic: 11. while loop