I have this condition:
con1 ? (con2 || con3) ? "blue" : "white" : "green"
Is this the correct interpretation of that code?
if con1 = true , then "blue"
if con1 = false, then "white"
if con2 || con3 = true, then "green"
?
I have this condition:
con1 ? (con2 || con3) ? "blue" : "white" : "green"
Is this the correct interpretation of that code?
if con1 = true , then "blue"
if con1 = false, then "white"
if con2 || con3 = true, then "green"
?
The JavaScript ternary operator works like this:
condtion ? return value if condition is true : return value if condition is false
What you have is a nested ternary operator in the "true" portion, so your code:
con1 ? (con2 || con3) ? "blue" : "white" : "green"
Can be thought of as being grouped like this:
con1 ? [ (con2 || con3) ? "blue" : "white" ] : "green"
So, the nested part is evaluated first:
(con2 || con3) ? "blue" : "white"
If con2
or con3
are true, "blue" is returned
If not, "white" is returned
And that "blue" or "white" is then placed where the nested ternary was in the overall expression:
con1 ? "blue" or "white" : "green"
So now, if con1
is true, "blue" or "white" (whichever was returned from the nested ternary) is returned.
If not, "green" is returned.
if con1 is false then "green"
if con1 is true and con2 || con3 is true then "blue"
if con1 is true and con2 || con3 is false then "white"
Explanation:
Condition is equivalent to :
con1 ? ( (con2 || con3) ? "blue" : "white" ) : "green"
as it is like:
condition ? expr1 : expr2
if condition is true it executes expr1 else expr2.
therefore if con1 is true it will evaluate: (con2 || con3) ? "blue" : "white"
else return "green".
Updated after Scott's comment:
First the condition (con2 || con3) ? "blue" : "white" )
is evaluated and then based on value returned it evaluated con1 ? [value returned from con2 || con3) ? "blue" : "white"] : "green"