JavaScript

How to Increment by 2 in for Loop in JavaScript

Most programs need to repeatedly execute code unless an end condition is satisfied. Loops are used in programming languages to repeat a block of code. The code block is iterated by using β€œfor”, β€œwhile”, or β€œdo-while” loops in JavaScript. The three basic looping structures in JavaScript are the β€œblock” or the body of the loop, the β€œcondition”, and the β€œlooping keyword”, such as for, while, and so on.

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:

for (var i = 0; i < 10; i += 2){
 // 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:

for (var i = 0; i < 10; i += 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:

var array = [1,2,3,4,5,6,7,8,9,10]

Here, iterate the loop over an array until its length, incrementing by 2:

for (var i = 0; i < array.length; i += 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.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.