Can someone please explain to me in simple words what is the ?:
(conditional, "ternary") operator and how to use it?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
unary
Binary
Ternary
For more clarification please read MDN document link
Ternary Operator
Commonly we have conditional statements in Javascript.
Example:
but it contain two or more lines and cannot assign to a variable. Javascript have a solution for this Problem Ternary Operator. Ternary Operator can write in one line and assign to a variable.
Example:
This Ternary operator is Similar in C programming language.
I want to add some to the given answers.
In case you encounter (or want to use) a ternary in a situation like 'display a variable if it's set, else...', you can make it even shorter, without a ternary.
Instead of:
You can use:
This is Javascripts equivallent of PHP's shorthand ternary operator
?:
Or even:
It evaluates the variable, and if it's false or unset, it goes on to the next.
It's an
if statement
all on one line.So
The expression to be evaluated is in the
( )
If it matches true, execute the code after the
?
If it matches false, execute the code after the
:
Ternary expressions are very useful in JS, especially React. Here's a simplified answer to the many good, detailed ones provided.
condition ? expressionIfTrue : expressionIfFalse
think of expressionIfTrue as the OG if statement rendering true, think of expressionIfFalse as the else statement.
ex: var x = 1; (x == 1) ? y=x : y=z;
this checked the value of x, the first y=(value) returned if true, the second return after the colon : returned y=(value) if false. Happy coding.