Update 02-first-steps/10-ifelse

This commit is contained in:
imidom 2019-01-06 13:38:04 -05:00 committed by GitHub
parent 3a24621e7e
commit 42cf06db0a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1,12 +1,12 @@
# Conditional operators: if, '?' # Conditional operators: if, '?'
Sometimes we need to perform different actions based on a condition. Sometimes, we need to perform different actions based on different conditions.
There is the `if` statement for that and also the conditional (ternary) operator for conditional evaluation which we will be referring as the “question mark” operator `?` for simplicity. To do that, we use the `if` statement and the conditional (ternary) operator which we will be referring to as the “question mark” operator `?` for simplicity.
## The "if" statement ## The "if" statement
The `if` statement gets a condition, evaluates it and, if the result is `true`, executes the code. The `if` statement evaluates a condition and, if the condition's result is `true`, executes a block of code.
For example: For example:
@ -18,9 +18,9 @@ if (year == 2015) alert( 'You are right!' );
*/!* */!*
``` ```
In the example above, the condition is a simple equality check: `year == 2015`, but it can be much more complex. In the example above, the condition is a simple equality check (`year == 2015`), but it can be much more complex.
If there is more than one statement to be executed, we have to wrap our code block inside curly braces: If we want to execute more than one statement, we have to wrap our code block inside curly braces:
```js ```js
if (year == 2015) { if (year == 2015) {
@ -29,15 +29,15 @@ if (year == 2015) {
} }
``` ```
It is recommended to wrap your code block with curly braces `{}` every time with `if`, even if there is only one statement. That improves readability. We recommend wrapping your code block with curly braces `{}` every time you use an `if` statement, even if there is only one statement to execute. Doing so improves readability.
## Boolean conversion ## Boolean conversion
The `if (…)` statement evaluates the expression in parentheses and converts it to the boolean type. The `if (…)` statement evaluates the expression in its parentheses and converts the result to a boolean.
Let's recall the conversion rules from the chapter <info:type-conversions>: Let's recall the conversion rules from the chapter <info:type-conversions>:
- A number `0`, an empty string `""`, `null`, `undefined` and `NaN` become `false`. Because of that they are called "falsy" values. - A number `0`, an empty string `""`, `null`, `undefined`, and `NaN` all become `false`. Because of that they are called "falsy" values.
- Other values become `true`, so they are called "truthy". - Other values become `true`, so they are called "truthy".
So, the code under this condition would never execute: So, the code under this condition would never execute:
@ -48,7 +48,7 @@ if (0) { // 0 is falsy
} }
``` ```
...And inside this condition -- always works: ...and inside this condition -- it always will:
```js ```js
if (1) { // 1 is truthy if (1) { // 1 is truthy
@ -56,7 +56,7 @@ if (1) { // 1 is truthy
} }
``` ```
We can also pass a pre-evaluated boolean value to `if`, like here: We can also pass a pre-evaluated boolean value to `if`, like this:
```js ```js
let cond = (year == 2015); // equality evaluates to true or false let cond = (year == 2015); // equality evaluates to true or false
@ -68,11 +68,11 @@ if (cond) {
## The "else" clause ## The "else" clause
The `if` statement may contain an optional "else" block. It executes when the condition is wrong. The `if` statement may contain an optional "else" block. It executes when the condition is false.
For example: For example:
```js run ```js run
let year = prompt('In which year was ECMAScript-2015 specification published?', ''); let year = prompt('In which year was the ECMAScript-2015 specification published?', '');
if (year == 2015) { if (year == 2015) {
alert( 'You guessed it right!' ); alert( 'You guessed it right!' );
@ -83,12 +83,12 @@ if (year == 2015) {
## Several conditions: "else if" ## Several conditions: "else if"
Sometimes we'd like to test several variants of a condition. There is an `else if` clause for that. Sometimes, we'd like to test several variants of a condition. The `else if` clause lets us do that.
For example: For example:
```js run ```js run
let year = prompt('In which year was ECMAScript-2015 specification published?', ''); let year = prompt('In which year was the ECMAScript-2015 specification published?', '');
if (year < 2015) { if (year < 2015) {
alert( 'Too early...' ); alert( 'Too early...' );
@ -99,13 +99,13 @@ if (year < 2015) {
} }
``` ```
In the code above JavaScript first checks `year < 2015`. If it is falsy it then goes to the next condition `year > 2015`, and otherwise shows the last `alert`. In the code above, JavaScript first checks `year < 2015`. If that is falsy, it goes to the next condition `year > 2015`. If that is also falsy, it shows the last `alert`.
There can be more `else if` blocks. The ending `else` is optional. There can be more `else if` blocks. The final `else` is optional.
## Ternary operator '?' ## Ternary operator '?'
Sometimes we need to assign a variable depending on a condition. Sometimes, we need to assign a variable depending on a condition.
For instance: For instance:
@ -124,16 +124,16 @@ if (age > 18) {
alert(accessAllowed); alert(accessAllowed);
``` ```
The so-called "ternary" or "question mark" operator lets us do that shorter and simpler. The so-called "ternary" or "question mark" operator lets us do that in a shorter and simpler way.
The operator is represented by a question mark `?`. The formal term "ternary" means that the operator has three operands. It is actually the one and only operator in JavaScript which has that many. The operator is represented by a question mark `?`. The formal term "ternary" means that the operator has three operands. It is actually the one and only operator in JavaScript which has that many.
The syntax is: The syntax is:
```js ```js
let result = condition ? value1 : value2 let result = condition ? value1 : value2;
``` ```
The `condition` is evaluated, if it's truthy then `value1` is returned, otherwise -- `value2`. The `condition` is evaluated: if it's truthy then `value1` is returned, otherwise -- `value2`.
For example: For example:
@ -141,7 +141,9 @@ For example:
let accessAllowed = (age > 18) ? true : false; let accessAllowed = (age > 18) ? true : false;
``` ```
Technically, we can omit parentheses around `age > 18`. The question mark operator has a low precedence. It executes after the comparison `>`, so that'll do the same: Technically, we can omit the parentheses around `age > 18`. The question mark operator has a low precedence, so it executes after the comparison `>`.
This example will do the same thing as the previous one:
```js ```js
// the comparison operator "age > 18" executes first anyway // the comparison operator "age > 18" executes first anyway
@ -149,10 +151,10 @@ Technically, we can omit parentheses around `age > 18`. The question mark operat
let accessAllowed = age > 18 ? true : false; let accessAllowed = age > 18 ? true : false;
``` ```
But parentheses make the code more readable, so it's recommended to use them. But parentheses make the code more readable, so we recommend using them.
````smart ````smart
In the example above it's possible to evade the question mark operator, because the comparison by itself returns `true/false`: In the example above, you can avoid using the question mark operator because the comparison itself returns `true/false`:
```js ```js
// the same // the same
@ -162,7 +164,7 @@ let accessAllowed = age > 18;
## Multiple '?' ## Multiple '?'
A sequence of question mark `?` operators allows returning a value that depends on more than one condition. A sequence of question mark operators `?` can return a value that depends on more than one condition.
For instance: For instance:
```js run ```js run
@ -176,14 +178,14 @@ let message = (age < 3) ? 'Hi, baby!' :
alert( message ); alert( message );
``` ```
It may be difficult at first to grasp what's going on. But after a closer look we can see that it's just an ordinary sequence of tests. It may be difficult at first to grasp what's going on. But after a closer look, we can see that it's just an ordinary sequence of tests:
1. The first question mark checks whether `age < 3`. 1. The first question mark checks whether `age < 3`.
2. If true -- returns `'Hi, baby!'`, otherwise -- goes after the colon `":"` and checks for `age < 18`. 2. If true -- it returns `'Hi, baby!'`. Otherwise, it continues to the expression after the colon '":"', checking `age < 18`.
3. If that's true -- returns `'Hello!'`, otherwise -- goes after the next colon `":"` and checks for `age < 100`. 3. If that's true -- it returns `'Hello!'`. Otherwise, it continues to the expression after the next colon '":"', checking `age < 100`.
4. If that's true -- returns `'Greetings!'`, otherwise -- goes after the last colon `":"` and returns `'What an unusual age!'`. 4. If that's true -- it returns `'Greetings!'`. Otherwise, it continues to the expression after the last colon '":"', returning `'What an unusual age!'`.
The same logic using `if..else`: Here's how this looks using `if..else`:
```js ```js
if (age < 3) { if (age < 3) {
@ -210,15 +212,15 @@ let company = prompt('Which company created JavaScript?', '');
*/!* */!*
``` ```
Depending on the condition `company == 'Netscape'`, either the first or the second part after `?` gets executed and shows the alert. Depending on the condition `company == 'Netscape'`, either the first or the second expression after the `?` gets executed and shows an alert.
We don't assign a result to a variable here. The idea is to execute different code depending on the condition. We don't assign a result to a variable here. Instead, we execute different code depending on the condition.
**It is not recommended to use the question mark operator in this way.** **We don't recommend using the question mark operator in this way.**
The notation seems to be shorter than `if`, which appeals to some programmers. But it is less readable. The notation is shorter than the equivalent `if` statement, which appeals to some programmers. But it is less readable.
Here is the same code with `if` for comparison: Here is the same code using `if` for comparison:
```js run no-beautify ```js run no-beautify
let company = prompt('Which company created JavaScript?', ''); let company = prompt('Which company created JavaScript?', '');
@ -232,6 +234,6 @@ if (company == 'Netscape') {
*/!* */!*
``` ```
Our eyes scan the code vertically. The constructs which span several lines are easier to understand than a long horizontal instruction set. Our eyes scan the code vertically. Code blocks which span several lines are easier to understand than a long, horizontal instruction set.
The idea of a question mark `?` is to return one or another value depending on the condition. Please use it for exactly that. There is `if` to execute different branches of the code. The purpose of the question mark operator `?` is to return one value or another depending on its condition. Please use it for exactly that. Use `if` when you need to execute different branches of code.