2018-10-12 15:37:13 -04:00
|
|
|
---
|
|
|
|
title: Introducing Else If statements
|
|
|
|
---
|
2019-07-24 00:59:27 -07:00
|
|
|
# Introducing Else If statements
|
2018-10-12 15:37:13 -04:00
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
---
|
|
|
|
## Problem Explanation
|
2018-10-12 15:37:13 -04:00
|
|
|
|
|
|
|
We'll be modifying the existing code above so that it follows the flow of logic that an **else-if** statement has.
|
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
### Hint 1
|
|
|
|
```javascript
|
2018-10-12 15:37:13 -04:00
|
|
|
if (val > 10) {
|
|
|
|
return "Greater than 10";
|
|
|
|
}
|
2019-07-24 00:59:27 -07:00
|
|
|
```
|
2018-10-12 15:37:13 -04:00
|
|
|
All `if` statements and their variants start off with an `if` statement.
|
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
### Hint 2
|
|
|
|
```javascript
|
2018-10-12 15:37:13 -04:00
|
|
|
else if (val < 5) {
|
|
|
|
return "Smaller than 5";
|
|
|
|
}
|
2019-07-24 00:59:27 -07:00
|
|
|
```
|
2018-10-12 15:37:13 -04:00
|
|
|
Statements between the `if` statement and the `else` statement in an **else-if** flow are in the else-if format
|
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
### Hint 3
|
|
|
|
```javascript
|
2018-10-12 15:37:13 -04:00
|
|
|
else {
|
|
|
|
return "Between 5 and 10";
|
|
|
|
}
|
2019-07-24 00:59:27 -07:00
|
|
|
```
|
2018-10-12 15:37:13 -04:00
|
|
|
The last statement in an **else-if** flow is in the `else` format
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
|
|
|
|
---
|
|
|
|
## Solutions
|
|
|
|
|
|
|
|
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
|
|
|
|
2018-10-12 15:37:13 -04:00
|
|
|
```javascript
|
|
|
|
function testElseIf(val) {
|
|
|
|
if (val > 10) {
|
|
|
|
return "Greater than 10";
|
2019-07-24 00:59:27 -07:00
|
|
|
} else if (val < 5) {
|
2018-10-12 15:37:13 -04:00
|
|
|
return "Smaller than 5";
|
2019-07-24 00:59:27 -07:00
|
|
|
} else {
|
|
|
|
return "Between 5 and 10";
|
2018-10-12 15:37:13 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Change this value to test
|
|
|
|
testElseIf(7);
|
|
|
|
```
|
2019-07-01 06:49:24 -07:00
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
#### Code Explanation
|
2018-10-12 15:37:13 -04:00
|
|
|
The structure of an **else-if logic flow** is an initial `if` statement, one more `if-else` statements, and one final `else` statement.
|
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
#### Relevant Links
|
2018-10-12 15:37:13 -04:00
|
|
|
- ["if...else" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else)
|
2019-07-24 00:59:27 -07:00
|
|
|
</details>
|
2018-10-12 15:37:13 -04:00
|
|
|
|