Final log in while loop logging twice


#1

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

the exercise is to create a for loop and a while loop to the same end. i have managed to get them to run, (logging numbers 1-10), however in the while loop the number 10 is being logged twice and i can't figure out why. Any ideas?


var exercise = 0

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

while (exercise < 11) {
    console.log(exercise);
    exercise++;
};


#2

its console behavior, because you update a variable after the last console.log(), this variable will also be logged to the console, you can simply swap exercise increment and console.log:

    exercise++;
    console.log(exercise);

to fix the problem


#3

that's great thanks. this is also logging 11 now though. sorry if this is rudimentary just trying to understand.


#4

because you increase i before logging it to the console, i see your point, we can simply do:

var exercise = 0

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

while (exercise < 11) {
    console.log(exercise);
    exercise++;
};
console.log("")

this way, we log an empty string to the console after updating the last variable


#5

ah now i see. wonderful thank you.


#6

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