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]

JS Array

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

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Object Ref
  5. DOM Scripting
  6. SVG
  7. Blog