'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?
Solution 1:[1]
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;
Solution 2:[2]
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 asvariable = 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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CertainPerformance |
| Solution 2 | tomleb |
