Javascript Array Map method

Javascript Array Map method

Definition and Usage

map() creates a new array from calling a function for every array element.

map() does not execute the function for empty elements.

map() does not change the original array.

Syntax

array.map(function(currentValue, index, arr), thisValue);

Parameters

ParameterDescription
function()Required.
A function to be run for each array element.
currentValueRequired
The value of the current element.
indexOptional
The index of the currennt element
arrOptional
The array of the current element.
thisValueOptional
Default value undfined
A value passed to the function to be used as its this value.

Return Value

typeDescription
An arrayThe results of a function for each array element.

Some Examples

const persons = [
  { firstname: "Malcom", lastname: "Reynolds" },
  { firstname: "Kaylee", lastname: "Frye" },
  { firstname: "Jayne", lastname: "Cobb" },
];

persons.map(getFullName);

function getFullName(item) {
  return [item.firstname, item.lastname].join(" ");
}

// ES6 Arrow function style

const getFullName = (item) => [item.firstname, item.lastname].join(" ");

// or

const noFunctionEvenNedded = persons.map((anyNameDoesNotMatter) =>
  [anyNameDoesNotMatter.firstname, anyNameDoesNotMatter.lastname].join(" ")
); // This return an array full of objects.

console.log(noFunctionEvenNedded);

Learn more about it here.

;