How to use array map in JavaScript

In this article, I am going to explain array map() in JavaScript.
  • 2663

Array map method in JavaScript

The JavaScript array map method creates a new array with the result of provided function on every element in this array.

Syntax of array map method

array.map(callback[, thisArgs);


Parameters in array map method:

  • arrary

    Array required an array object.
     

  • callback

    Callback function accepts up to three arguments, and callback function is produce an element of the new array from the array of current one.
     

  • thisArgs

    ThisArgs is used as this when executing callbacks.

Return value in map method

A new array in which each element is the callback function return value for the associated original element.


Exception in map  method

If callback argument is not a function object, A TypeError exception is fire.


There are the following callback function parameter:
 

Parameter Value
value Array element value.
index Numeric  index of the array element.

Example of array map method:

<!DOCTYPE html>

<html>

<head>

<title>JavaScript Array map()</title>

</head>

<body>

<script type="text/javascript">

    if (!Array.prototype.map) {

        Array.prototype.map = function (fun /*, thisp*/) {

            var len = this.length;

            if (typeof fun != "function")

                throw new TypeError();

 

            var res = new Array(len);

            var thisp = arguments[1];

            for (var i = 0; i < len; i++) {

                if (i in this)

                    res[i] = fun.call(thisp, this[i], i, this);

            }

            return res;

        };   }

    var numbers = [1, 2, 5];

    var roots = numbers.map(Math.sqrt);

 

    document.write("roots is : " + roots);

</script>

</body>

</html>


OutPut:

 

roots is : 1,1.4142135623730951,2.23606797749979


Ask Your Question 
 
Got a programming related question? You may want to post your question here
 

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.