. Advertisement .
. Advertisement .
That is why here we are to get you out of trouble. Read on to learn more!
That way, once this logical operator finds that one of the two accepted values is committing the fault above, it will return the other on the right side of the mark.
Have a look at the code below. Let’s say the firstName is assigned as the username variable value, and the code inspects that this value is undefined. Then the operator will automatically assign it to “Visitor”.
let firstName = undefined; let username1 = firstName ?? "Editor"; console.log(username1); // "Editor" // You may also write it like this: let username2 = undefined ?? "Visitor"; console.log(username2); // "Visitor”
Why Should You Use The Nullish Coalescing Operator?
Little did you know, we can employ Nullish Coalescing exactly like the way we employ the logical OR operator. Then why should we utilize the former but not the latter?
The logical OR operator (||) is often practical in assigning a default value as variable. For instance:
let a; let result = a || 19 ; console.log(result); // 19
As such, we have the null variable is “a”, which is compelled to go false, triggering the result to become 19.
For instance, we have the code as follow:
In variable value1, the code features “0” and “default string.” Let’s say we report its value in the console; what we receive will be the “default string“, which is completely strange.
Since zero is neither undefined or null, we should get “0” instead. As can be seen, ‘||’ is not much effective in this situation.
So, what happen if we substitute ‘||’ by ‘??’? Here is the upcoming scenario:
To put it another way, “??” permits only undefined and null values, which make it work wonders for those empty strings (“) or 0s.
Leave a comment