What’s the difference between null and undefined data types?
Last updated: September 18, 2021.
null
and undefined
are two different data types in Javascript. But both seem to convey a similar meaning. So what’s the difference?
undefined
is used to signify that a variable has been initialised but no value has yet been assigned to it. For example:
let emptyVariable; alert(emptyVariable); // undefined alert(typeof emptyVariable); // undefined
let
and var
to initialize a variable with no assigned value. This is not allowed with const
.
null
on the other hand is an assigned value that indicates no value:
let nullVariable= null; alert( nullVariable ); // null alert(typeof nullVariable ); // object
You may be surprised null is of the type object
and not type null
given that it is a primitive object.
According to the book Professional Javascript For Web Developers (Wrox):
You may wonder why the typeof operator returns ‘object’ for a value that is null. This was actually an error in the original JavaScript implementation that was then copied in ECMAScript. Today, it is rationalized that null is considered a placeholder for an object, even though, technically, it is a primitive value.