Difference between null / undefined / not defined?
Introduction
In JavaScript, both null
and undefined
indicate that a value being accessed is non-existent. Even using loose equality ==
, both are considered equal. However, they are fundamentally different, and this article aims to clarify their relationship.
console.log(null == undefined); // trueconsole.log(null === undefined); // false
Null
null
means “exists but has no value” and can only be obtained through an explicit assignment of null
. Therefore, when a value of null
is received, it indicates that the developer intentionally assigned it, rather than it occurring for other reasons. For instance, if no results are found, null
can be assigned to represent that the value is nothing.
const search = null;console.log(search); // null
Undefined
undefined
means “does not exist and has no value.” By default, all variables are undefined
unless they have been explicitly assigned another value. Thus, when this value is received, it often indicates that the value does not truly exist.
let foo;console.log(foo); // undefined
Not Defined
In addition to null
and undefined
, there is another situation: not defined. This is not a specific value; rather, it occurs when you attempt to access a variable that has not been declared, resulting in a not defined error.
console.log(bar); // ❌ ReferenceError: bar is not defined
Conclusion
The difference between the two lies in the developer’s “intent.” While both represent “nothing,” one indicates “exists” while the other indicates “does not exist,” so it’s often preferable to define null
.
Interestingly, undefined
can actually be defined, and defining something that essentially does not exist is a strange but feasible thing to do. It’s best to avoid doing this 😅.