My Favorite JavaScript Oddities

This article was first posted on LinkedIn on August 19, 2019.

There are so many oddities in an interpreted language like JavaScript. I’m sharing a list of my favorites. To make this article more accessible, I skipped the more complex quirks, the ones requiring a deeper understanding of JavaScript and its syntax. I’m also skipping the complex behavior of the “==” operator, a source of so many jokes in the JS community.

If you have a JS oddity you would like to add to this list, please let me know.

Curiosity #1

> ('b' + 'a' + + 'a' + 'a').toLowerCase()

  "banana"

The middle + “a” (since it’s preceded by another +) is a unary coercion of “a” into a number, which fails and results in NaN, which is then concatenated in and lower-cased. If we remove the .lowercase() the error becomes evident because we get baNaNa.

Curiosity #2

> [] + []

  ""

Adding two empty arrays returns an empty string (Gary Bernhardt). I don’t have any explanation for this.

Curiosity #3

> [] + {}
  [object Object] 

> {} + []
  0  

Adding an empty array to an empty object returns an object, while the reverse, adding an empty object to an empty array returns zero (Gary Bernhardt). I don’t have any explanation for this.

Curiosity #4

> 1 - []
  1

> 1 - {}
  NaN

> 1 + []
  "1"

Subtracting an empty array from a number returns the number, while subtracting an empty object from a number returns NaN. Interestingly, adding an empty array to a number returns the string version of the number.

Curiosity #5

> [] == [] 
  false

> [] != []
  true

> ![]
  false

Apparently, an empty array is not the same as an empty array, but not an empty array is false (Brian Leroux).

Curiosity #6

> [3, 2, 1].sort()
  [1, 2, 3]

> [3, 2, 10].sort()
  [10, 2, 3]

By default, the sorting of an array uses the lexical comparator converting every item to a string.

Curiosity #7

> 0.1 + 0.1
  0.2

> 0.1 + 0.2
  0.30000000000000004

This is an error common to several languages and is related to the way JavaScript represents floating points.

Curiosity #8

> (3).toString()
  "3"

> 3.toString()
  Uncaught SyntaxError: Invalid or unexpected token

> 3..toString()
  "3"

> 3.0.toString()
  "3"

> Number(3).toString()
  "3"

This time the trick is to convince JS to convert the number 3 to an object before converting it to a string. The behavior remains anti-intuitive at best.

Curiosity #9

> typeof 3
  "number"

> typeof NaN
  "number"

Apparently, NaN (Not a Number) is a number, somehow.


Franco Folini lives and works in the eCommerce territory, a wild area between the Kingdom of Technology and the Kingdom of Marketing. He speaks fluently the language of both realms. For many years, Franco has been helping people bridge the divide and successfully collaborate.

If you want to find out more about Franco, visit his LinkedIn profile or send him an email folini[at]gmail.com