JavaScript Quiz #8 (One line Quiz)

Assume that we have the following short JavaScript code:

<script>
    var result = (2..valueOf() + ({z : 10, x : 20}).x);
    alert(result);
</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 22. Let’s understand why we will have 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, so for example 2 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 here 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 x value which is 20.

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