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

188
Visualizações
Why ternary operator gives an Error without brackets?

I have four lines of code like this:

let postId = // <== maybe undefined or string;
const sections = // <== maybe null or an array of sections with posts objects.

postId = postId || (sections ? sections[0]?.posts[0]?.id : null);
console.log(postId || sections ? sections[0]?.posts[0]?.id : null);

The third line is working and I understand why - If postId is falsy, then compute right part of an expression in brackets where I use ternary with optional array item and optional object parameters.

But the fourth line gives me an error:

Uncaught TypeError: Cannot read properties of null (reading '0')

I do not understand why brackets is important in this case.

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

0

fourth line gives me an error

The reason behind that is your ternary operator is now working on postId || sections. Hence, Surround your right side statement in parenthesis in order to prevent it to consider left side variable as a part of ternary operation.

It should be :

console.log(postId || (sections ? sections[0]?.posts[0]?.id : null));
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