JavaScript Glossary - Lesson #11

JavaScript Array .map() Method

The map() method takes a callback method that performs an operation on the elements in the array. It returns a new array containing the resulting values of running the operation on each element. This method does not mutate the calling array.

let newArray = [1, 2, 3, 4, 5].map(function(number){
    return number * 2
// [2, 4, 6, 8, 10]
// Array of numbers
const scores = [20, 30, 50, 2]

// Update numbers
const updatedScores ={
  return score + 10

// Output new array
console.log(updatedScores) // [30,40,60,12]

The .map() method:

  • Takes a callback function that is called once for each element.
  • Calls the callback function and gets the result of the operation run on the element
  • Returns a new array with the results> The .map() method creates a new array and doesn't mutate the old array.
let newArray =[, index[, array]])[, thisArg])

callback This is the function that executes each of the elements of the array. The callback function is required and can take three parameters:

  • element: This is the element currently being executed - required.
  • index: This is the index of the current item - optional.
  • array: This is the array that is currently being processed - optional.

thisArg This is an argument passed to be used as the this value in the callback - optional

A new array with each value being the result of the callback function.

const numbers = [2, 4, 6, 8];
const squares = => number * numbers);

// output: Array [4, 16, 36, 64]

Fetching scores from an object:

// Student data in an object
const students = [{name: 'Rich', score: 33}, {name: 'Peter', score: 55}];

// Run through array and fetch scores
let scores ={
  return student.score

// Output scores in an array
console.log(scores); // [33,55]

Attach the month to its number:

// Array of months
const months = ['Jan', 'Feb', 'Mar', 'Apr'];

// Change month to include number value
let monthsIndex =, index){

// Make index nonzero
  let noneZeroIndex = index + 1;
  // Return manipulated month values
  return month + '-' + noneZeroIndex;

// Output result
console.log(monthsIndex); // ["Jan-1","Feb-2","Mar-3","Apr-4"]

Want to improve your coding and design skills?

I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.

We value your privacy. 1-click unsubscribe.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created which was acquired.


What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)