Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

187
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!