ResourcesJavascriptGuides
Null vs undefined
Introduction
In JavaScript, null
and undefined
are two different primitive types representing the absence of value.
While they may seem similar, they have different uses and behaviors.
In this article I will explain what's the difference.
All Javascript data types
Null and undefined
Undefined
undefined
is a primitive value automatically assigned to variables that have been declared but not initialized.
When is undefined used?
- Variable declared but not assigned a value.
- Function is called but doesn't return a value.
- Property does not exist in an object.
- Accessing array elements outside the array bounds.
Null
null is a primitive value that represents the intentional absence of any object value. It is explicitly assigned by the programmer to indicate "no value."
When is null used?
- Intentionally setting a variable to have no value.
- Resetting or clearing a variable to indicate no value.
Key difference between null and undefined
1. Type
undefined
is typeundefined
null
is typeobject
2. Usage
undefined
is used by JavaScript in various cases as a default valuenull
is used by programmers to intentionally denote the absence of a value
3. Equality
==
(loose equality): null and undefined are equal.===
(strict equality): null and undefined are not equal.