0
0
Javascriptprogramming~5 mins

Map method in Javascript

Choose your learning style9 modes available
Introduction

The map method helps you change every item in a list and get a new list with the changed items.

You want to double every number in a list of prices.
You need to get the names only from a list of people objects.
You want to add a symbol to every word in a list.
You want to convert all temperatures from Celsius to Fahrenheit.
Syntax
Javascript
array.map(function(item, index, array) {
  // return new item
})

The map method runs a function on each item in the array.

The function must return the new item to be in the new array.

Examples
Doubles each number in the array.
Javascript
[1, 2, 3].map(x => x * 2)
Changes all fruit names to uppercase.
Javascript
['apple', 'banana'].map(fruit => fruit.toUpperCase())
Extracts the name from each object.
Javascript
[{name: 'Ann'}, {name: 'Bob'}].map(person => person.name)
Sample Program

This program doubles each number in the list and prints the new list.

Javascript
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled);
OutputSuccess
Important Notes

The original array does not change; map creates a new array.

If you forget to return a value in the function, the new array will have undefined items.

Summary

Use map to make a new array by changing each item in the old array.

The function inside map must return the new item.

The original array stays the same after using map.