JS: Array.prototype.map

By Xah Lee. Date: . Last updated: .

Apply function f to every element of the array myArray.

Return the new array.

Original array is not changed.

If thisArg is given, it will be used as this value of f. If it is not given, undefined is used.

[see JS: “this” Binding]

The function f is passed 3 args: • current_elementcurrent_indexmyArray.

// example of Array.prototype.map
const a1 = [3,4,5];

const a2 = a1.map( ((x) => (x+1)) );

console.log(a2);  // [ 4, 5, 6 ]

console.log(a1);  // [ 3, 4, 5 ]  original is not changed

Example of using Array.prototype.map, with the passed function using more than 1 argument.

// example of using Array.prototype.map, with the passed function using more than 1 arg

const a1 = ["a", "b", "c"];

const a2 = a1.map(
    ((x,i,ar) => (console.log ( x, i, ar )))
);

// prints
// a 0 [ 'a', 'b', 'c' ]
// b 1 [ 'a', 'b', 'c' ]
// c 2 [ 'a', 'b', 'c' ]

Example of using Array.prototype.map with second argument.

// example of using Array.prototype.map with second argument

const a1 = [3,4,5];

const obj = { john:9 };

a1.map(
    function (x)
    {
        console.log ( x , this );
    },
    obj
);

// prints

// 3 { john: 9 }
// 4 { john: 9 }
// 5 { john: 9 }

[see JS: Array.prototype.forEach]

Reference

ECMAScript® 2016 Language Specification#sec-array.prototype.map

Array Topic

  1. JS: Array Basics
  2. JS: Understand JS Array
  3. JS: Create Array
  4. JS: Sparse Array
  5. JS: Array-Like Object
  6. JS: Array How-To

  1. JS: Array Object
  2. JS: Array.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth