JavaScript map() Method
The map()
method in JavaScript is used to create a new array by applying a function to each element of the original array. It iterates through each element of the array and invokes a callback function for each element. The result of the callback function is then added to the new array.
Syntax:
arr.map(function(args){
...
})
Example: Using JavaScript’s map() Method to Update Array Elements
The code initializes an array arr
with values [2, 4, 8, 10]. The map()
method is then used to create a new array updatedArr
where each element of arr
is incremented by 2. Both the original and updated arrays are logged to the console.
let arr= [2,4,8,10]
let updatedArr = arr.map(val=> val+2)
console.log(arr);
console.log(updatedArr);
Output
[ 2, 4, 8, 10 ] [ 4, 6, 10, 12 ]