JavaScript tutorials > JavaScript Basics > Operators > What is the nullish coalescing operator (??)?
What is the nullish coalescing operator (??)?
The nullish coalescing operator ( It provides a concise way to assign a default value to a variable if the original value is either ??
) is a logical operator that returns its right-hand side operand when its left-hand side operand is null
or undefined
, and otherwise returns its left-hand side operand.null
or undefined
.
Basic Syntax
The If ??
operator takes two operands:
value
: The value to be checked.defaultValue
: The default value to be returned if value
is null
or undefined
.value
is not null
or undefined
, then value
is returned. Otherwise, defaultValue
is returned.
const result = value ?? defaultValue;
Example with Null
In this example, name
is assigned null
. Since name
is null
, the nullish coalescing operator returns the right-hand side operand, which is 'Guest'
. Therefore, name
is assigned the value 'Guest'
.
const name = null ?? 'Guest';
console.log(name); // Output: Guest
Example with Undefined
In this example, age
is assigned undefined
. Since age
is undefined
, the nullish coalescing operator returns the right-hand side operand, which is 25
. Therefore, age
is assigned the value 25
.
const age = undefined ?? 25;
console.log(age); // Output: 25
Example with a Valid Value
In this example, city
is assigned 'New York'
. Since city
is neither null
nor undefined
, the nullish coalescing operator returns the left-hand side operand, which is 'New York'
. Therefore, city
remains 'New York'
.
const city = 'New York' ?? 'Unknown';
console.log(city); // Output: New York
Concepts Behind the Snippet
The nullish coalescing operator addresses a common need to provide default values when dealing with potentially missing or unset data. It's specifically designed to only trigger when a value is strictly Understanding the difference between null
or undefined
, distinguishing it from the logical OR operator (||
).??
and ||
is crucial. The ||
operator considers falsy values (0
, ''
, false
, null
, undefined
, NaN
) as equivalent to false
and returns the right-hand side operand if the left-hand side operand is falsy. The ??
operator only considers null
or undefined
to be equivalent to the absence of a value.
Real-Life Use Case Section
Consider a scenario where you are fetching user data from an API. Some fields might be missing (i.e., null
or undefined
). The nullish coalescing operator allows you to provide default values for these missing fields, ensuring that your application displays meaningful information to the user. The example demonstrates this use case with a mock userData
object and uses the operator to assign default values for name, age and city in case those are null or undefined.
// Fetch data from an API, but provide defaults
const userData = {
name: 'John Doe',
age: null, // Age is not available
city: undefined // City is not available
};
const displayName = userData.name ?? 'Anonymous'; // Defaults to 'Anonymous' if name is null or undefined
const displayAge = userData.age ?? 'N/A'; // Defaults to 'N/A' if age is null or undefined
const displayCity = userData.city ?? 'Unknown'; // Defaults to 'Unknown' if city is null or undefined
console.log(`Name: ${displayName}`); // Output: Name: John Doe
console.log(`Age: ${displayAge}`); // Output: Age: N/A
console.log(`City: ${displayCity}`); // Output: City: Unknown
Best Practices
null
or undefined
cases. If you need to handle all falsy values (0
, ''
, false
, etc.), then the logical OR operator (||
) might be more appropriate.&&
or ||
without explicit parentheses. JavaScript doesn't allow combining the ??
operator directly with &&
or ||
without using parentheses to clarify the precedence. This is to prevent ambiguity and potential errors.
Interview Tip
Be prepared to explain the difference between the nullish coalescing operator (??
) and the logical OR operator (||
). Highlight that ??
only checks for null
and undefined
, while ||
checks for any falsy value. Also, mention the precedence rules and the need for parentheses when mixing with &&
and ||
.
When to Use Them
Use the nullish coalescing operator when you want to provide a default value specifically when a variable is null
or undefined
, and you want to avoid using the default value for other falsy values (like 0
or ''
).
Memory Footprint
The nullish coalescing operator itself doesn't significantly impact memory footprint. It's a lightweight operator that simply checks for null
or undefined
and returns one of its operands. The memory usage will be determined by the data types and sizes of the operands involved.
Alternatives
Before the introduction of the nullish coalescing operator, developers often used the logical OR operator (||
) to provide default values. Another alternative involves using a ternary operator or an if
statement to explicitly check for null
or undefined
.
Alternatives: Logical OR (||) Operator
The ||
operator returns the right-hand side if the left-hand side is falsy. Use it if you want to handle all falsy values.
const name = someValue || 'Default Name';
// This will use 'Default Name' if someValue is any falsy value (null, undefined, '', 0, false)
Alternatives: Ternary Operator
A more verbose, but explicit, way to check for null
or undefined
.
const name = someValue === null || someValue === undefined ? 'Default Name' : someValue;
Pros
null
or undefined
.
Cons
??
and ||
to use it correctly.
FAQ
-
What's the difference between
??
and||
?
??
only checks fornull
orundefined
, while||
checks for falsy values (0
,''
,false
,null
,undefined
,NaN
). -
Can I use
??
with&&
or||
?
Yes, but you must use parentheses to explicitly specify the order of operations. For example:(a ?? b) && c
ora ?? (b || c)
. Omitting the parentheses will result in a syntax error. -
Is
??
supported in all browsers?
No, older browsers might not support it. Consider using a transpiler like Babel to ensure compatibility or use alternative approaches for older environments.