Home > Mobile >  breaking a for loop with length decrement
breaking a for loop with length decrement

Time:11-17

I found this code to convert an excel column name into a column number but having a hard time understanding the break condition for the loop

//function convert excel sheet column to number

toColumnNumber = (colName) => {
  let result = 0;
  for (let i = colName.length, j = 0; i--; j  ) {
    result  = Math.pow(26, i) * (colName.charCodeAt(j) - 64);
  }
  return result;
};
console.log(toColumnNumber("AB"));

it uses i-- as a break condition and i can't understand how it can be used to break the loop. or is it just that is how javascript works when we use i-- as a break condition and it reaches 0 it breaks the loop?

CodePudding user response:

As we keep decrementing the value of i, eventually it reaches 0 and that would be falsy and would stop the loop.

This is just a fancy way of saying:

for (let i = colName.length, j = 0; i > 0; j  , i--) {
    result  = Math.pow(26, i) * (colName.charCodeAt(j) - 64);
  }
  • Related