JavaScript provides several ways to check if a variable is null
or undefined
. Understanding the nuances of these checks is crucial for writing robust and predictable code. This tutorial will cover the different approaches, their implications, and best practices for ensuring code reliability.
Understanding null
and undefined
Before diving into the methods, it’s important to understand the difference between null
and undefined
:
undefined
: A variable that has been declared but not assigned a value will have the valueundefined
. It also represents the absence of a value for an object property.null
: Represents the intentional absence of any object value. It’s an assignment value, meaning you explicitly set a variable tonull
to indicate that it doesn’t currently hold a value.
Methods for Checking null
and undefined
Let’s explore the various ways to check for these values:
1. The typeof
Operator
The typeof
operator returns a string indicating the type of a variable. Crucially, it returns "undefined"
for undeclared variables without throwing an error.
let myVariable; // Declared but not assigned
console.log(typeof myVariable); // Output: "undefined"
let anotherVariable = null;
console.log(typeof anotherVariable); // Output: "object" (a historical quirk of JavaScript)
let declaredVariable = 10;
console.log(typeof declaredVariable); //Output: "number"
While typeof
is useful for checking if a variable has been declared, it doesn’t reliably distinguish between null
and undefined
due to the "object"
result for null
.
2. Strict Equality (===
) and Strict Inequality (!==
)
Using strict equality (===
) and strict inequality (!==
) is generally recommended for most comparisons in JavaScript because they check both value and type without type coercion. However, there’s one exception to this rule: checking for null
or undefined
.
let myVariable;
let anotherVariable = null;
console.log(myVariable === undefined); // true
console.log(anotherVariable === null); // true
console.log(myVariable === null); // false
3. Loose Equality (==
) and Loose Inequality (!=
)
Loose equality (==
) performs type coercion before comparing values, which can lead to unexpected results. However, there’s a specific case where using loose equality is considered acceptable: when checking if a value is either null
or undefined
.
let myVariable;
let anotherVariable = null;
console.log(myVariable == null); // true
console.log(anotherVariable == null); // true
This works because both null
and undefined
are loosely equal to each other. While functional, using == null
is considered an exception to the general rule of using strict equality. Many style guides, including the jQuery style guide, explicitly allow this exception for this specific use case.
4. The Boolean()
Constructor
The Boolean()
constructor converts a value to a boolean. null
, undefined
, 0
, NaN
, an empty string (""
), and false
all evaluate to false
when converted to a boolean.
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean(0)); // false
console.log(Boolean("")); // false
console.log(Boolean(false)); // false
While this works, it’s generally not recommended for specifically checking for null
or undefined
as it also flags other "falsy" values as false
.
Best Practices and Recommendations
- For most comparisons, use strict equality (
===
) and strict inequality (!==
). - When specifically checking if a variable is either
null
orundefined
, use loose equality (== null
). This is a widely accepted exception to the strict equality rule. - Be mindful of the difference between
null
andundefined
. Choose the appropriate check based on the context of your code. - Avoid relying solely on the
Boolean()
constructor for checkingnull
orundefined
as it will also flag other "falsy" values.
Example Scenarios
- Optional Function Arguments:
function myFunction(arg) {
if (arg == null) {
console.log("Argument is null or undefined");
} else {
console.log("Argument is:", arg);
}
}
myFunction(); // Output: Argument is null or undefined
myFunction(10); // Output: Argument is: 10
myFunction(null); // Output: Argument is null or undefined
- Object Properties:
let myObject = {};
if (myObject.nonExistentProperty == null) {
console.log("Property does not exist or is null/undefined");
}