This content originally appeared on DEV Community and was authored by Ustariz Enzo
Hey fellow creators,
The forEach method is really handy when you’re working with arrays or nodelists.
It allows you to run a callback function for each element in those containers.
Let’s learn how to use it in less than a minute!
If you prefer to watch the video version, it's right here :
1. How to use it.
To use it, you need to feed it with a callback function, which can take up to three parameters.
Those parameters are:
- The current value
- The index
- And the array/nodelist that you’re working with.
const array = [1, 2, 3];
array.forEach((current, index, arr) => {
console.log(current, index, arr);
});
Take a look in your console/terminal and you’ll see:
2. Let’s create three buttons to have a real example.
In an HTML file, create three buttons:
<button data-action="modify">Modify</button>
<button data-action="delete">Delete</button>
<button data-action="update">Update</button>
In your JS file, select the buttons:
const buttons = document.querySelectorAll('button');
The .queryAll method returns a nodelist, and the nodelists also have access to the forEach method in their prototype.
Thus, we can use it to attach an event listener to each button :
buttons.forEach(btn => {
btn.addEventListener('click', (e) => {
alert(e.target.getAttribute
('data-action'))
})
});
This is a basic example but you now know how useful this method is!
You can easily avoid code repetition.
Come and take a look at my Youtube channel: https://www.youtube.com/c/Learntocreate/videos
See you soon!
Enzo.
This content originally appeared on DEV Community and was authored by Ustariz Enzo
Ustariz Enzo | Sciencx (2021-12-20T09:23:06+00:00) Learn how to use the forEach method in JS!. Retrieved from https://www.scien.cx/2021/12/20/learn-how-to-use-the-foreach-method-in-js/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.