I've see both x || [] and x ?? [] used for providing a fallback value if x is nullish. Are there any cases where these two give different results?
Any difference between x || [] and x ?? [] in javascript?
242 Views Asked by JOrielly AtThere are 3 best solutions below
On
If x was a non-nullish falsey value, it would be different.
x = 0;
x = x ?? []
console.log(x);
y = null;
y = y ?? []
console.log(y);
On
They do different things.
?? is called Nullish coalescing operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
And works checking if the left side of the evaluation is null or undefined and if it's not the case will assign the right side of the evaluation.
The previous is really useful when you are checking a variable with the value zero which will be false if you are checking for it.
|| is the Logical Operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR
The logical operator works as any other logical operator. Will evaluate the left side and then the right side
null || 1 // output 1
undefined || 1 // output 1
0 || 1 // 1 <-- there are cases where you want to treat zero as a truthy value and **that's where the nullish operator is handy**
These expressions
x || []andx ?? []are logical assignments in Javascript.x ?? []is used to represent null or undefined cases whilex || []representtrueif eitheraorbistrue.x ?? []works by evaluating if the left side of the expression is null or undefined.x || []works by evaluating ifaorbistrue. Ifais true continue in the if statement. Ifbis true, continue in the if statement.