Hugo JS

Weak dynamic typing is arguably one of those things everybody likes to pick at about JavaScript. For an elegant dynamic language, JavaScript does some very silly things.

Or does it? (Queue Vsauce intro)

This is my little attempt to explain JavaScript’s type coercion in a very simple manner that all JavaScript developers, regardless of experience, can simply understand. I hope you’ll leave this with an enriched knowledge of how to take hold of the language’s quirks and use it to your advantage.

What is it doing wrong?

Example 1

const a = [ 1, 2, 3 ];
const b = [ 1, 2, 3 ];

console.log(a + b); //-> 1,2,31,2,3 <- Why?

Example 2

const nope = Array(10).join("nope" - 1) + " Batman!";

console.log(nope); //-> NaNNaNNaNNaNNaNNaNNaNNaNNaN Batman! <- Why?

Example 3

const x = [];
const y = {};

console.log(x + y); //-> [object Object] <- Wait what?

Why is it doing it wrong?

The simple reason is history. JavaScript has a long, weird, winding history from when Brendan Eich originally wrote the first prototype in 10 days at Netscape in 1995.

Since then, anything that hasn’t been “fixed” has only one reason. JavaScript has one simple rule – don’t break the web. This is why strange things like typeof null === 'object' exist.

#javascript #es6

Type Coercion in JavaScript (and why everyone gets it wrong)
33.25 GEEK