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.
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) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With