December 13, 20203 min read
null is an assignment value. It can be assigned to a variable as a representation of no value:
There are two features of null you should understand:
null
is an empty or non-existent value.null
must be assigned.In the example below, we are assigning value to null.
var x = null
console.log(x);
// null
Undefined usually means a variable has been declared, but not defined.
var z = {};
console.log(z.value);
// undefined
null
and undefined
are primitive values in JavaScript.null == undefined
// true
null
vs. undefined
Another interesting difference to note is when arithmetic operations are performed with null vs. undefined.
Arithmetic operations with a null value will result in integer value while any arithmetic operation with undefined will result in the value of the variable being changed to
NaN
.
var x = 5 + null;
console.log(x);
// 5
var y = 5 + undefined;
console.log(y);
// NaN
console.log(typeof(undefined)); //"undefined"
console.log(typeof(null)); //"object"
console.log(null === undefined) //false
console.log(null == undefined) //true
console.log(null !== undefined) //true
null
!== undefined
but null
== undefined
.