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

112
Views
Strangest JS ternary statement I've ever seen

So i'm working on this project, which has code someone else wrote, and I found this javascript ternary operation to assign a variable. They aren't available for me to ask about it. I understand the first half, but ...

variable = statement ? option1 : option2 ? option2 : option1

it would be simple for me if it was just

variable = statement ? option1 : option2

but the second half of the statement is just baffling to me. Can someone please explain what is happening here?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

variable = statement ? option1 : option2 ? option2 : option1

is, spaced out:

variable = statement
  ? option1
  : option2
    ? option2
    : option1

If statement, option1.

Otherwise, if option2, option2.

Otherwise, option1.

Another way of doing it is:

if (statement) {
  variable = option1;
} else if (option2) {
  variable = option2;
} else {
  variable = option1;
}

A clearer way of implementing the same logic would be:

if (!statement && option2) {
  variable = option2;
} else {
  variable = option1;
}

or

variable = (!statement && option2)
  ? option2
  : option1;
about 4 years ago · Juan Pablo Isaza Report

0

Not the same.
variable = statement ? option1 : option2 ? option2 : option1
would be the equivalent of -

if (statement) {
   variable = option1;
} else {
   if (option2) {
      variable = option2;
   } else {
      variable = option1;
   }
}

Where as
variable = statement ? option1 : option2
would be equivalent to -

if (statement) {
   variable = option1;
} else {
   variable = option2;
}

As can be more clearly seen here, in the second example, if statement is false, variable will always be equal to option2.
But in the first example, it can still be equal to option1 in some cases.

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!