Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optioning chaining not working for array.length === x

Tags:

javascript

let products;

if (products?.length !== 0) {
  console.log('true')
}

vs

let products;

if (products && products.length !== 0) {
  console.log('true')
}

If there is no product array, example 1 will still run the if statement. Shouldn't the optional chaining check to see if product exists, then check for the length and finally check length to 0?

Example. 2 will not run if product does not exist.

like image 971
pancake Avatar asked Nov 14 '25 13:11

pancake


1 Answers

Optional chaining does not take precedence over comparison. This

if (products?.length !== 0) {

is

if ((products?.length) !== 0) {

It evaluates the chain, then compares the result to 0. If there was a value at the end of the chain, that'll be compared. If the chain failed due to something being nullish, it'll evaluate to undefined, and that will be compared with 0.

if ((undefined) !== 0) {

which will always be true.

Since you want the block to run if products exists and isn't empty, use

if (products?.length) {
like image 136
CertainPerformance Avatar answered Nov 17 '25 10:11

CertainPerformance



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!