js null vs undefined

null vs undefined

What is null?
There are two features of null you should understand:

null is an empty or non-existent value.
null must be assigned.

ex:

1
2
3
let a = null;
console.log(a);
// null

Undefined most typically means a variable has been declared, but not defined. For example:

1
2
3
4
5
6
7
let b;
console.log(b);
// undefined

let c = undefined;
console.log(c);
// undefined

Finally, when looking up non-existent properties in an object, you will receive undefined:

1
2
3
var d = {};
console.log(d.fake);
// undefined

Here’s a full list for six falsy values:

1
2
3
4
5
6
false
0 (zero)
“” (empty string)
null
undefined
NaN (Not A Number)

Interestingly enough, when using typeof to test null, it returns object:

1
2
3
4
5
6
let a = null;
let b;
console.log(typeof a);
// object
console.log(typeof b);
// undefined

Null !== undefined

1
null !== undefined

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

1
null == undefined

a great example:

1
2
let logHi = (str = 'hi') => {
console.log(str);

This function requires one parameter and sets the default of that parameter to hi if it isn’t supplied. Here’s what that looks like:

1
2
3
4
5
6
logHi();
// hi
logHi('bye');
// bye

}

With default parameters, undefined will use the default while null does not.

1
2
3
4
logHi(undefined);
// hi
logHi(null);
// null

Summary
null is an assigned value. It means nothing.
undefined typically means a variable has been declared but not defined yet.
null and undefined are falsy values.
null and undefined are both primitives. However an error shows that typeof null = object.
null !== undefined but null == undefined.