For Loop in JavaScript: An Explanation

book pic

This question came up, concerning this question in a book: how to understand this for loop.

let result=1;
 for (let counter=0; counter < 10; counter=counter+1){
    result=result*2;
 }
 console.log(result);

It's a little confusing because one value (counter) tracks the iteration through the loop, and the other value (result) tracks the value being changed. It's also very verbose, for what it is.

Basically though, counter is counting you through the loop, and result is what is actually changing. Outside of just doing things 10 times (starting with 0 and ending at 9), counter is unimportant, and a little confusing, in this example.

So, as counter is doing this:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9

The result is doing this:

1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024

Notice that you started at 0. When you count on your fingers from 1 to 10, that's 10 digits. When you start from 0 and stop at 9 (which is the last number less than 10), there's also 10 digits.

Also note that this is a somewhat confusing and inelegant way to do the calculation, and if you were to submit this for loop in a code interview, you'd probably get docked some points. It works, but it's not great.

Another way, also using JavaScript, using forEach, would be:

let val=1;
 [0,1,2,3,4,5,6,7,8,9].forEach(function(i) {
  val=val*2;
});
console.log(val);

Using map:

val=1;
 [0,1,2,3,4,5,6,7,8,9].map((item)=>val=val * 2);
 console.log(val);

Using reduce:

let counter = [2,2,2,2,2,2,2,2,2,2];
 result = counter.reduce(function(previousVal, currentVal) {  return previousVal  * currentVal }, 1);
 console.log(result);

They all return the same value - so that gives you a few ways to think about and do it.