Over a million developers have joined DZone.

JavaScript Quiz #9

DZone 's Guide to

JavaScript Quiz #9

This JavaScript quiz will test your knowledge of arrays along with the order of operations. If you don't know the answer, you'll want to brush up on Array.prototype.map.

· Web Dev Zone ·
Free Resource

If you haven't checked out JavaScript quizzes 7 and 8 take some time to look at those after doing this one.  Each one builds on the other and they get progressively more difficult. See if you really know your JavaScript arrays.

    var x = [1, 2, 3, 4].map(function(x, y) { return x + y } );


Question: Will this code succeed or fail? And if it succeeds, what is the output of the alert?

*Write your answer on a piece of paper and then read the answer.*


The code will work fine. The final result is [1, 3, 5, 7]. Let’s understand why we will have this result. The key to understanding the previous expression is to understand how Array.prototype.map works.

According to ECMA documentation, Array.prototype.map creates a new array and calls a provided function on every element in this array. This function represents the first parameter. It 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 the following:
[1 + 0, 2 + 1, 3 + 2, 4 + 3] ==> [1, 3, 5, 7].


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}