Back to JavaScript
2026-04-277 min read

ES6 Array map() (JavaScript)

Learn ES6 Array map() (JavaScript) step by step with clear examples and exercises.

Why This Matters

In programming, transforming an array's elements is a frequent task, such as applying a function to each element or creating a new array based on existing data. The map() method in JavaScript, introduced with ES6, makes this process more efficient and readable. Understanding its usage will help you solve real-world coding challenges and impress interviewers.

Importance of map()

  1. Improved performance: Using map() can be more efficient than manually looping through an array and modifying each element, as it avoids mutating the original data structure.
  2. Readability: The map() method provides a concise and readable way to transform arrays, making your code easier to understand for other developers.
  3. Reusable logic: By encapsulating transformation logic within functions passed to map(), you can easily reuse these functions in other parts of your application.
  4. Functional programming: The map() function is a key concept in functional programming, which emphasizes immutable data structures and the composition of pure functions.

Prerequisites

Before diving into the map() function, ensure you have a good understanding of:

  1. Basic JavaScript concepts: variables, data types, operators, control structures (if/else, loops)
  2. ES6 syntax: let and const, arrow functions, template literals, destructuring assignment
  3. Arrays in JavaScript: creating arrays, accessing elements, array methods like filter(), reduce()
  4. Understanding of first-class functions in JavaScript
  5. Familiarity with higher-order functions (functions that take other functions as arguments or return them)

Core Concept

The map() method creates a new array with the results of calling a provided function on every element in the original array. It doesn't modify the original array and is often used for tasks like transforming data structures, filtering arrays, or creating copies with modified elements.

Syntax

array.map(function callback(currentValue, index, arr), thisValue)
  • callback: a function that takes three arguments (current element, its index, the array itself).
  • thisValue (optional): an object to bind as the this value within the callback.

Example

Let's create a simple example where we double each number in an array using the map() function:

const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(num => num * 2);
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]

In this example, we define an array numbers, create a new array doubledNumbers using the map() method, and double each number in the original array. The console.log() function displays the resulting array.

Creating Custom map() Function

Although JavaScript provides a built-in map() method for arrays, you can also create your own custom implementation:

Array.prototype.myMap = function(callback) {
const newArray = [];
for (let i = 0; i < this.length; i++) {
newArray.push(callback(this[i], i, this));
}
return newArray;
};

With this custom myMap() function, you can now use it like the built-in version:

const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.myMap(num => num * 2);
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]

Worked Example

Let's dive deeper into the map() function by creating a more complex example: Squaring every odd number in an array and returning a new array of squared even numbers.

const inputArray = [1, 2, 3, 4, 5, 6];

// Function to square a number
function square(num) {
return num * num;
}

// Using map() to square odd numbers and filter out even squares
const squaredOdds = inputArray.map(num => (num % 2 !== 0) ? square(num) : null).filter(num => num);
console.log(squaredOdds); // Output: [9, 25, 49]

// Using map() to square even numbers and filter out odd squares
const squaredEvens = inputArray.map(num => (num % 2 === 0) ? square(num) : null).filter(num => num % 2 === 0);
console.log(squaredEvens); // Output: [4, 16]

In this example, we first define an input array inputArray. We then create a function square() to square a number. Using the map() method, we apply the square() function to each element in the array and filter out the null values (which represent odd numbers that were not squared).

We repeat this process for even numbers, creating another array called squaredEvens. Finally, we log both arrays to the console.

Common Mistakes

  1. Forgetting to return a value from the callback function: If you don't explicitly return a value in your callback function, the map() method will return undefined, which will be included in the resulting array.
  1. Not understanding the this keyword: By default, the this keyword inside the map() function refers to the array itself. If you need to use a different this value, you must pass it as the third argument (thisValue).
  1. Using map() for side effects: While map() is designed for transforming arrays, it's not meant for performing side effects like modifying external variables or logging to the console. Use other functions like forEach() if you need to perform side effects.

Common Mistakes (cont.)

  1. Ignoring array order: When using a callback function with multiple statements, be aware that the order of execution may not always follow the original array's order. To preserve the order, use an explicit loop or the forEach() method instead.
  1. Not handling undefined values: If your input array contains undefined values, they will be passed to the callback function as well. Be sure to handle these cases appropriately within your callback function.
  1. Incorrectly using map() with other methods: Remember that map() creates a new array and doesn't modify the original one. If you want to use the results of map() with another method like filter(), reduce(), or sort(), you must chain these methods together, as shown in our worked example.

Practice Questions

  1. Write a JavaScript function that takes an array of strings and returns a new array containing only the strings with more than 5 characters.
const words = ["apple", "banana", "cherry", "date", "grape"];
const longWords = words.map(word => word.length > 5 ? word : null).filter(word => word);
console.log(longWords); // Output: ["apple", "grape"]
  1. Write a JavaScript function that takes an array of numbers and returns a new array containing the squares of all negative numbers.
const numbers = [-1, 0, 3, -4, 5];
const squaredNegatives = numbers.map(num => num < 0 ? num * num : null).filter(num => num !== null);
console.log(squaredNegatives); // Output: [1, 16]
  1. Write a JavaScript function that takes an array of objects and returns a new array containing the names of all objects with a property named "color".
const items = [
{ name: "apple", color: "red" },
{ name: "banana", color: "yellow" },
{ name: "cherry", color: "red" },
{ name: "date", color: "brown" }
];
const coloredItems = items.map(item => item.color ? item.name : null).filter(item => item);
console.log(coloredItems); // Output: ["apple", "banana", "cherry"]

FAQ

Why does map() return a new array instead of modifying the original one?

The map() method is designed to create a new array without altering the original one. This allows you to work with the transformed data without affecting the source data.

Can I use map() for filtering arrays?

Yes, you can use the filter() method in combination with map() to achieve complex filtering and transformation tasks. In our worked example, we demonstrated this by using filter() after map().

What is the difference between map(), filter(), and reduce()?

  • map() creates a new array with the results of calling a provided function on every element in the original array.
  • filter() returns a new array containing all elements that pass the test implemented by the provided function.
  • reduce() reduces an array to a single value by iteratively applying a function to each element and accumulating the result.

Why does my callback function return undefined when using map()?

If your callback function doesn't explicitly return a value, it will return undefined. Make sure you use the return keyword in your callback functions when working with map().

How can I use map() to perform multiple transformations on an array?

To perform multiple transformations using map(), you can chain multiple map() calls together or combine them with other methods like filter() and reduce(). Be mindful of the order in which these methods are called, as the output of one method may serve as input for another.

Can I use map() to sort an array?

While map() is not designed for sorting arrays, you can use it in combination with other methods like sort() or Array.prototype.sort() to achieve a sorted output. However, keep in mind that the built-in sort() method sorts elements based on their string representation, so you may need to convert numbers to strings if you want them to be sorted as strings.

How can I use map() with an arrow function?

You can use an arrow function when defining the callback for map(). Just make sure that your arrow function captures the correct value of this by either using an explicit binding (e.g., thisArg) or avoiding the use of this entirely if possible.

How can I use map() with a class method?

To use map() with a class method, you need to ensure that the method is bound to the correct context (i.e., the instance of the class). You can achieve this by using an arrow function or by explicitly binding the method to the instance using the bind() method.

ES6 Array map() (JavaScript) | JavaScript | XQA Learn