Skip to content

Commit 85e0baa

Browse files
junedevSleeplessBytetejasbubane
authored
[V3] Add Concept Exercise: While and Switch (#1073)
Co-authored-by: Derk-Jan Karrenbeld <[email protected]> Co-authored-by: Tejas Bubane <[email protected]>
1 parent 1bd15ea commit 85e0baa

File tree

23 files changed

+891
-0
lines changed

23 files changed

+891
-0
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"blurb": "Besides the if-statement, JavaScript also has a switch-statement to conditionally execute logic. It is used when a single variable needs to be compared to multiple variants.",
3+
"authors": ["junedev"],
4+
"contributors": []
5+
}
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
# About
2+
3+
## General Syntax
4+
5+
Besides the if-statement, JavaScript also has a switch-statement to conditionally execute logic.
6+
It is used when a single variable needs to be compared to multiple variants.
7+
The comparison is done by checking for strict equality (`===`), see [concept comparison][concept-comparison].
8+
For some variable `x`, the switch statement in JavaScript has the following syntax.
9+
10+
<!-- prettier-ignore-start -->
11+
```javascript
12+
switch (x) {
13+
case option1:
14+
// code that is executed when "x === option1" is true
15+
break;
16+
case option2:
17+
// code that is executed when "x === option2" is true
18+
break;
19+
default:
20+
// code that is executed when x does not equal any of the options
21+
}
22+
```
23+
<!-- prettier-ignore-end -->
24+
25+
The `default` case is optional and used in case you want to execute some code if none of the other options match the variable.
26+
27+
## Fallthrough by Default
28+
29+
The `break` statements above are needed because by default all cases are "fallthrough" in JavaScript.
30+
That means without any `break` statement all the code in the cases below the first matching option would be executed even though `x` did not match those options.
31+
This "fallthrough by default" behavior is a common pitfall when using `switch` in JavaScript.
32+
Inside a function, `return` can also be used instead of `break` to avoid this problem.
33+
34+
You can use the fallthrough behavior to your advantage when you want to apply the same code for multiple cases.
35+
You can find an example of this in the [MDN documentation][mdn-group-cases].
36+
37+
## Scope
38+
39+
By default the variables in the different `case` statements share the same scope.
40+
This can lead to unexpected behavior.
41+
For example due to copying and pasting a case, you could end up with a `let message` declaration in two cases which results in an error, see [MDN documentation][mdn-switch-scope].
42+
To avoid problems due to the shared scope, you can create a separate scope for each case statement by adding code blocks with curly brackets for each case.
43+
44+
```javascript
45+
switch (x) {
46+
case option1: {
47+
// Variables declared here are contained to this case.
48+
break;
49+
}
50+
case option2: {
51+
// ...
52+
break;
53+
}
54+
default: {
55+
// ...
56+
}
57+
}
58+
```
59+
60+
## Using Expressions
61+
62+
Instead of a variable `x`, you can also use an expression.
63+
That expression is evaluated once at the beginning of the switch statement and the result compared against the cases.
64+
A common use of this is a "type switch" that executes different code depending on the type of a variable.
65+
66+
<!-- prettier-ignore-start -->
67+
```javascript
68+
switch (typeof x) {
69+
case 'string':
70+
// code that is executed when x is a string
71+
break;
72+
case 'number':
73+
// code that is executed when x is a number
74+
break;
75+
default:
76+
// code that is executed when x has some other type
77+
}
78+
```
79+
<!-- prettier-ignore-end -->
80+
81+
The options can be expressions as well.
82+
83+
[concept-comparison]: /tracks/javascript/concepts/comparison
84+
[mdn-group-cases]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch#methods_for_multi-criteria_case
85+
[mdn-switch-scope]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch#block-scope_variables_within_switch_statements
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Introduction
2+
3+
Besides the if-statement, JavaScript also has a switch-statement to conditionally execute logic.
4+
It is used when a single variable needs to be compared to multiple variants.
5+
The comparison is done by checking for strict equality (`===`), see [concept comparison][concept-comparison].
6+
For some variable `x`, the switch statement in JavaScript has the following syntax.
7+
8+
<!-- prettier-ignore-start -->
9+
```javascript
10+
switch (x) {
11+
case option1:
12+
// code that is executed when "x === option1" is true
13+
break;
14+
case option2:
15+
// code that is executed when "x === option2" is true
16+
break;
17+
default:
18+
// code that is executed when x does not equal any of the options
19+
}
20+
```
21+
<!-- prettier-ignore-end -->
22+
23+
The `default` case is optional and used when you want to execute some code if none of the other options match the variable.
24+
25+
The `break` statements above are needed because by default all cases are "fallthrough" in JavaScript.
26+
That means that without any `break` statement all the code in the cases below the first matching option would be executed even though `x` did not match those options.
27+
This "fallthrough by default" behavior is a common pitfall when using `switch` in JavaScript.
28+
Inside a function, `return` can also be used instead of `break` to avoid this problem.
29+
30+
[concept-comparison]: /tracks/javascript/concepts/comparison
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
[
2+
{
3+
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch",
4+
"description": "MDN: Switch Statement"
5+
}
6+
]
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"blurb": "Execute code repeatedly as long as a certain condition is fulfilled. Depending on when that condition should be checked, you can use a while or a do-while loop in JavaScript.",
3+
"authors": ["junedev"],
4+
"contributors": []
5+
}

