Open In App

How to Replace a value if null or undefined in JavaScript?

In JavaScript if a variable is not initialised with any value, then it is set to undefined. We can set a default value if a value is undefined. This can be done using two ways.

Example 1: By using if checks (Brute force). In this method, we will manually check whether a value is not null or not undefined, if so then set it to some default value.



Example 2: By using logical OR (||) operator. In this method, if the value is null or undefined, then it will simply replaced by default value set by user.

Note: In Method 2, don’t use the following newValue = 10 || oldValue;. It will always set newValue to 10 because 10 will always return true.




Article Tags :