Blog

How to Use the `map` Function in JavaScript

2 min read·5/25/2026·JavaScript·FridgeChef
Try the app
Want more recipes?
Sign up and get a trial — unlock limits and extra features.

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

Syntax

const newArray = array.map(callback(currentValue[, index[, array]])[, thisArg])
  • callback: A function to execute for each element in the array. It takes three arguments:
    • currentValue: The current element being processed in the array.
    • index (optional): The index of the current element being processed.
    • array (optional): The array map was called upon.
  • thisArg (optional): Value to use as this when executing callback.

Examples

1. Doubling each number in an array:

const numbers = [1, 4, 9, 16];
const doubledNumbers = numbers.map(num => num * 2);
console.log(doubledNumbers); // Output: [2, 8, 18, 32]

2. Extracting a property from an array of objects:

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
];
const userNames = users.map(user => user.name);
console.log(userNames); // Output: ['Alice', 'Bob', 'Charlie']

3. Converting strings to uppercase:

const words = ['hello', 'world'];
const uppercasedWords = words.map(word => word.toUpperCase());
console.log(uppercasedWords); // Output: ['HELLO', 'WORLD']

Key Benefits of map()

  • Immutability: map() does not modify the original array. It always returns a new array.
  • Readability: It makes code more declarative and easier to understand compared to traditional for loops for transformations.
  • Chaining: map() can be easily chained with other array methods like filter() and reduce().

When to Use map()

Use map() whenever you need to transform each element of an array into something else and collect those transformed elements into a new array. If you only need to iterate over an array without creating a new one, forEach() might be more appropriate.

Try the app
Want more recipes?
Sign up and get a trial — unlock limits and extra features.