Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any difference between x || [] and x ?? [] in javascript?

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?

like image 655
JOrielly Avatar asked Dec 18 '25 15:12

JOrielly


2 Answers

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);
like image 155
CertainPerformance Avatar answered Dec 20 '25 03:12

CertainPerformance


These expressions x || [] and x ?? [] are logical assignments in Javascript.

x ?? [] is used to represent null or undefined cases while x || [] represent true if either a or b is true.

  • x ?? [] works by evaluating if the left side of the expression is null or undefined.

  • x || [] works by evaluating if a or b is true. If a is true continue in the if statement. If b is true, continue in the if statement.

like image 43
yet-it-compiles Avatar answered Dec 20 '25 04:12

yet-it-compiles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!