Files

49 lines
1.2 KiB
Markdown
Raw Normal View History

2018-10-12 15:37:13 -04:00
---
title: Introducing Else statements
---
# Introducing Else statements
2018-10-12 15:37:13 -04:00
---
## Hints
### Hint 1
2018-10-12 15:37:13 -04:00
When the first `if` statement returns `false` the next piece of code is executed/evaluated (like `return`, `if` or `else` statements).
### Hint 2
2018-10-12 15:37:13 -04:00
Sometimes `if` (`condition`) statements can be replaced by `else {code to execute instead} ` statements (in essence you are telling your function to do _"y"_ if it can't do _"x"_ instead of specifying _"x"_ several times) .
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
2018-10-12 15:37:13 -04:00
```javascript
function testElse(val) {
var result = "";
// Only change code below this line
2018-10-12 15:37:13 -04:00
if (val > 5) {
result = "Bigger than 5";
} else {
2018-10-12 15:37:13 -04:00
result = "5 or smaller";
}
2018-10-12 15:37:13 -04:00
// Only change code above this line
return result;
}
// Change this value to test
testElse(4);
```
#### Code Explanation
2018-10-12 15:37:13 -04:00
The function first evaluates `if` the condition `val > 5` evaluates to `true`. If it doesn't, it executes the next statement (`else { return "5 or smaller";})`.
#### 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)
</details>