Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

JavaScript Quiz #8 (One Line Quiz)

DZone's Guide to

JavaScript Quiz #8 (One Line Quiz)

This week's JavaScript Quiz just a one-liner. See if you can tell if this code will succeed or fail, and learn about using decimal points in float numbers.

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

Assume that we have the following snippet of JavaScript code:

<script>
    var result = (2..valueOf() + ({z : 10, x : 20}).x);
    alert(result);
</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 22. Let’s understand why we will get this result. Let’s divide the expression in two parts. In the first part, we have:

2..valueOf()

This expression will work fine because in JavaScript, it is valid to trail decimal points in float numbers, that means 2, for example, can be represented as 2 or 2.0 or 2. (without having to mention the extra 0 after the decimal dot).

So the expression can be read simply as (2.).valueOf() which will return 2.

The second part is straightforward:

({z : 10, x : 20}).x

We have a JavaScript object with two attributes x and z, and we are getting the value of x using .x, which means that the result will be equal to the value of x, which is 20.

Adding the first part's result to the second part result will result in: 20 + 2 = 22.

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

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 DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}