DEV Community

Cover image for JavaScript null is weird
Ebenezer Enietan (Niza)
Ebenezer Enietan (Niza)

Posted on

JavaScript null is weird

JavaScript has a unique way of implementing common programming concepts. Some things you assume will work a certain way will definitely give you a result but not the one you were expecting.

Let's say you read some literature that Null is a data type then you run typeof(null) then you find out null is not an object, but it is of type object:

let x = null;
console.log(typeof x);  // logs "object"
//also this not-object-fake-object  has no properties
let x = null;
console.log(x.prop);  // TypeError: Cannot read property 'prop' of null
Enter fullscreen mode Exit fullscreen mode

Also consider this, in JavaScript, null is considered a falsy value, which means it will be coerced to false when used in a boolean context. This means that when null is compared to 0 using the less-than-or-equal-to operator (<=), the result will be true.

console.log(null < 0);  // logs "false"
console.log(null > 0);  // logs "false"
console.log(null == 0);  // logs "false"
console.log(null === 0);  // logs "false"
console.log(null <= 0);  // logs "true"
console.log(null >= 0);  // logs "true"
Enter fullscreen mode Exit fullscreen mode

Talking about weird things here is another example NaN is never equal to NaN the best way to test NaN is to use isNaN();

NaN === NaN; //false
console.log(isNaN(NaN)); // true
console.log(isNaN(123)); // false
console.log(isNaN('hello')); // true
//But beware
console.log(isNaN('123')); // false
Enter fullscreen mode Exit fullscreen mode

I know you have experienced other weirdness in your JavaScript journey, please share it and the reason why you think it exists? Do you think there were too many opinions in the development of the language? Are there too many people taking advantage of these quirks for them to be changed? Let me know your opinion.

Top comments (0)