concepts/while-loops/about.md

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
# About
2+
3+
## General Syntax
4+
5+
With a while loop you can execute code repeatably as long as a certain condition is fulfilled.
6+
7+
It is written with the `while` keyword followed by a condition wrapped in round brackets and a code block that contains the _body_ of the loop wrapped in curly brackets.
8+
9+
```javascript
10+
while (condition) {
11+
// code that is executed repeatedly as long as the condition is true
12+
}
13+
```
14+
15+
JavaScript also has a do-while loop.
16+
Here the condition is checked after the loop body was executed.
17+
This is useful when the condition depends on evaluations done in the body.
18+
19+
```javascript
20+
do {
21+
// The code here will always be executed once and then
22+
// repeatedly while the condition is true.
23+
} while (condition);
24+
```
25+
26+
## Break
27+
28+
Inside a loop body you can use the `break` keyword to stop the execution of the loop entirely.
29+
This is often used in combination with `true` as condition.
30+
With that, you can control when the loop should stop from any place inside the loop body.
31+
32+
```javascript
33+
const winningNumber = 7;
34+
35+
while (true) {
36+
const num = readUserGuess();
37+
if (num === winningNumber) {
38+
break;
39+
}
40+
}
41+
```
42+
43+
The `break` keyword cannot be used inside a function that is nested in the loop, see the [MDN documentation][mdn-break-in-function] for an example.
44+
45+
## Continue
46+
47+
In contrast to `break`, the keyword `continue` only stops the execution of the current iteration and continues with the next one.
48+
With `continue` you can often avoid wrapping big parts of the loop body in an if-statement.
49+
50+
```javascript
51+
let i = 0;
52+
53+
while (i < 100) {
54+
i = i + 2;
55+
56+
if (i % 3 === 0) {
57+
continue;
58+
}
59+
60+
// The code here will only executed when i was not divisible
61+
// by 3 in the check above.
62+
}
63+
```
64+
65+
## Infinite Loops
66+
67+
A loop that is (theoretically) repeated forever is created when the loop condition is always fulfilled and no break or return statement is reached in the loop body.
68+
The execution has to be terminated from the outside.
69+
Depending on the environment in which such code runs, this will be done automatically or needs a manual intervention.
70+
71+
```javascript
72+
let i = 0;
73+
74+
while (i < 100) {
75+
if (i % 3 === 0) {
76+
continue;
77+
}
78+
79+
i = i + 2;
80+
}
81+
82+
// This loop runs forever since the variable i does not change
83+
// anymore after it is divisible by 3 the first time.
84+
```
85+
86+
Spotting infinite loops might seem trivial in this toy example, but is not always that easy with more complex code.
87+
It is good practice to thoroughly think about whether your condition eventually becomes false or whether your break or return statement is actually reached.
88+
89+
[mdn-break-in-function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break#break_within_functions
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Introduction
2+
3+
With a while loop you can execute code repeatably as long as a certain condition is fulfilled.
4+
It is written with the `while` keyword followed by a condition wrapped in round brackets and a code block that contains the _body_ of the loop wrapped in curly brackets.
5+
6+
```javascript
7+
while (condition) {
8+
// code that is executed repeatedly as long as the condition is true
9+
}
10+
```
11+
12+
JavaScript also has a do-while loop.
13+
Here the condition is checked after the loop body was executed.
14+
This is useful when the condition depends on the outcome of the code in the body.
15+
16+
```javascript
17+
do {
18+
// The code here will always be executed once and then
19+
// repeatedly while the condition is true.
20+
} while (condition);
21+
```
22+
23+
Inside a loop body you can use the `break` keyword to stop the execution of the loop entirely.
24+
In contrast to this, the keyword `continue` only stops the execution of the current iteration and continues with the next one.
25+
With `continue` you can often avoid wrapping big parts of the loop body in an if-statement.
26+
27+
```javascript
28+
let i = 0;
29+
30+
while (i < 100) {
31+
i = i + 2;
32+
33+
if (i % 3 === 0) {
34+
continue;
35+
}
36+
37+
// The code here will only executed when i was not divisible
38+
// by 3 in the check above.
39+
}
40+
```

concepts/while-loops/links.json

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
[
2+
{
3+
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while",
4+
"description": "MDN: While Loop"
5+
},
6+
{
7+
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while",
8+
"description": "MDN: Do-While Loop"
9+
},
10+
{
11+
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break",
12+
"description": "MDN: break"
13+
},
14+
{
15+
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue",
16+
"description": "MDN: continue"
17+
}
18+
]

config.json

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,14 @@
157157
"concepts": ["for-loops", "increment-decrement"],
158158
"prerequisites": ["arrays", "comparison", "conditionals"],
159159
"status": "beta"
160+
},
161+
{
162+
"slug": "mixed-juices",
163+
"name": "Mixed Juices",
164+
"uuid": "81c3fb86-af86-4c56-a45f-e021403c4070",
165+
"concepts": ["while-loops", "conditionals-switch"],
166+
"prerequisites": ["comparison", "conditionals", "arrays"],
167+
"status": "beta"
160168
}
161169
],
162170
"practice": [
@@ -1643,6 +1651,16 @@
16431651
"uuid": "a2347a19-1e44-449b-9741-94eda00d8ba7",
16441652
"slug": "increment-decrement",
16451653
"name": "Increment and Decrement Operators"
1654+
},
1655+
{
1656+
"uuid": "4e68e39a-e36c-4d2d-8714-eb6482e31ff5",
1657+
"slug": "while-loops",
1658+
"name": "While Loops"
1659+
},
1660+
{
1661+
"uuid": "d5d54931-b2a7-4b1a-a593-ad85a2810f2f",
1662+
"slug": "conditionals-switch",
1663+
"name": "Switch Statement"
16461664
}
16471665
],
16481666
"key_features": [
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Hints
2+
3+
## 1. Determine how long it takes to mix a juice
4+
5+
- Set up a [switch statement][mdn-switch] for the `name` variable.
6+
- The different cases should represent the different juice names.
7+
- Use the `default` case to cover all other names.
8+
- Remember that the cases are [fallthrough by default][mdn-fallthrough] so make sure you did something to prevent that behavior.
9+
10+
## 2. Replenish the lime wedge supply
11+
12+
- Use a [while loop][mdn-while] to cut one lime after the other.
13+
- Revisit the [arrays concept][concept-arrays] to find a way to remove the limes from the list in the correct order.
14+
- Set up a [switch statement][mdn-switch] to get the number of wedges for a certain size of a lime.
15+
- You need to keep track of two things, how many limes where already cut and how many wedges are still missing.
16+
- You can combine two conditions for the loop using [logical operators][concept-booleans].
17+
18+
## 3. Finish up the shift
19+
20+
- Use a [do-while loop][mdn-do-while] to handle one order after the other.
21+
- Revisit the [arrays concept][concept-arrays] to find a way to remove the drinks from the list in the correct order.
22+
- You already have a function that determines the time it takes to prepare a drink, use it to reduce the time that is left accordingly.
23+
- You can combine two conditions for the loop using [logical operators][concept-booleans].
24+
25+
[mdn-switch]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch#
26+
[mdn-fallthrough]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch#what_happens_if_i_forgot_a_break
27+
[mdn-while]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while
28+
[mdn-do-while]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while
29+
[concept-booleans]: /tracks/javascript/concepts/booleans
30+
[concept-arrays]: /tracks/javascript/concepts/arrays

0 commit comments

Comments
 (0)