- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- Array concat() method
- Array indexOf()
- Array length
- Array pop()
- Array shift
- Arrays
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Comment
- Conditions
- Console
- Constructor
- Creating a p element
- Data types
- Date getTime()
- Destructuring
- Else
- Else if
- Enum
- Equals operator
- Error Handling
- ES6
- Event loop
- Events
- Extend
- Fetch API
- Filter
- For loop
- forEach()
- Function
- Function bind()
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- includes()
- Infinity property
- Iterator
- JSON
- Less than
- Local storage
- Map
- Methods
- Module
- Numbers
- Object.keys()
- Overriding methods
- Parameters
- Promises
- Random
- Reduce
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- Sort
- Splice
- String
- String concat()
- String indexOf()
- Substring
- Switch statement
- Template literals
- Ternary operator
- Tile
- Type conversion
- While loop
JAVASCRIPT
JavaScript forEach(): Syntax, Usage, and Examples
The forEach()
method in JavaScript provides a clean, readable way to loop through elements in an array. It's one of the most commonly used iteration methods in modern JavaScript development. The JavaScript forEach method executes a provided function once for each array element, allowing you to work with data without writing traditional for
or while
loops.
How to Use JavaScript forEach
The forEach()
method works on arrays and array-like structures. The syntax looks like this:
array.forEach(function(currentValue, index, array) {
// Your code here
});
You can also use an arrow function for brevity:
array.forEach((currentValue, index, array) => {
// Your code here
});
Parameters:
- currentValue – Required. The current element being processed.
- index – Optional. The index of the current element.
- array – Optional. The array that
forEach()
is being called on.
Basic Example:
const fruits = ["apple", "banana", "cherry"];
fruits.forEach((fruit) => {
console.log(fruit);
});
This prints each fruit to the console—one per line.
When to Use forEach JavaScript
Use the JavaScript forEach method when you need to:
Perform Side Effects for Each Item in an Array
forEach is ideal when you want to log data, update the DOM, or perform other side effects. It doesn’t return a value, so don’t use it when you need to create a new array.
const users = ["Alice", "Bob", "Charlie"];
users.forEach((user) => {
console.log(`Welcome, ${user}!`);
});
Loop Over an Array Without Managing Indexes Manually
Unlike traditional loops, you don’t need to declare counters or check lengths manually:
const scores = [92, 85, 74];
scores.forEach((score, index) => {
console.log(`Score #${index + 1}: ${score}`);
});
This makes code shorter and easier to read.
Work with JavaScript Arrays Functionally
forEach provides a functional programming pattern. It’s not as powerful as map()
or filter()
, but it’s perfect when you want to apply logic to each item without changing the original array.
Examples of JavaScript forEach Loop in Practice
Looping Over a JavaScript Array
const colors = ["red", "green", "blue"];
colors.forEach((color) => {
document.body.style.backgroundColor = color;
});
This changes the background color sequentially (only the last color will persist).
Using Index and Original Array
const names = ["John", "Jane", "Jim"];
names.forEach((name, index, arr) => {
console.log(`${name} is at position ${index} in [${arr}]`);
});
forEach gives access to all the context you might need.
JavaScript Array forEach with Objects
const students = [
{ name: "Emma", grade: "A" },
{ name: "Liam", grade: "B" }
];
students.forEach((student) => {
console.log(`${student.name} received grade ${student.grade}`);
});
This is useful when looping through arrays of objects.
Learn More About the forEach Loop in JavaScript
JavaScript forEach Index Handling
You can always access the current index through the second parameter:
const cities = ["Paris", "Tokyo", "Sydney"];
cities.forEach((city, index) => {
console.log(`City ${index + 1}: ${city}`);
});
This is helpful for numbered lists or position-based logic.
Using forEach Loop in JavaScript with Conditional Logic
const numbers = [5, 10, 15, 20];
numbers.forEach((num) => {
if (num > 10) {
console.log(`${num} is greater than 10`);
}
});
You can apply any if
/else
logic directly inside the callback.
Using continue
in JavaScript forEach
Unlike traditional loops, you can't use continue
inside forEach()
. Instead, simulate it with return
inside the callback:
const animals = ["cat", "", "dog"];
animals.forEach((animal) => {
if (!animal) return;
console.log(animal);
});
The return
skips over the current iteration without stopping the entire loop.
forEach vs Map in JavaScript
Use forEach()
when you're executing side effects and don’t need to return anything. Use map()
when you want to create a new array:
// forEach
const names = ["Anna", "Ben"];
names.forEach((name) => console.log(name.toUpperCase()));
// map
const upperNames = names.map((name) => name.toUpperCase());
console.log(upperNames); // ["ANNA", "BEN"]
They serve different purposes. Choosing between them depends on your intent.
forEach on Objects
JavaScript forEach
doesn’t work directly on plain objects. To loop through object properties, use Object.keys()
or Object.entries()
:
const person = { name: "Alex", age: 30 };
Object.entries(person).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
This makes it behave similarly to iterating over a key-value map.
JavaScript Map forEach
If you're working with a Map
object instead of an array, Map.prototype.forEach()
works slightly differently:
const capitals = new Map([
["France", "Paris"],
["Japan", "Tokyo"]
]);
capitals.forEach((value, key) => {
console.log(`${key}'s capital is ${value}`);
});
Notice how the callback parameters are value, key
, unlike arrays which use element, index
.
forEach and Arrow Functions
Arrow functions work great with forEach for cleaner code:
[1, 2, 3].forEach((num) => console.log(num));
But remember, arrow functions don’t bind their own this
, so if you rely on this
inside the loop, use a regular function or bind manually.
Error Handling with forEach
Wrap the logic inside the callback with a try-catch block to handle exceptions:
data.forEach((item) => {
try {
riskyFunction(item);
} catch (error) {
console.error("Error processing item:", error);
}
});
This prevents one bad item from crashing the entire loop.
The JavaScript forEach method is a convenient way to iterate over arrays and apply logic to each item. Whether you're looping over data for display, executing side effects, or processing arrays of objects, foreach JavaScript syntax keeps your code concise and readable. It doesn’t return a new array like map()
, but it excels when the goal is to act on data directly.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.