Map method explain in javascript!

Pradip Chaudhary
2 min readJan 17, 2023

--

The map() method in JavaScript is a function that is used to create a new array with the results of calling a provided function on every element in the calling array. The new array will have the same number of elements as the original array.

Map method

Syntax:

array.map(function(currentValue, index, array) {
// code to be executed
});

Here, currentValue is the current element being processed in the array, index is the index of the current element, and array is the array the map() method was called upon.

For example, let’s say you have an array of numbers and you want to create a new array with the squares of those numbers:

let numbers = [1, 2, 3, 4];
let squares = numbers.map(function(number) {
return number * number;
});
console.log(squares);

This will output [1, 4, 9, 16]

In ES6, the map() method can also be written using arrow functions:

let numbers = [1, 2, 3, 4];
let squares = numbers.map(number => number * number);
console.log(squares);

It is also possible to use map method with map function to map the key value pairs and return the new set of key value pairs.

Please note that the map() method does not modify the original array, it creates and returns a new one.

--

--

Pradip Chaudhary

Full-stack Software Developer and Javascript Enthusiast, Who Loves Building Things In Javascript. 🔥 👨🏽‍💻🏅