Differences between "null" and "undefined" keywords?

Nuno Pereira - Aug 29 '19 - - Dev Community

They both represent a empty value.

Difference nr 1!

When you define a variable but not assign a value to it, it automatically puts a placeholder which is called undefined so you don't have do it manually, JavaScript does it for you.

Null means an empty or non-existent value.

Null is assigned, and explicitly means nothing. while undefined typically means a variable has been declared but not defined yet.

var a;
console.log(a);
// undefined

var b = null;
console.log(b);
// null

Difference nr 2!

Null and undefined are both primitives and falsy values. However null is also an object. Interestingly, this was actually an error in the original JavaScript implementation.

var a;
console.log(typeof(a));
// undefined

var b = null;
console.log(typeof(b));
// object

Difference nr 3!

As you can see so far, null and undefined are different, but share some similarities. Thus, it makes sense that null does not strictly equal undefined.

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

But, and this may surprise you, null loosely equals undefined.

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

In JavaScript, a double equals tests for loose equality and preforms type coercion. This means we compare two values after converting them to a common type.

See you soon for more tips !

. . . . . . .