As the year marks its end and we are therefore exposed to the yearly "What to use in 2024" click-bait articles, let's instead amuse us with some oddities of JavaScript.
Numbers
You can't divide by zero. But why not? If I divide 1 by smaller and smaller fractions, I'll be getting higher and higher numbers nearing infinity. So eventually we'd end up at infinity? Not so fast. If we "came from the other side" towards zero, we'd approach negative infinity when getting to zero:
const a = 1/0.0001; // 1,000
const b = 1/0.000001; // 100,0000
const c = 1/-0.000001; // -100,0000
const d = 1/-0.0000001; // -1,000,0000
So what does JavaScript do when dividing by zero? "NaN" maybe? Nope, it goes for infinity.
console.log(1/0) // Infinity
Interesting. That means that the type of 1/0 must be infinity? Nope, it's NaN (Not a number).
console.log(typeof 1/0) // NaN
Okay, so infinity doesn't seem to be a type, then? Let's test:
console.log(typeof Infinity) // number
Wait a second, you think? If infinity is a number and 1/0 is infinity, why is the type of 1/0 not a number (NaN)? Well, let's explore:
console.log(typeof NaN) // number
console.log(NaN === NaN) // false
Confused, yet?
Objects
What's so nice about having no type safety is that we can be quick & dirty. So dirty indeed, that nearly every company will insist on Typescript to avoid almost impossible to find bugs. Let's examine the following code.
let myObject = null;
function getFromBackend(){
fetch('/api/object').then(j => j.json()).then(result => {
// result: {a: "b"}
myObject = result;
})
}
// SpongeBob narrator: ..several hours later
// Is our variable myObject filled?
function checkIfValid(){
if(typeof myObject === 'object'){
// do something
}
}
Seems logical to a beginner, but here's the culprit
console.log(typeof null) // object
console.log(typeof null === typeof {}) // true
But then again, we all know objects aren't object anyway, right?
console.log({} === {}) // false
OMG, what a language
Using the type-safe comparison (===) is therefore a must, as otherwise the nightmare would be so much worse:
const array = []
console.log(array == false) // true
console.log(array === false) // false
There are even books about JavaScript oddities, as this list could go on for a while. But I guess we'd rather go on reddit to bash on PHP so Santa doesn't put us on the naughty list ;-)
I completely agree. This is, without a doubt, the worst-built language ever. I even wrote an entire article about why I hate it.