What's the difference between a variable that is: null , undefined ...
What's the difference between a variable that is: null , undefined ...
In JavaScript, the terms null, undefined, and undeclared refer to different states of variables, each representing a unique situation in the code. Understanding these differences is crucial for effective debugging and code management.
A variable is null
when it has been explicitly assigned the null
value. It represents a deliberate assignment of "no value" or "empty" to a variable. The type of a null
variable is an object, which intentionally signifies the absence of any object value. To check if a variable is null
, you can use strict equality (===
) since null
is only equal to null
or undefined
under non-strict equality.
Example:
let variable = null;
if (variable === null) {
console.log('variable is null');
}
A variable is undefined
if it has been declared but not assigned any value. It is a primitive type and is the default value of variables that have been declared but left uninitialized. To check if a variable is undefined
, you can use the typeof
operator or strict equality.
Example:
let variable;
if (typeof variable === 'undefined') {
console.log('variable is undefined');
}
An undeclared variable is one that has not been declared at all (i.e., no var
, let
, or const
has been used to declare it). Trying to access such a variable results in a ReferenceError
. However, if you check the type of an undeclared variable using typeof
, it returns 'undefined', which can be misleading because it does not throw an error like direct access does.
Example:
try {
console.log(undeclaredVariable);
} catch (error) {
console.log('variable is undeclared'); // This will catch the ReferenceError
}
Checking for these states:
To determine if a variable is null
, undefined
, or undeclared, you can use a combination of typeof
checks and strict equality. Here’s a function that encapsulates these checks...
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào