forEach()
The forEach() method executes a function once for each element in an array.
It is mainly used when you want to perform an action, such as printing values, updating the UI, or making API calls.
array.forEach(function(element, index, array) {
// code
});
element → Current array element
index → Position of the current element
array → Original array
Example 1: Print All Elements
let fruits = ["Apple", "Mango", "Orange"];
fruits.forEach(function(fruit) {
console.log(fruit);
}); // Output:
Apple
Mango
Orange
Example 2: Using Index
let fruits = ["Apple", "Mango", "Orange"];
fruits.forEach(function(fruit, index) {
console.log(index + " : " + fruit);
}); // Output:
0 : Apple
1 : Mango
2 : Orange
forEach() does not return a new array.
let numbers = [1, 2, 3];
let result = numbers.forEach(num => num * 2);
console.log(result); // Output: undefined
map()
The map() method creates a new array by applying a function to every element of the original array.
It is mainly used when you want to modify or transform array elements.
array.map(function(element, index, array) {
return newValue;
});
element → Current array element
index → Position of the current element
array → Original array
Example 1: Double Every Number
let numbers = [1, 2, 3, 4];
let doubled = numbers.map(functio
n(num) {
return num * 2;
});
console.log(doubled); // Output:
[2, 4, 6, 8]
Original Array vs New Array
let numbers = [1, 2, 3];
let doubled = numbers.map(num => num * 2);
console.log(numbers);
console.log(doubled); // Output:
[1, 2, 3]
[2, 4, 6]
Notice that map() does not change the original array. Instead, it returns a new array.
Top comments (0)