The difference between || and ?? operators in Javascript & NodeJS
In short, the difference between the two operators boils down to the difference between falsy
and null/undefined
. Where the logical or (||
) operator takes the right operand in the case of a falsy
value — which includes empty string, 0, false, NaN, etc. The nullish coalescing operator (??
) takes the right operand only when the left side is set to null
or undefined
. Having said that, we could think of the ??
operator as subset of the ||
.
A practical example of where we would want to use the ??
as opposed to the ||
would be when an empty string ""
is a valid value and we want the default value to N/A
. Without the ??
we would need to write:
if(currentDescription == null) {
targetDescriptionn = "N/A";
}
else {
targetDescriptionn = currentDescription;
}// or using the ternary operatortargetDescription = currentDescription == null ? "N/A": currentDescription
which can be replaced with a shorter one-liner:
targetDescriptionn = currentDescription ?? "N/A"
The way I double-check any Javascript behavior I’m unsure about (we all know that javascript doesn’t always behave the way we expect) is by running the interactive nodejs shell. In my experience, it’s a quicker way than googling for an answer. The way to access NodeJS interactive shell is by simply typing node
in the terminal (assuming the nodejs is added in the $PATH
).
Additional operators — logical AND (&&=) and OR(||=) assignment operators
Logical AND & OR assignment operators are only available in NodeJS version 15+
A nice addition to the above operator is logical AND assignment (&&=)
— which behaves very similar to the additional assignment operator (+=)
. A great use-case of the operator is setting default values on an existing variable.
description &&= "N/A"
As already discussed in the previous section, the value of the description will be set to N/A
only in the case the description variable is set to null
or undefined
.
Again, if however, the requirement is to change the value of the description in case of falsy
value (let say, empty string) the logical OR assignment (||=)
could be used
description ||= "N/A"