Arithmetic with JavaScript Arrays

4 May 2017
A Astonishing Adventure

An empty array is zero:

> +[]
0

An array of length 1 is equivalent to the first value:

> +[1]
1
> -[2]
-2

Any longer, and the array is not a number:

> +[1,2]
NaN

One can add 2 arrays together:

> [1] + [2]
'12'
> [1,2] + [3]
'1,23'
> [1,2] + [3,4]
'1,23,4'

Or take them apart:

> [10] - [3]
7
> [] - [10]
-10
> [10,2] - [3]
NaN

And multiply or divide:

> [2] * [3]
6
> [3] / [4]
0.75

Or be wise with their bits:

> [4] | [2]  // 100 | 010
6
> [4] & [12]  // 0100 & 1100
4
> [4] ^ [5]  // 100 ^ 101
1
> [1] << [2]
4

You can compare:

> [1] < [3]
true
> [3] < [1]
false

No matter the length:

> [1,2] < [1]
false
> [1] < [1,2]
true

Javascript, huh? What an interesting language. While so many have seen Gary Bernhardt's amazing talk "Wat", it is a good laugh to dive into a random part of JavaScript and see how it behaves. I found it very odd how a single-element array is automatically unwrapped for arithmetic operations. But I never knew the that array addition just does string concatenation. Isn't it odd that arrays are NaN if they are long, but not if they are short?

What's you favourite JavaScript quirk? Let us know on our IRC channel or via email!