Assume that we have the following short JavaScript code which runs on a browser that is ECMA 5 compatible:
<script> var x = [1, 2, 3, 4].map(function(x, y) { return x + y } ); alert(x); </script>
Will this code succeed or fail? and if it succeeds, what is the output of the alert?
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
The code will work fine. The final result is [1, 3, 5, 7]. Let’s understand why we will have this result. The main idea of the previous expression is to understand how Array.prototype.map
works.
According to ECMA documentation, Array.prototype.map
creates a new array with the results of calling a provided function on every element in this array; this provided function represents the first parameter. This means that the following function will be called on every element in the array:
function(x, y) { return x + y }
Array.prototype.map
passes the array element and its index to the provided function; this means that the resulting array will be as follows:
[1 + 0, 2 + 1, 3 + 2, 4 + 3] ==> [1, 3, 5, 7].