Jump to content

How to Increment by 2 in for Loop in JavaScript


Recommended Posts

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

in-for-Loop-in-JavaScript-1.png

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:

in-for-Loop-in-JavaScript-2.png

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.

View the full article

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...