The
forEach()
method is a built-in function in JavaScript that executes a provided function once for each element in an array. It's a versatile tool for iterating through arrays and performing operations on each element.
JavaScript’s forEach()
function takes a callback as a parameter, and calls that callback for each element of the array. It calls the callback with the value as the first parameter and the array index as the 2nd parameter.
// Prints "0: a, 1: b, 2: c"
['a', 'b', 'c'].forEach(function callback(value, index) {
console.log(`${index}: ${value}`);
});
forEach()
is a method on JavaScript arrays, not objects. To iterate over an object, you must turn it into an array using Object.entries(), Object.keys(), or Object.values()
. After that, you can then use forEach()
to iterate through the keys, values, or entries:
const obj = {
name: 'Jean-Luc Picard',
rank: 'Captain'
};
// Prints "name Jean-Luc Picard" followed by "rank Captain"
Object.keys(obj).forEach(key => {
console.log(key, obj[key]);
});
const obj = {
name: 'Jean-Luc Picard',
rank: 'Captain'
};
// Prints "Jean-Luc Picard" followed by "Captain"
Object.values(obj).forEach(val => {
console.log(val);
});
const obj = {
name: 'Jean-Luc Picard',
rank: 'Captain'
};
// Prints "name Jean-Luc Picard" followed by "rank Captain"
Object.entries(obj).forEach(entry => {
const [key, value] = entry;
console.log(key, value);
});
This way, you have understood how to use forEach() with key value pairs
#javascript #programming #developer