Everything About JavaScript forEach() Loop Method
JavaScript forEach()
method provides another way to loop an iterable object (like arrays).
The forEach method uses callback functions to deal with each iteration.
It uses callbacks, but that does not mean it is inherently asynchronous.
Also, it can’t use JavaScript’s Break and Continue statements.
Let’s jump right in.
1. JavaScript forEach - Basic Examples
These examples will answer the question ”how to use foreach in javascript?”. Expected results are shown as comments.
1.1. Basic Example - Logging Array Elements
["a", "b", "c"].forEach((element) => console.log(element));
// a
// b
// c
It that example, we simply created an Array and directly iterated it using the forEach
method. It will simply log each element per line in the console.
1.2. DOM Example - Logging NodeList Elements
The forEach method does not only work with Array. NodeList objects also have .forEach()
.
document.querySelectorAll("div").forEach((element) => console.log(element));
// all div elements will get logged per line
This example logs all div
elements of the page per line on the console.
1.3. Basic Indices - Logging Array Index and Element
In the above examples we have logged only the element, but what about indices?
["a", "b", "c"].forEach((element, index) => console.log(index, element));
// 0 a
// 1 b
// 2 c
1.4. Object Example - Logging Key and Value of Object
JavaScript object foreach. In this example, we will take a simple object and log its keys and values per line.
Main Problem: Objects are not directly iterable. Firstly we have to make an array of object keys using Object.keys()
.
const theObject = {
programmer: "Aaryan",
level: "intermediate",
years: 3.5,
};
Object.keys(theObject).forEach((key) =>
console.log(`${key}: ${theObject[key]}`)
);
// programmer: Aaryan
// level: intermediate
// years: 3.5
2. JavaScript forEach - Questions
Here the most asked question concerning the JavaScript forEach method.
2.1. How to use foreach in javascript?
Any array or iterable object has a .forEach()
method, which you can use for loops. For better understanding look the above use-cases.
2.2. How to break the foreach loop in javascript?
The answer is, you can’t break the forEach
loop in JavaScript.
The best you can do is, use a return
statement to skip an iteration.
If you really want to break the loop, use the classic JavaScript for loop.
2.3. What is the difference between for and foreach in javascript?
Here’s for vs forEach loop.
const array = [10, 20, 30];
/**
* Iterating with classic for loop
* You can use `break` or `continue`
*/
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
// 10
// 20
// 30
/**
* Iterating with forEach loop
* You CAN NOT use `break` or `continue`
*/
array.forEach((element) => console.log(element));
// 10
// 20
// 30
3. JavaScript forEach - Practical Uses
There are endless possibilities of practical uses for the forEach method. We’ll look at the most requested use cases.
3.1. Appending items to a List in DOM
Here we are appending JavaScript LI
in UL
or OL
.
const items = ["James", "Mary", "Henry"];
const list = document.getElementById("list"); // could be any element id or selector
items.forEach((item) => {
const node = document.createElement("LI"); // creates a List Item element
node.innerText = item; // sets the created element's innerText to current item
list.appendChild(node); // appens the element to the list
});
3.2. How to catch an Error in a foreach loop?
You can actually catch errors using;
- Classic Try/Catch block. This can stop the ongoing operation though.
- Make an Array of errors. This way you can keep the process going, but also keeping track of possible errors.
Both have appropriate use cases.
Conclusion
The JavaScript forEach method is a really great way to loop any iterable object. It provides syntactic sugar to beautify our code.
However, it uses callbacks and hence can’t use break
or continue
statements as pointed out in the example.