March 02, 2020
&& and || are short-circuiting operators in Javascript. It handles truthy and falsey values.
Consider this example.
a |
b |
a && b |
a || b |
|---|---|---|---|
| True | True | a | a |
| True | False | b | a |
| False | True | a | b |
| False | False | a | b |
These operators are used generally to ensure null checking, or to provide a default value in everycase. However, it could lead to bugs. In JavaScript world, there are six falsey values: undefined, null, false, 0, NaN, and the empty string ”.
Consider the following example:
function(props) {
const isPresent = props.value || true;
}Case 1: props is undefined
Value of isPresent will be true
Case 2: props.value is true
Value of isPresent will be true
Case 3: props.value is false
Value of isPresent will be true
So, no matter what the value of props or props.value be, we are always setting isPresent to be equal to true. It may not be desired case. Intention may be to set default to true, only when value is undefined or not present.
Therefore, there has been an introduction of nullish operator ( ?? ) in 2019. It acts similar to || operator, but only strictly checks nullish value ( null and undefined). Let’s understand this with similar examples.
function(props) {
const isPresent = props.value ?? true;
}Case 1: props is undefined
Value of isPresent will be true
Case 2: props.value is true
Value of isPresent will be true
Case 3: props.value is false
Value of isPresent will be false
So in case 3, we got the desired result.
Some more examples to understand.
undefined ?? '2'
> "2"
false ?? '2'
> false
true ?? '2'
> true
0 ?? 1
> 0
null ?? undefined
> undefined
null ?? 1
> 1
null ?? {}
>Object { }
'' ?? null
> ""
'' ?? 'test'
> ''
Written by Kanishk Agrawal who lives and works in Bangalore, India.