Fetch alternative even values from a JavaScript array?

To fetch alternative even values from a JavaScript array, you need to iterate through the array and check if the index is even using the modulo operator. An index is even when index % 2 == 0.

Syntax

if (index % 2 == 0) {
    // This will select elements at even positions (0, 2, 4, ...)
}

Example

The following example demonstrates how to fetch alternative even values from an array:

var subjectsName = ["MySQL", "JavaScript", "MongoDB", "C", "C++", "Java"];

for (let index = 0; index 

Output

Subject name at even position = MySQL
Subject name at even position = MongoDB
Subject name at even position = C++

Using filter() Method

You can also use the filter() method with index parameter to achieve the same result:

var subjectsName = ["MySQL", "JavaScript", "MongoDB", "C", "C++", "Java"];

var evenPositionElements = subjectsName.filter((element, index) => index % 2 == 0);

console.log("Elements at even positions:");
evenPositionElements.forEach(element => console.log(element));

Output

Elements at even positions:
MySQL
MongoDB
C++

How It Works

The modulo operator % returns the remainder of division. When index % 2 equals 0, it means the index is divisible by 2, making it an even position. Array indices start from 0, so positions 0, 2, 4, etc. are considered even positions.

Conclusion

Use index % 2 == 0 condition in loops or the filter() method to extract elements at even positions. This technique is useful for processing every alternate element in an array.

Updated on: 2026-03-15T23:19:00+05:30

310 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements