Menu
Coddy logo textTech

The forEach Method

Part of the Fundamentals section of Coddy's JavaScript journey — lesson 64 of 77.

The forEach method allows you to loop through a sequence (like an array) while keeping track of each item.

Without forEach we would access both the index and the value the following way:

let fruits = ["apple", "banana", "orange"];
for (let i = 0; i < fruits.length; i++) {
    console.log(`Index ${i}: ${fruits[i]}`);
}

forEach is a more elegant way to get both index and value:

let fruits = ["apple", "banana", "orange"];
fruits.forEach((fruit, index) => {
    console.log(`Index ${index}: ${fruit}`);
});

Both examples will output:

Index 0: apple
Index 1: banana
Index 2: orange
challenge icon

Challenge

Easy

Write a program that receives an array of numbers as input (given), and prints an array of the numbers that are either below 50 or are divisible by 5. Use the forEach method.

Cheat sheet

The forEach method allows you to loop through an array while keeping track of each item and its index:

let fruits = ["apple", "banana", "orange"];
fruits.forEach((fruit, index) => {
    console.log(`Index ${index}: ${fruit}`);
});

This is more elegant than using a traditional for loop:

for (let i = 0; i < fruits.length; i++) {
    console.log(`Index ${i}: ${fruits[i]}`);
}

Try it yourself

let arr = inp.split(",").map(Number); // Don't change this line

// Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals