Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

178
Visualizações
Optioning chaining not working for array.length === x

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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) {
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda