Assume that we have the following short JavaScript code:

<script> var result = 3..valueOf() + (1, 2, 4); 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 `7`

. Let’s understand why we will have this result. Let’s divide the expression in two parts. In the first part, we have:

3..valueOf()

This expression will work fine because in JavaScript, it is valid to trail decimal points in float numbers, so for example 3 can be represented as `3`

or `3.0`

or `3`

. (without having to mention the extra 0 after the decimal dot).

So the expression can be read simply as `(3.).valueOf()`

which will return `3`

.

The second part is straightforward:

(1, 2, 4)

In order to know the result of this expression, we have to know how expressions work with the comma operator, if we have an expression that contains many comma operators then this expression will be evaluated to the last mentioned value. This means that

`(1, 2, 4)`

will be evaluated to `4`

.

Adding the first part result to the second part result will result in: `3 + 4 = 7`

.