Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Replace a value if null or undefined in JavaScript?
In JavaScript, you can replace null or undefined values using the logical OR operator (||) or the nullish coalescing operator (??).
Syntax
// Using logical OR operator var result = value || defaultValue; // Using nullish coalescing operator (ES2020+) var result = value ?? defaultValue;
Using Logical OR Operator (||)
The || operator returns the first truthy value or the last value if all are falsy:
var value = null;
console.log("The original value:", value);
var actualValue = value || "This is the Correct Value";
console.log("The replaced value:", actualValue);
// Testing with undefined
var undefinedValue = undefined;
var replacedUndefined = undefinedValue || "Default for undefined";
console.log("Replaced undefined:", replacedUndefined);
The original value: null The replaced value: This is the Correct Value Replaced undefined: Default for undefined
Using Nullish Coalescing Operator (??)
The ?? operator only replaces null and undefined, preserving other falsy values like 0 or empty strings:
var nullValue = null;
var undefinedValue = undefined;
var zeroValue = 0;
var emptyString = "";
console.log("null ?? 'default':", nullValue ?? "default");
console.log("undefined ?? 'default':", undefinedValue ?? "default");
console.log("0 ?? 'default':", zeroValue ?? "default");
console.log("'' ?? 'default':", emptyString ?? "default");
null ?? 'default': default undefined ?? 'default': default 0 ?? 'default': 0 '' ?? 'default':
Comparison
| Operator | Replaces | Preserves 0, false, "" |
|---|---|---|
|| |
All falsy values | No |
?? |
Only null/undefined | Yes |
Practical Example
function getUserName(user) {
// Using ?? to preserve empty strings but replace null/undefined
return user.name ?? "Anonymous User";
}
var user1 = { name: null };
var user2 = { name: undefined };
var user3 = { name: "John" };
console.log("User 1:", getUserName(user1));
console.log("User 2:", getUserName(user2));
console.log("User 3:", getUserName(user3));
User 1: Anonymous User User 2: Anonymous User User 3: John
Conclusion
Use || when you want to replace any falsy value, or ?? when you specifically want to replace only null and undefined while preserving other falsy values.
Advertisements
