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: orangeChallenge
EasyWrite 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 belowThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Type Coercion7Bill Split Calculator
Welcome MessageCalculating The Tip And Total2Variables
NumbersStringBooleanNaming ConventionsEmpty VariablesRecap - Initialize VariablesConstants3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsStrict vs Loose EqualityRecap - Simple Math6Basic IO
OutputOutput with VariablesType Conversion - Part 1Type Conversion - Part 2Recap - Till 120Recap - True or False9Functions
Declare a FunctionArgumentsReturnRecap - Sigma FunctionFunction ExpressionDefault ParametersArrow FunctionsRecap - Validation Function12Arrays Part 2
Iterating Over ArraysThe forEach Methodfor...of LoopRecap - P CounterArray SlicingArray Methods Part 3Array Methods Part 4Membership Testing