In this article we are going to understand the map method in javascript which highly used.
In JavaScript, the map()
method is a higher-order function available for arrays. It's used to apply a given function to each element of an array and creates a new array containing the results without modifying the original
let newArray = array.map(callback(currentValue) {
// return element for newArray, after executing something
});
array
: The original array that you want to operate on.callback
: Function to execute on each element in the array, taking in three arguments:currentValue
: The current element being processed in the array.
It has some more options what they are optional and most of the time we not use them.
// Define a function to double each number
function doubleNumber(num) {
return num * 2;
}
// Original array
let numbers = [1, 2, 3, 4, 5];
// Using map() to double each number in the array using the function
let doubledNumbers = numbers.map(doubleNumber);
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
map()
in JavaScript creates a new array by applying a provided function to each element of the original array, returning a transformed array without modifying the original one. It's a powerful method often used for data transformation and manipulation in JavaScript.
// Array of names
let names = ["Alice", "Bob", "Charlie", "David"];
// Using map() to get the lengths of each name
let nameLengths = names.map(name => name.length);
console.log(nameLengths); // Output: [5, 3, 7, 5]
The
names
array contains strings.The
map()
method is applied to thenames
array, using an arrow functionname => name.length
as the callback function.The callback function takes each
name
in the array and returns its length using thelength
property, effectively creating a new arraynameLengths
containing the lengths of each name in the original array.
Thank you for reading my content. Be sure to follow and comment on what you want me to write about next
🤓
Subscribe to our newsletter
Read articles from directly inside your inbox. Subscribe to the newsletter, and don't miss out.