Added comparison to regular if-else statement (#20756)
This commit is contained in:
committed by
Huyen Nguyen
parent
028cdd94b0
commit
fc1c2f4a12
@ -5,7 +5,7 @@ title: Conditional Ternary Operators
|
||||
### Basic usage
|
||||
The ternary operator is a compact way to write an if-else inside an expression.
|
||||
```js
|
||||
const thing = (condition) ? <if true> : <if false>;
|
||||
const thing = <condition> ? <if condition is true> : <if condition is false>;
|
||||
```
|
||||
E.g.
|
||||
```js
|
||||
@ -18,6 +18,20 @@ You can also chain ternary operators, this way you will have an if-else if-else
|
||||
: <second condition> ? <value if second is true>
|
||||
: <fallback value>
|
||||
```
|
||||
### Comparison to if statement:
|
||||
The ternary operator is essentially a simplification of the normal `if` statement. You turn this:
|
||||
```js
|
||||
if (condition) {
|
||||
<if condition is true>;
|
||||
} else {
|
||||
<if condition is false>;
|
||||
}
|
||||
```
|
||||
Into this:
|
||||
```js
|
||||
var output = <condition> ? <if condition is true> : <if condition is false>;
|
||||
```
|
||||
As you can see, it is much easier to write and read.
|
||||
> **Pro tip**: As you see you can split the ternary operator on multiple lines
|
||||
E.g.
|
||||
```
|
||||
|
Reference in New Issue
Block a user