To add to that, the for loop block is broken into three parts:
for(initializer; condition; incrementer)
The initializer gives an initial value that can used for the loop. The condition tells JavaScript “hey, only do this stuff while this condition is true” and the incrementer is used to perform some action once at the end of every loop. Typically it is used to increment or decrement a counting variable initialized in the initializer.
Just a few things to say further, the initializer can have any number of variables declared in it. I’ve done it with two, though there’s really no limit to how many you want, except common sense and readability:
function binary(binstring) {
// converts a string of binary to a decimal number
// 0101 => 3
let result = 0;
for(let i = binstring.length - 1, j = 0; i >= 0, j < binstring.length; i--, j++) {
result += parseInt(binstring[i]) * (2 ** j);
}
return result;
}
To get the above code to work, I needed one counter to go up, and another to go down. So I was able to initialize two variables, and use both of them in the incrementer.
In fact, there’s no rule stating the incrementer even has to increment, it’s just a statement that gets run every time the loop progresses:
for(let j = 'cat', k = ''; true; console.log(k)) {
k += j;
if(k === 'catcatcat') {
break;
}
}
This absurd example will log:
cat
catcat
And break when it gets to catcatcat
, so it won’t ever print that.
Not that I’d advise doing this, by the way, just showing an example of how it works.
Finally, all three blocks are optional, but the semicolons are not.
for(;;) {}
The above is an infinite loop that will never break. If you don’t need one or more of the blocks, you don’t have to use it.
In the end go to the MDN for more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for