JavaScript Array map
Method (Live Playground)
The map
method in JavaScript creates a new array with the results of calling a provided function on every element in the array.
Here's an example:
let numbers = [1, 2, 3, 4, 5];
let squares = numbers.map(function (number) {
return number * number;
});
console.log(squares);
// Expected output: [1, 4, 9, 16, 25]
In this example, numbers.map(function(number) { return number * number; })
returns a new array where each element is the square of the corresponding element in the numbers
array.
Live Playground, Try it Yourself
The map
method does not change the original array. Instead, it returns a new array. For instance, if we console.log the numbers
array, we will see that it remains the same:
console.log(numbers);
// Expected output: [1, 2, 3, 4, 5]
Live Playground, Try it Yourself
The map
method is a handy tool when you need to apply the same operation to every element of an array and create a new array with the results.
Remember to practice using the map
method with different examples!