.map()

.map()

  • Calls a function for each element of the array and returns a new array of results

  • .map() is one of the most useful and used iterator methods

  • .map() is does NOT mutate the original array

  • The callback function for .map() accepts the following parameters:

    • currentValue: (required) current element being processed in the array.

    • index: (optional) index of the current element being processed in the array

    • array: (optional) the array map was called upon.


Syntax

Using traditional (ES5) function syntax

const result = arr.map(function(item, index, array) {
  // returns the new value instead of item
})

Using arrow syntax (ES6)

const result = arr.map((item, index, array) => {
  // returns the new value instead of item
})

Example

const numbers = [1, 2, 3, 4, 5 ]

const numbersSquared = numbers.map((number) => {
  return number**2
})

console.log(numbersSquared) // [2, 4, 9, 16, 25]

console.log(numbers) // [1, 2, 3, 4, 5 ]

JS Bin on jsbin.com


Exercise

  • Use .map() to downcase all the words in loudWords. Save the returned values to a variable declared with const called lowerCaseWords;

JS Bin on jsbin.com