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.
Join the DZone community and get the full member experience.
Join For FreeIf 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].
Published at DZone with permission of Hazem Saleh, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
How to LINQ Between Java and SQL With JPAStreamer
-
Security Challenges for Microservice Applications in Multi-Cloud Environments
-
Application Architecture Design Principles
-
How Web3 Is Driving Social and Financial Empowerment
Comments