3

I came across a statement that has left my head confused.

Assume x >= 0

(x - 1 ? 16:11)

Apparently this code has the same response as

(x > 1 ? 16:11)

Can someone explain how the minus one works? I thought that conditional operators had to provide a true or false result. I don't understand how an integer can fit into a conditional operator.

1
  • You can put anything into a conditional, it will then be coerced to an boolean. Commented Mar 2, 2018 at 8:32

4 Answers 4

4

In the code:

(x - 1 ? 16 : 11)

if x is equal to 1, x - 1 is 0 and 0 is falsy so the expression evaluates to 11. Otherwise, x - 1 is truthy and the expression evaluates to 16.

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

3 Comments

I was just about to write the same thing
And also for more information about what falsy is, see: developer.mozilla.org/en-US/docs/Glossary/Falsy
Why would developers prefer to write this instead of a equality operator? Wouldn't the equality operator be 'safer'?
2

You could use some values to get an idea what is going on.

 x - 1 ? 16 : 11

-1 - 1              -2 truthy -> 16
 0 - 1              -1 truthy -> 16
 1 - 1               0 falsy  -> 11
 2 - 1               1 truthy -> 16
 3 - 1               2 truthy -> 16

Based on this, the condition could be rewritten to

 x !== 1 ? 16 : 11

Comments

2

The conditional operator is evaluating the result of your expression.

Assuming x = 2 the results would be:

2 - 1 = 1 2 > 1 = true

Assuming x = 1 the results would be:

1 - 1 = 0 1 > 1 = false

0 will be treated as false. 1 as true.

So both expressions will have the same result.

But be aware: If you do use negative numbers the expressions will have different results, since negative numbers will be treated as true by the conditional operator.

-3 - 1 = -4 => true

-3 > 1 = false

2 Comments

nitpick: it is the "conditional operator", which is just one of the possible ternary operators (meaning: 3 operands). Not that I know of any others, however ...
Thanks! I changed my answer.
1

values greater than 0 or less than 0 are taken as true in conditional statements, and zero is taken as false

(1)?"true": "false";
(0)?"true": "false";

console.log((-1)? "true": "false");
console.log((1)? "true": "false");
console.log((0)? "true": "false");

Comments

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.