Cover by Evan Dennis on Unsplash
Summary
Intro
You may have seen a Javascript piece of code like this before:
const value = actualValue || "defaultValue";
The operator ||
used above is called "Logic OR", and works this way: If the value at the left of the operator is true, its value will be assigned to the variable value
. If it is false, then the variable value
will receive the value at the right, "defaultValue"
.
If you're used to Javascript, you must know that there are various problems with false and true values. Example: ""
and 0
are considered false values. Then, if in an algorithm ""
and 0
are considered valid values, the operator ||
wouldn't give the desired result. That's when the Nullish Coalescing operator comes.
The operator ??
Now that you understand the problem, comes the solution. The Nullish Coalescing operator is represented by the symbols ??
and is used like this:
const value = actualValue ?? "defaultValue";
In this case, if the value of actualValue
is null
or undefined
, the value "defautlValue"
will be assigned to the variable value
. Otherwise, the value actualValue
will be assigned to it.
Use case
Think about this scenario: You're creating a function that evaluates a expression using a coefficient. If the coefficient isn't provided, it will receive a default value, with 0
being valid. As I've said before, the operator ||
would not be the best for this case. Then, the operator ??
is much more suitable. Check the representation of this problem below:
function calculateResult(x,y,coefficient) { ;
const c = coefficient ?? 0.5;
return x + y * c;
}
const result = calculateResult(2,3);
console.log(result) // Output: 3.5 ( 2 + 3 * 0,5 )
The function calculateResult
uses the ??
to check if the parameter coefficient
is provided. If it is, then the value will be taken. Otherwise, the default coefficient will be 0.5
.
Considerations
The case used was a simple example, but the operator ??
can be useful in a lot of situations and assure more reliability to your code.
Enjoyed this article? Follow me for more contents like this one!
Follow me:
Twitter | Instagram | Youtube.
See you on the next article!👋🏽
Top comments (0)