Master JavaScript ForEach: Practical Example Guide

The 'foreach' loop in JavaScript is a simple yet powerful concept that allows you to traverse through arrays, objects, or even DOM elements. It's particularly useful when you need to perform an operation on each item of a collection, making it a staple in any JavaScript developer's toolbox.

JavaScript Array forEach(): Looping Over an Array
JavaScript Array forEach(): Looping Over an Array

In this article, we'll delve into the world of JavaScript's 'foreach' loop with practical examples, exploring its usage, syntax, and real-world applications.

What is β€œforEach()” Method in JavaScript? (With Examples)
What is β€œforEach()” Method in JavaScript? (With Examples)

Understanding the 'foreach' Loop

At its core, 'foreach' is an iteration statement that you can use to loop through the elements of an object. It's a simpler and more readable alternative to the traditional 'for' loop in many situations.

JavaScript Cheatsheet for Beginners | Learn JS Fast (One-Page Guide)
JavaScript Cheatsheet for Beginners | Learn JS Fast (One-Page Guide)

'foreach' iterates over each element of an array or each key-value pair of an object, executing a provided function (or block of code) for every element or pair.

Syntax of 'foreach' Loop

HTML,CSS JAVASCRIPT cheatsheet
HTML,CSS JAVASCRIPT cheatsheet

The syntax for the 'foreach' loop is straightforward. Here's how you use it with an array and an object:

  • array.forEach(callback(currentValue, index, array), thisValue)
  • Object.entries(object).forEach(callback([key, value], index, array), thisValue)

'foreach' Loop Example with Array

How to Create a Function in JavaScript: Step-by-Step Guide πŸš€
How to Create a Function in JavaScript: Step-by-Step Guide πŸš€

Let's start with a simple example. Suppose we have an array of numbers, and we want to multiply each number by 2:

First, we declare our array:

const numbers = [1, 2, 3, 4, 5];

Next, we use the 'foreach' loop to multiply each number by 2:

Javascript Cheet cheet
Javascript Cheet cheet

numbers.forEach((number, index, array) => {
  console.log(number * 2);
});

This will log the following output to the console: '2', '4', '6', '8', '10'.

Using 'foreach' with Objects

10 JavaScript Concepts Every Beginner Must Know (Save This Cheat Sheet!)
10 JavaScript Concepts Every Beginner Must Know (Save This Cheat Sheet!)
The JavaScript Cheat Sheet Every Beginner Wishes They Had
The JavaScript Cheat Sheet Every Beginner Wishes They Had
JavaScript Arrow Functions: Write Shorter & Cleaner Code πŸš€
JavaScript Arrow Functions: Write Shorter & Cleaner Code πŸš€
JavaScript Arrays: Some(), Every(), and forEach()
JavaScript Arrays: Some(), Every(), and forEach()
JavaScript Full Notes Every Beginner Must Save πŸ’‘
JavaScript Full Notes Every Beginner Must Save πŸ’‘
Map vs forEach in JavaScript
Map vs forEach in JavaScript
Javascript Fundamental
Javascript Fundamental
3 Ways to Define Functions in JavaScript
3 Ways to Define Functions in JavaScript
an image of a flow diagram with two different types of loops and loops on it
an image of a flow diagram with two different types of loops and loops on it
Break from foreach Javascript Techniques To Use
Break from foreach Javascript Techniques To Use
JavaScript | Chapter 2 πŸ“–| Part 1 ✨
JavaScript | Chapter 2 πŸ“–| Part 1 ✨
Functions in Javascript
Functions in Javascript
JavaScript Methods: Add Functionality to Your Objects πŸš€
JavaScript Methods: Add Functionality to Your Objects πŸš€
JavaScript Basics You MUST Know
JavaScript Basics You MUST Know
JavaScript Logical Operators: Master &&, ||, and ! for Smarter Code πŸ€–
JavaScript Logical Operators: Master &&, ||, and ! for Smarter Code πŸ€–
JavaScript Basics | Chapter 1 πŸ“– | Part 2
JavaScript Basics | Chapter 1 πŸ“– | Part 2
8 Essential JavaScript Array Methods Visual Guide
8 Essential JavaScript Array Methods Visual Guide
an info sheet with different types of web pages
an info sheet with different types of web pages
an image of a programming program with the text'codezhunt'on it
an image of a programming program with the text'codezhunt'on it
Javascript Functions Javascript Infographic, Javascript Functions List, Javascript Guide To Functions, Javascript Function Types, How To Write Javascript Functions, Javascript Function Expression, Javascript Functions Tutorial, Javascript Functions, Javascript Function Syntax
Javascript Functions Javascript Infographic, Javascript Functions List, Javascript Guide To Functions, Javascript Function Types, How To Write Javascript Functions, Javascript Function Expression, Javascript Functions Tutorial, Javascript Functions, Javascript Function Syntax

'foreach' can also be used to iterate over the key-value pairs of an object. Let's illustrate this with an example:

Iterating Over Object's Key-Value Pairs

Suppose we have an object containing user data, and we want to display each user's name and age:

First, we declare our object:

const users = {
  user1: { name: 'Alice', age: 30 },
  user2: { name: 'Bob', age: 25 },
  user3: { name: 'Charlie', age: 35 }
};

Next, we use 'Object.entries' and 'foreach' to iterate over the key-value pairs:

Object.entries(users).forEach(([key, value]) => {
  console.log(`User ${key} is ${value.name}, ${value.age} years old.`);
});

This will display the following output: 'User user1 is Alice, 30 years old.', 'User user2 is Bob, 25 years old.', 'User user3 is Charlie, 35 years old.'

='foreach' with the DOM

'foreach' is also useful when working with the DOM. It allows you to iterate over a list of DOM elements, performing an operation on each one. For example, let's select all paragraph elements on a page and change their color:

Iterating Over DOM Elements

First, we select all paragraph elements on the page:

const paragraphs = document.querySelectorAll('p');

Next, we use 'foreach' to iterate over each paragraph and change its color:

paragraphs.forEach((paragraph) => {
  paragraph.style.color = 'blue';
});

This will change the color of all paragraph text on the page to blue.

As you can see, the 'foreach' loop is a versatile and powerful tool in your JavaScript toolbox. It simplifies iteration, makes your code more readable, and can help you work more efficiently with arrays, objects, and even the DOM.

Happy coding! Now that you understand and have seen the 'foreach' loop in action, why not explore other JavaScript iteration statements or try using 'foreach' in your own projects? The possibilities are endless!

Related Articles

Fireball Tutorial Line Dance W3schools Javascript Get Url Parameters W3schools Javascript Object Properties Youtube Eye Makeup Tutorial For Brown Eyes Youtube Capcut Tutorial For Beginners W3schools Javascript This W3s Javascript Dom Enum Javascript Example Difference Between Queryselector And Queryselectorall W3schools Foreach Js