Have you ever seen the double question mark operator in javascript??
It can be used like this
const firstName = null;
const lastName = null;
const nickname = null;
console.log(firstName ?? lastName ?? nickname ?? "anonymous")
// => "anonymous"
The console did not log null from the first 3 variables, but the last one. This is because the Nullish Coalescing Operator will output the first defined value. The 3 variables we defined are set null so they are all faulty and have no value.
This looks like it is similar to another operator we have that looks like this "||". The OR operator almost does the same thing but the first TRUTHY value. As opposed to the Nullish Coalescing Operator returns the first DEFINED value.
Review our list of Falsy Values:
- false
- 0
- -0
- 0n
- ""
- null
- undefined
- NaN
When looking at a ?? b
if a is defined with a value, then we will get "a", otherwise we will return b.
const a = 0;
const b = 1;
console.log(a ?? b)
// => 0
The value of a is returned here since we defined a with the value 0. If this was using the OR operator
const a = 0;
const b = 1;
console.log(a || b)
// => 1
a is defined with a faulsy value so we will get retrned the value of b.
Top comments (0)