This page looks best with JavaScript enabled

Null and Undefined - Heroes who are equal to none in Javascript

 ·   ·  ☕ 1 min read

You have used null. You have used undefined. But, have you ever thought about what they mean to the world and to Javascript?

The fact is quite simple - we can’t do a null equality check.

1
2
3
4
console.log(1 == null); // false
console.log(0 == null); // false
console.log(false == null); // false
console.log("" == null); // false

The same holds for undefined.

1
2
console.log(1 == undefined); // false
console.log(false == undefined); // false

But, they measure up to themselves and to each other.

1
2
3
4
5
console.log(null == null); // true
console.log(null == undefined); // true

console.log(null === null); // true
console.log(null === undefined); // false

Practical usage of null and undefined, therefore, follow this pattern -

1
2
3
4
5
let x;
console.log(x == null); // true

x = 0;
console.log(x != null); // true

You should not be using this -

1
2
3
let x;
// cannot use this.
console.log(x === null); // false

Yes, even if the whole world is trying to push you towards the reinforced equality operator, you can push back those forces with some help from null.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things