Hi everyone! I wonder if anyone would be willing to break down the answer to this question:

"
What is the value that is computed by this code block?
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);
"

I actually got it right, so I know the answer is ‘23’ and their explanation is ’ The loop variable (i is 6, 4, 2, 0) accesses the values in the order: 5, 15, 4, 1.’ if anyone would be willing to explain this step by step I would greatly appreciate it!

Essentially what this is doing is taking every second element starting from the end, dividing the total by that and adding 10. I will break down a couple of the passes but not the entire process as due to the nature of it being a loop, it’s much the same every pass.

values and total variables are declared and initialised.

The loop conditions are initialised. In this case, i takes the starting value of 8-2 = 6. Then over the course of the loop i will decrease by 2 until no longer bigger than or equal to 0. This just ensures that no invalid indexes are read.

a is initialised to be the value of values[i]. As we said i is initialised to 6, therefore a = values[6], which is equal to 5 since arrays are 0-indexed in JS.

total is set equal to it’s current value divided by this a value. Therefore total = 100/5 = 20.

10 is then added to total, giving total a final value of 30 on first pass.

The process then repeats, with i becoming this time 6-2 = 4. This means that a = values[4] = 15. Then total = 30/15 = 2. And finally on this pass total = 2 + 10 = 12. The process then repeats until the final stage is reached and an answer is finalised.

Hopefully that break down makes sense and helps, let me know if you have any further questions!

Thank you, Adam! That was very helpful. I think what threw me off was that there was a single numerical answer. Your explanation cleared up a few uncertainties for me. I appreciate your energy in helping me think through this question.