DEV Community

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

Posted on

5

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →