Hi, I'm Sam Parkinson

Arithmetic with JavaScript Arrays

A Astonishing Adventure

By Sam Parkinson, 4 May 2017; view other posts

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!


Comments, thoughts? Mail them to sam@sam.today. I would love to hear them!

Related posts

View all posts
Exposing properties with Graphene Django
The other missing guide
Read post
Freeing Disk Space with the PackageKit cache
Automatic updates gone wrong
Read post
Creating a super simple derivation - Learning Nix pt 3
Wrapping some shell scripts
Read post
So Variables are a Thing - Learning Nix pt 2
Taking advantage of the fact Nix is a programming language
Read post
NSDC 2016 Topics
Digitizing the motions from National Schools Debating Championships 2016
Read post
Environments with Nix Shell - Learning Nix pt 1
An introduction for how to run Nix code
Read post