The nullish coalescing operator in JavaScript is used to provide a default value when an expression is null or undefined. It is represented by the ?? operator and is useful when a program needs to handle missing or unavailable values without treating other falsy values such as 0, false, or an empty string as missing. The nullish coalescing operator is commonly used when working with user input, configuration values, API responses, and optional data.
Table of Contents
What Is the Nullish Coalescing Operator in JavaScript?
The nullish coalescing operator ?? returns the value on its left side when that value is not null or undefined. If the left-side value is null or undefined, JavaScript returns the value on the right side.
It is useful when a default value should be used only when the original value is missing.
Syntax:
value ?? defaultValue
Syntax of the Nullish Coalescing Operator
The nullish coalescing operator uses two question marks.
leftValue ?? rightValue
Left Value: JavaScript checks the value on the left side first.
Right Value: The value on the right side is returned when the left value is null or undefined.
How the Nullish Coalescing Operator Works
The nullish coalescing operator follows a simple process for selecting a value.
- Evaluate the Left Value: JavaScript first evaluates the expression on the left side of ??.
- Check for Nullish Values: JavaScript checks whether the result is null or undefined.
- Return the Left Value: If the value is neither null nor undefined, JavaScript returns the left-side value.
- Use the Default Value: If the value is null or undefined, JavaScript returns the right-side value.
Nullish Coalescing with null
When the left-side value is null, the nullish coalescing operator returns the value on the right side.
// JavaScript program to demonstrate nullish coalescing with null let username = null; let result = username ?? "Guest"; console.log(result);
Output:
Guest
Since username contains null, JavaScript uses "Guest" as the default value.
Nullish Coalescing with undefined
The ?? operator also uses the right-side value when the left-side value is undefined.
// JavaScript program to demonstrate nullish coalescing with undefined let username; let result = username ?? "Guest"; console.log(result);
Output:
Guest
The variable username is undefined because it has been declared without an assigned value. Therefore, "Guest" is returned.
Nullish Coalescing with Default Values
The nullish coalescing operator is commonly used to provide default values.
// JavaScript program to demonstrate a default value with nullish coalescing let age = null; let userAge = age ?? 18; console.log(userAge);
Output:
18
Since age is null, the default value 18 is used.
If the original value is available, JavaScript keeps that value.
// JavaScript program to demonstrate nullish coalescing with an existing value let age = 25; let userAge = age ?? 18; console.log(userAge);
Output:
25
Here, age is neither null nor undefined, so the value 25 is returned.
Difference Between ?? and ||
The nullish coalescing operator ?? and the logical OR operator || can both be used to provide default values, but they treat falsy values differently.
The || operator uses the right-side value when the left-side value is any falsy value, such as 0, false, "", null, or undefined.
The ?? operator uses the right-side value only when the left-side value is null or undefined.
Example using ||:
// JavaScript program to demonstrate the logical OR operator with a zero value let score = 0; let result = score || 100; console.log(result);
Output:
100
The || operator considers 0 to be falsy, so it returns 100.
Example using ??:
// JavaScript program to demonstrate the nullish coalescing operator with a zero value let score = 0; let result = score ?? 100; console.log(result);
Output:
0
The ?? operator does not consider 0 to be nullish, so it keeps the value 0.
Nullish Coalescing with Variables
The ?? operator can be used with variables to provide fallback values.
// JavaScript program to demonstrate nullish coalescing with variables let firstName = null; let lastName = "Shinde"; let name = firstName ?? lastName; console.log(name);
Output:
Shinde
Since firstName is null, JavaScript uses the value of lastName.
Nullish Coalescing with Objects
The nullish coalescing operator can be useful when an object property may be missing or contain null.
// JavaScript program to demonstrate nullish coalescing with an object property
let student = {
name: "Tanavi",
age: null
};
let age = student.age ?? 18;
console.log(age);
Output:
18
The age property contains null, so the default value 18 is used.
Nullish Coalescing with Function Parameters
The ?? operator can also be used inside functions when a parameter may contain null or undefined.
// JavaScript program to demonstrate nullish coalescing with a function parameter
function greet(name) {
let username = name ?? "Guest";
console.log("Hello, " + username);
}
greet(null);
greet("Tanavi");
Output:
Hello, Guest
Hello, Tanavi
When null is passed, the function uses "Guest". When "Tanavi" is provided, the original value is used.
Combining ?? with Optional Chaining
The nullish coalescing operator is often used with optional chaining (?.) when working with nested objects.
Optional chaining safely accesses a property without causing an error when an intermediate value is null or undefined.
// JavaScript program to demonstrate optional chaining with nullish coalescing
let user = {
profile: null
};
let city = user.profile?.city ?? "Unknown";
console.log(city);
Output:
Unknown
Here, user.profile?.city produces undefined because profile is null. The ?? operator then provides "Unknown" as the default value.
Complete Program Using the Nullish Coalescing Operator
The following program demonstrates how the nullish coalescing operator can be used to provide default values for different variables.
// JavaScript program to demonstrate the nullish coalescing operator
let username = null;
let age = 20;
let city;
let displayName = username ?? "Guest";
let displayAge = age ?? 18;
let displayCity = city ?? "Pune";
console.log("Name:", displayName);
console.log("Age:", displayAge);
console.log("City:", displayCity);
Output:
Name: Guest
Age: 20
City: Pune
The username and city variables are nullish, so their default values are used. The age variable already contains a valid value, so its original value is retained.
Advantages of the Nullish Coalescing Operator
- Default Values: The ?? operator provides a default value when a value is null or undefined.
- Preserves Valid Falsy Values: It keeps values such as 0, false, and an empty string instead of replacing them with a default value.
- Readable Code: It provides a clear and concise way to handle missing values.
- Useful with API Data: It can provide fallback values when data from an API is missing.
- Useful with Optional Data: It works well with optional chaining when accessing properties that may not exist.
Common Beginner Mistakes
- Confusing ?? with ||: The ?? operator checks only for null and undefined, while || treats several other values such as 0, false, and "" as falsy.
- Thinking 0 Is Nullish: The value 0 is not null or undefined, so ?? keeps 0.
- Thinking false Is Nullish: The Boolean value false is not nullish, so false ?? true returns false.
- Using ?? Without Understanding Missing Values: The operator is specifically useful when null or undefined should trigger a fallback value.
- Mixing ?? Directly with && or ||: JavaScript does not allow ?? to be mixed directly with && or || without parentheses. Parentheses should be used to clearly specify the intended order.
Conclusion
The nullish coalescing operator ?? is used in JavaScript to provide a default value when an expression is null or undefined. Unlike the logical OR operator ||, it preserves valid falsy values such as 0, false, and an empty string. This makes ?? particularly useful when handling optional data, API responses, object properties, and default values. Understanding the difference between ?? and || helps developers handle missing values more accurately.
FAQs
1. What is the nullish coalescing operator in JavaScript?2. What is the syntax of the nullish coalescing operator?The nullish coalescing operator ?? returns the left-side value when it is not null or undefined. Otherwise, it returns the right-side default value.
3. What is the difference between ?? and ||?The syntax is value ?? defaultValue, where the default value is used when the first value is null or undefined.
4. Does ?? replace zero with a default value?The ?? operator uses the default value only for null and undefined, while || uses the default value for any falsy value, including 0, false, and an empty string.
5. Can ?? be used with optional chaining?No. The value 0 is not nullish, so the nullish coalescing operator keeps 0.
Yes. Optional chaining and nullish coalescing can be combined to safely access optional properties and provide a default value when the result is null or undefined.
0 Comments