How to Replace a value if null or undefined in JavaScript?
In JavaScript, replacing a value if it is null or undefined involves providing a default value to use when the original value is either null or undefined. This ensures the application has valid data, preventing potential errors or unexpected behavior.
Here we have some common approaches:
Table of Content
Approach 1: Using Brute force
The brute force approach in JavaScript involves manually checking if a value is null or undefined using if statements. If the condition is true, the value is set to a default value. This ensures valid data is always present.
Example: In this example, we check if the value is null or undefined, assigns 'default value' if true, and prints 'default value' to the console.
let value = null;
if (value === null || value === undefined) {
value = 'default value';
}
console.log(value);
Output
default value
Approach 2 : Using logical OR (||) operator
Using the logical OR (||) operator in JavaScript, you can assign a default value if the original value is null or undefined. This approach also covers other falsy values like 0 or an empty string.
Example : In this example we initializes value to null, then assigns 'default value' using the logical OR operator || if value is falsy,
let value = null;
value = value || 'default value';
console.log(value); // Output: "default value"
Output
default value