forEach()
The forEach() method calls a function (a callback function) for each array element.
The forEach() method is available on arrays and allows you to execute a provided function once for each array element.
This method is particularly useful for side effects or when you don't need to create a new array based on the original one.
The callback function automatically receives three arguments:
Here,
i → Current value
j → Current index
k → Complete array
const numbers=[20,40,60,54,10];
function greet(i,j,k){
console.log("Numbers",i,j,k )
}
numbers.forEach(greet);
OUTPUT:
Numbers 20 0 [ 20, 40, 60, 54, 10 ]
Numbers 40 1 [ 20, 40, 60, 54, 10 ]
Numbers 60 2 [ 20, 40, 60, 54, 10 ]
Numbers 54 3 [ 20, 40, 60, 54, 10 ]
Numbers 10 4 [ 20, 40, 60, 54, 10 ]
forEach() accepts a callback function as an argument.
It calls that function once for each array element.
It does not return a new array or a function.
const numbers=[20,40,60,54,10];
function greet(i,j,k){
console.log("Numbers",i);
return i*2;
}
const forEachReturn=numbers.forEach(greet);
console.log(forEachReturn);
OUTPUT:
Numbers 20
Numbers 40
Numbers 60
Numbers 54
Numbers 10
undefined
Map()
The map() method creates a new array by performing a function on each array element.
The map() method does not execute the function for array elements without values.
The map() method does not change the original array.
It returns the new array.
const numbers=[20,40,60,54,10];
function greet(i,j,k){
console.log("Numbers",i,j,k);
return i*2;
}
const mapReturn=numbers.map(greet);
console.log(mapReturn);
OUTPUT:
Numbers 20 0 [ 20, 40, 60, 54, 10 ]
Numbers 40 1 [ 20, 40, 60, 54, 10 ]
Numbers 60 2 [ 20, 40, 60, 54, 10 ]
Numbers 54 3 [ 20, 40, 60, 54, 10 ]
Numbers 10 4 [ 20, 40, 60, 54, 10 ]
[ 40, 80, 120, 108, 20 ]
Top comments (0)