| by Arround The Web | No comments

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.

Share Button

Source: linuxhint.com

Leave a Reply