-1

Looking for the proper way to do this. I managed to get the answer, but I don't think it was how I was supposed to do it.

I'm supposed to use a for loop, to decremment var countDown by one each time the loops runs until it equals 0.

var countDown = 10; 

for (let i=0; i < 5; i++)
countDown = countDown-i

console.log(countDown) // output 0;

I understand why my way works. But it doesn't decrement by one. Another way I thought was:

var countDown = 10;

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

console.log(countDown) // output 10, 9 , 8, 7, 6, 5, 4, 3, 2, 1, 0, 10

How would I globally change the countDown variable to 0?

  • 1
    `for(; countDown > 0; countDown--);` – ASDFGerte Jul 03 '18 at 22:41
  • Possible duplicate of [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Vincent Taing Jul 03 '18 at 23:44

4 Answers4

0
let countDown = 10;
for(let i = 0; i < 10; i++){
  countDown--;
}

console.log(countDown); //print 0;
Payam
  • 11
  • 1
  • 1
    Hello and welcome to SO! While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. Please read the [tour](https://stackoverflow.com/tour), and [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) – Mhd Alaa Alhaj Jan 20 '21 at 09:29
-1

Simple way using a for loop.

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

Depending on what the context is, you can put the var in the for loop too like

for(var countDown = 10; countDown > 0; countDown--)

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
-1

Just make countdown the variable in your loop and decrement while > -1.

for (var countDown = 10; countDown>0;countDown--)
{
  console.log(countDown);
}
console.log(countDown);
nixkuroi
  • 2,259
  • 1
  • 19
  • 25
-1
let countDown = 10;
// ADD CODE HERE

for (let countDown=10; countDown <=10 && countDown > 0;)
{
    countDown--
}

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

This will decrement the countDown by 1 from 10 to 0 but the challenge asks for only the zero to be displayed after the code had run.

This will display 0 after the code had run.

To display the countDown from 10 to 0 write the for loop like this:

for (let countDown=10; countDown <=10 && countDown > 0; countDown--);
Diego Bascans
  • 1,083
  • 1
  • 6
  • 14