Over a million developers have joined DZone.

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

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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.

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

    alert(x);
</script>

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.*


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].


Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:
javascript

Published at DZone with permission of Hazem Saleh, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}