Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

191
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda