1

In JavaScript, is it possible to place a Conditional statement after an Or operator? If so, why is the following fails for me?

var value = 1 || true ? 2 : 3;    // equals to 2

When I set value to be equals to [1 || true ? 2 : 3], I get an unexpected result. The result that get is that:

value == 2

I've expected value to be equals to 1 (value= = 1), since 1 is truthy, and the Or statement should have return 1. The conditional statement is not even supposed to be executed.

The only way val can be equals to 2 (val == 2) is if the Or operator is behaving not as expected, and runs the second part of the Or statement and the Conditional statement that is in it.

Why is it behaving that way?

2
  • 1
    Because it's interpreted as (1 || true) ? 2 : 3 Commented Jan 16, 2017 at 19:33
  • Ohh.. I forgot about operator precedence .. Commented Jan 16, 2017 at 19:36

2 Answers 2

3

I've expected value to be equals to 1 (value = 1), since 1 is truthy

To get that, you need parens:

var value = 1 || (true ? 2 : 3);
// --------------^------------^

Without them, the || is between 1 and true, and then the conditional operator's first operand is the result of that (which is 1).

This is because || has higher precedence than the conditional operator (just); here's a table on MDN.

Sign up to request clarification or add additional context in comments.

Comments

0

Because Logical OR has precedence over the Conditional operator. Then your statement is actually interpreted as:

(1 || true) ? 2 : 3;

Which obviously evaluates to 2.

See MDN

1 Comment

Thank you guys for the fast response (:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.