We use the += or i++ assignment operator to update the counter variable. It’s called a final expression and work is to evaluate at the end of each loop iteration.
This occurs before the next evaluation of condition
. Generally used to update or increment the counter variable.
JavaScript for loop increment examples
HTML examples codes:-
Increments i by 1 after each pass through the loop.
for (let i = 0; i < 9; i++) {
console.log(i);
// more statements
}
Increment variable every 5 iterations of for loop?
If you won’t want to have a variable that gets incremented every 5th iteration, so you need to check if the index is a multiple of 5:
var foo = 0;
for (var i; i < someLength; ++i) {
if (i % 5 === 0) {
foo++;
}
}
This uses the modulus operator to get the remainder of i / 5
. If it’s 0, then we know the index is a multiple of 5.
How to increment for a loop by 2 in JavaScript?
Here is an example using an Array, the same way you can do for increments of 3,4 and so on.
<!DOCTYPE html>
<html>
<body>
<script>
var myVar = [1,2,3,4,5,6,7,8,9,10]
for (var i = 0; i < myVar.length; i += 2) {
console.log(myVar[i]);
}
</script>
</body>
</html>
Output:
Do comment if you have any doubts and suggestions on this topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version