In JavaScript, both null
and undefined
are primitive types with different meanings. It is crucial to understand the distinctions between them.
-
undefined:
- When a variable is declared but not assigned any value, it is considered
undefined
. - For example:
let age; // age is undefined
- It is important to note that attempting to access a variable that has not been declared will result in a
ReferenceError: <variable> is not defined
error, which is different fromundefined
.
- When a variable is declared but not assigned any value, it is considered
-
null:
- When a variable has the value
null
, it means that it has been intentionally assigned to have no value. - For example:
let age = null; // age is null
- To check if a variable has been assigned the value
null
, you can use the comparison operator===
. - To check for both
null
andundefined
, you can use the statement:if (!age) { // code here }
- The
typeof
operator can also be used to determine the type of a variable. However,null
is evaluated as an object, even though it is a primitive type:let age; typeof age; // 'undefined' let age = null; typeof age; // 'object'
- When a variable has the value
Understanding the difference between null
and undefined
is essential for writing clean and reliable JavaScript code.