10 Quick JavaScript forEach Examples for Mastery

Javascript

The Javascript forEach loop is a powerful tool in JavaScript that allows you to iterate over arrays and perform a specific action for each element. This loop is similar to the for loop, but it’s more concise and easier to read. In this article, we’ll take a closer look at the forEach loop and cover 10 practical examples of how to use it.

Basic Syntax

The basic syntax of the forEach loop is as follows:

array.forEach(function(element, index) {
    // code to be executed for each element
});

The forEach method accepts a single argument, which is a callback function that will be executed for each element in the array. The callback function takes two arguments: the current element and its index. You can checkout the official docs for more info.

Example 1: Logging each element to the console

The simplest use case for the forEach loop is to log each element of an array to the console.

let numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(element) {
    console.log(element);
});

This code will log each number in the numbers array to the console.

Example 2: Summing up all elements

Another common use case is to sum up all elements of an array.

let numbers = [1, 2, 3, 4, 5];
let sum = 0;
numbers.forEach(function(element) {
    sum += element;
});
console.log(sum);

This code will calculate the sum of all elements in the numbers array and log it to the console.

Example 3: Modifying each element

You can also use the forEach loop to modify each element of an array.

let numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(element, index) {
    numbers[index] = element * 2;
});
console.log(numbers);

This code will double each number in the numbers array and log the modified array to the console.

Example 4: Filtering an array

The forEach loop can also be used to filter an array.

let numbers = [1, 2, 3, 4, 5];
let evenNumbers = [];
numbers.forEach(function(element) {
    if (element % 2 === 0) {
        evenNumbers.push(element);
    }
});
console.log(evenNumbers);

This code will filter out all odd numbers from the numbers array and log the even numbers to the console.

Example 5: Removing an element

You can also use the forEach loop to remove an element from an array.

let numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(element, index) {
    if (element === 3) {
        numbers.splice(index, 1);
    }
});
console.log(numbers);

This code will remove the element with the value of 3 from the numbers array and log the modified array to the console.

Example 6: Creating a new array

You can also use the forEach loop to create a new array from an existing one.

let numbers = [1, 2, 3, 4, 5];
let squareNumbers = [];
numbers.forEach(function(element) {
    squareNumbers.push(element * element);
});
console.log(squareNumbers);

This code will create a new array called squareNumbers that contains the square of each number in the numbers array and log the new array to the console.

Example 7: Using Javascript forEach with arrow function

You can also use an arrow function as a callback function for the forEach loop.

let numbers = [1, 2, 3, 4, 5];
numbers.forEach((element) => console.log(element));

This is equivalent to the first example, but the callback function is written in a shorter form.

Example 8: Using the forEach as an object property

You can also use the forEach loop as object property

let numbers = [1, 2, 3, 4, 5];
let obj = {
    numbers: numbers,
    multiplyByTwo: function() {
        this.numbers.forEach(function(element) {
            console.log(element * 2);
        });
    }
};
obj.multiplyByTwo();

In this example, we defined an object called obj with a property called numbers and a method called multiplyByTwo. Inside the method, we used the forEach loop to iterate over the numbers property and multiply each element by two.

Example 9: Javascript forEach with objects

The forEach loop can also be used with objects.

let obj = {
    a: 1,
    b: 2,
    c: 3
};
Object.keys(obj).forEach(function(key) {
    console.log(obj[key]);
});

This code will extract all the keys of the object and iterate over them using the forEach loop and log the values of the object to the console.

Example 10: Using Javascript forEach with the map method

You can also use the forEach loop in conjunction with the map method.

let numbers = [1, 2, 3, 4, 5];
let squareNumbers = numbers.map(function(element) {
    return element * element;
});
squareNumbers.forEach(function(element) {
    console.log(element);
});

In this example, we first use the map method to create a new array of square numbers, then we use the forEach loop to log each element of the new array to the console.

In conclusion, the forEach loop is a powerful tool in JavaScript that allows you to iterate over arrays and perform specific actions for each element. It’s a great alternative to the traditional for loop, and it’s easy to read and understand. By mastering the forEach loop and understanding the examples in this article, you’ll be able to write more efficient and effective code.

Leave a Reply

Your email address will not be published. Required fields are marked *

0 Comments