JavaScript 1.6: Array’s map method

I came across a Node.js code sample last night and noticed something I hadn’t seen before:

var myArray = ['a', 'b', 'c'], 
    newArray = myArray.map(function(elem){ 
        return elem + ' x';         
    });

Arrays’ map method will return a new array after invoking your callback on each item in myArray. In this case we get a new array that looks like this:

['a x', 'b x', 'c x']

The map method accepts two arguments

  1. the callback to invoke
  2. the this context

The callback accepts three arguments:

  1. the value of the element
  2. the index of the element
  3. the Array object being traversed

Apparently the ECMAScript 5 edition (ES5) specified this functionality and has been implemented in JavaScript 1.6. You can easily verify if your browser supports this functionality by firing up the console and running:

[].map

You don’t have this functionality if ‘undefined’ is returned. No big deal, you’re a JavaScript programmer implement it yourself by adding a method to Array’s prototype:

 

if(!Array.prototype.map) {

    Array.prototype.map = function(callback, thisContext) {

    //do your thing:)

    }

}

I just added something new to my toolset I hope you did too.

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply