junebug
junebug

Reputation: 45

Looping Fundamentals

Can someone please let me know where I went wrong here? When I run the code, I get 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 10. How would I make the loop stop at 0? When I remove the last line of code (console.log(countDown);), the loop ends at 0 but the challenge isn't completed. Any help is greatly appreciated!

Using a for loop, decrement countDown by one each time the loop runs until it equals 0, making use of looping functionality instead of logging each number separately.

let countDown = 10;
// ADD CODE HERE
for (let countDown = 10; countDown>0;countDown--)
{
  console.log(countDown);
}

// Uncomment the below line to check your work
console.log(countDown) // -> should print 0;

Upvotes: 4

Views: 369

Answers (2)

ttarczynski
ttarczynski

Reputation: 1014

It's not a problem with looping - it's a problem with variable scope. See this link for what scope is: wiki

let countDown = 10; // global scope - visible everywhere

for (let countDown = 10; countDown>0;countDown--) // local scope -- visible only in the loop
{
  console.log(countDown);  // this is again the inner variable with local scope
}

console.log(countDown) // the global scope variable again, hence 10;

To the issue itself, in fact you have two variables with the same name countdown. One defined outside the loop, and the other in the loop declaration. The latter shadows (hides) the former, thus any changes done to the inner variable - with a smaller scope, encompassing only the loop body - are not visible after the loop ends. So, in fact, your code does not change the value of the outer countdown.

To make it work, don't declare the inner variable, and reuse the outer one as the loop counter:

let countDown = 10;

for (; countDown > 0; countDown--) {
    console.log(countDown);
}

console.log(countDown);

Upvotes: 1

Yousaf
Yousaf

Reputation: 29282

Problem is that you have two countDown variables in your code, one at the top and one declared as a loop variable, in the initialization part of the for loop.

They both are different variables. Your loop is terminated correctly but when you log the countDown variable after the loop, you are not logging the one used in the loop, you are logging the one declared above the loop.

You don't need to declare countDown variable in loop, just use the one declared above the loop.

let countDown = 10;

for (; countDown > 0; countDown--) {
  console.log(countDown);
}

console.log(countDown) // -> should print 0;

Upvotes: 5

Related Questions