Javascript Syntax Part II: Loops / 'For' Reverse Loop

Hey CC Community!

I’m a first time poster and beginner on the Full Stack Engineer path, so bear with me if my question reaks of n00b.

So, I was answering a question in one of the Practice Pack for the topic: Javascript Syntax Part II: Loops (https://www.codecademy.com/practice/paths/full-stack-engineer-career-path/tracks/fscp-javascript-syntax-part-ii/modules/fecp-learn-javascript-syntax-loops).

Here is the question I was given:

What is the value that is computed by this code block?
[and the code]

const values = [1, 10, 4, 3, 15, 3, 5, 2];
 
let total = 100
for (let i = values.length - 2; i >= 0; i -= 2) {
  let a = values[i];
  total /= a;
  total += 10;
}
console.log(total);

After some calculations, and as many guesses as the site allowed, I finally got the answer to the question (Spoiler Alert: 23). However, I can not for the life of me, understand why. Before this, I believed I had a good understanding of variables, ‘for’ loops/reversing ‘for’ loops, and control flow, but this single question has me questioning that belief.

If anyone has some time, can you please explain to me why the answer is what it is?

Thanks!

Hi @reneevalentine342818
welcome to the forum!
Did you add a console.log to each calculation step? I think that would help you understand the loop:

 
let total = 100
for (let i = values.length - 2; i >= 0; i -= 2) {
  let a = values[i];
  console.log('a: ', a);
  total /= a;
  console.log('total: ', total);
  total += 10;
  console.log('total: ', total);
}

These are the total values after each loop:

// 1st round
// values.length === 8
// values.length-2 === 6
// i-=2 --> counts down by 2
/*
for (let i = values.length - 2; i >= 0; i -= 2) { // i === 6
  let a = values[i]; // values[6] --> a === 5
  total /= a; // total = total / 5  --> 100 / 5 --> 20
  total += 10; // total = total + 10 --> 20 + 10 --> 30
}
// 2nd round
for (let i = values.length - 2; i >= 0; i -= 2) { // i === 4
  let a = values[i]; // values[4] --> a === 15
  total /= a; // total = total / 15  --> 30 / 15 --> 2
  total += 10; // total = total + 10 --> 2 + 10 --> 12
}
// 3rd round
for (let i = values.length - 2; i >= 0; i -= 2) { // i === 2
  let a = values[i]; // values[2] --> a === 4
  total /= a; // total = total / 4  --> 12 / 4 --> 3
  total += 10; // total = total + 10 --> 3 + 10 --> 13
}
// 4th round
for (let i = values.length - 2; i >= 0; i -= 2) { // i === 0
  let a = values[i]; // values[2] --> a === 1
  total /= a; // total = total / 1  --> 13 / 1 --> 13
  total += 10; // total = total + 10 --> 13 + 10 --> 23
}
*/

I hope that helps. Otherwise let me know, where you’re stuck.

2 Likes

This is such an incredible breakdown, @mirja_t, I’m able to see exactly where I messed up. This breakdown actually helps me understand nested ‘for’ loops, and definitely this question, a lot more. Thank you so much for your help!

1 Like