This article will describe the βforβ loopβs increment statement by 2.
How to Increment by 2 in for Loop in JavaScript?
The βforβ statement constructs a loop with three optional arguments βinitializerβ, βconditional-statementβ and the βfinal-expressionβ enclosed in parentheses and spaced by semicolons. The final expression is utilized to change the counterβs value.
Syntax
For the increment by 2 in βforβ loop, use the below-provided syntax:
// statement
}
In the above syntax:
- i=0 is called initializer, use βvarβ or βletβ instead of βconstβ because it will throw an Uncaught TypeError: Assignment to constant variable.
- i<10 is the conditional statement that must be executed before every loop iteration.
- i+=2 is the final expression that increments by 2.
Example 1:
Let, print the even numbers between 0 and 10 using βforβ loop, incrementing by 2:
console.log(i);
}
Output
The above output indicates that the loop increments by 2 and prints an even number between 0 and 10.
Example 2:
Create an array of number 1 to 10:
Here, iterate the loop over an array until its length, incrementing by 2:
console.log(array[i]);
}
The output displays an odd numbers between 1 and 10 from an array:
Conclusion
A βforβ loop is utilized to repeatedly run a given block of code a certain number of times. It has three optional arguments, the initializer, the conditional statement, and the incremental or decremental expression. To increment by 2 in a for loop, use the βi += 2β as a final or incremental expression statement. This article described the for loopβs increment statement by 2.