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?
We can use with Jquery as well as length as below example :
Suppose we have GuarantorName textbox which has value and want to get firstname and lastname- it may be null. So rathar than
We can use below code with Jquery with minimum code
This is a one-line shorthand for an if-else statement. It's called the conditional operator.1
Here is an example of code that could be shortened with the conditional operator:
This can be shortened with the
?:
like so:In Javascript conditional operator can evaluate to an expression, not just a statement:
They can even be chained:
Be careful, though, or you will end up with convoluted code like this:
1 Often called "the ternary operator," but in fact it's just a ternary operator [an operator accepting three operands]. It's the only one JavaScript currently has, though.
It's called the 'ternary' or 'conditional' operator.
Example
From MSDN JS documentation.
Basically it's a shorthand conditional statement.
Also see:
It's a little hard to google when all you have are symbols ;) The terms to use are "javascript conditional operator".
If you see any more funny symbols in Javascript, you should try looking up Javascript's operators first: MDC's list of operators. The one exception you're likely to encounter is the
$
symbol.To answer your question, conditional operators replace simple if statements. An example is best:
Instead of: