Learn how to use the forEach method in JS!
source link: https://dev.to/ziratsu/learn-how-to-use-the-foreach-method-in-js-3im
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
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);
});
Enter fullscreen mode
Exit fullscreen mode
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>
Enter fullscreen mode
Exit fullscreen mode
In your JS file, select the buttons:
const buttons = document.querySelectorAll('button');
Enter fullscreen mode
Exit fullscreen mode
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'))
})
});
Enter fullscreen mode
Exit fullscreen mode
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.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK