Https://www.codecademy.com/practice/tracks/introduction-to-javascript/modules/learn-javascript-loops

https://www.codecademy.com/practice/tracks/introduction-to-javascript/modules/learn-javascript-loops

Fill the blanks in the following code, so that the computed result is 9876 .

let total = 0;
for (let n = 9; n >= 6; n -= 1) {
total *= 10;
total += n;
}
Would you please explain how the code above computes to 9876
Also, did I write it out correctly?

Thanks!

  • The loop iterates backwards (n-=1)
  • starting with n = 9 and ending with n = 6.
  • it performs the operations of multiplying the total by 10
  • it adds n to the total
  • (loops back, n = 8 now, repeat until it equals 5 – in which case it doesn’t run the code)

Thanks so much!

I now get the looping in the code (let n=9; n>= 6; n -= 1)

But when you get inside the code block, we mulitply 9876 x 10 = 98760 and then we add n to the total. I am confused by what n is at this point. Is it still 9? Is the final total 98769?

Well, you can write it out on paper, it helps to make a table

n | first op | second op
-------------------------
9 | 0        | 9           
8 | 90       | 98

et cetera.

1 Like