Can someone explain this line of code?

Can someone explain me this for loop below?

I’d think that by using “-3”, you would extract 3 from whatever number you have but, from what I understood, this loop is returning a string representation of the number value with a comma every 3 digits.

``````/* modules/utilities.js */
export const formatNumber = number => {
// Get rid of the decimals and convert to a string.
let numStr = String(Math.floor(number));

// Starting 3 from the end, add a comma every 3 digits.
for (let i = numStr.length - 3; i > 0; i -= 3) {
numStr = numStr.slice(0, i) + ',' + numStr.slice(i);
}

// And return!
return numStr;
}
``````

thank you!

Hello!
The i in the for loop is being used as the index where you want to insert the , into the string.
So, if the number is 11223344. It’s first converted to a string “11223344”
Then the loop starts and i is set to the strings length -3 ( so in our case 5.)
Inside the loop,
numStr.slice(0, 5)
(slice takes the string from index 0 (the start) up to, but not including, index 5)
“11223”
then it adds in a comma, then;
numStr.slice(5)
takes the slice of string from i to the end.
“344”
So, numStr now becomes “11223,344”

The loop will reduce i by 3 (so it now becomes 2) and we get
numStr = numStr.slice(0, 2) + ‘,’ + numStr.slice(2)
so, numStr = “11” + ‘,’ + “223,344” = “11,223,344”

Then, i is again reduced by 3 to -1. Which means i > 0 is no longer true and the loop ends.

Hopefully that helps

1 Like