how to print even numbers in javascript using for loop

To print even numbers in JavaScript using a for loop, you can use the for loop to iterate over the numbers from 2 to a given number, and print the values that are divisible by 2. Here are a few examples of different ways to print even numbers in JavaScript:

Example 1: Using a for loop and if statement

how to print even numbers in javascript using for loop
how to print even numbers in javascript using for loop

In this example, the variable limit is set to 10, which is the highest number you want to print. The for loop starts by declaring a variable i and setting its value to 2. The loop then continues to run as long as i is less than or equal to limit. On each iteration of the loop, the i variable is incremented by 1.

The if statement is used to check if i is divisible by 2 by using the modulo operator % and the equality operator ==. If i is divisible by 2, the console.log method is used to print the value of i.

This example will output the following:

how to print even numbers in javascript using for loop
how to print even numbers in javascript using for loop

Example 2: Using a for loop and continue statement

how to print even numbers in javascript using for loop
how to print even numbers in javascript using for loop

In this example, the for loop is similar to the first example, except the i variable is incremented by 2 on each iteration of the loop instead of 1. This means that only even numbers will be printed.

This example will output the following:

how to print even numbers in javascript using for loop
how to print even numbers in javascript using for loop

Both examples will print even numbers from 2 to the limit specified in the limit variable. The first example uses an if statement to check if a number is even, while the second example increments the i variable by 2 on each iteration of the loop to only print even numbers.

By umarbwn