Home > Back-end >  Strangest JS ternary statement I've ever seen
Strangest JS ternary statement I've ever seen

Time:03-19

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?

CodePudding user response:

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;

CodePudding user response:

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.

  • Related