I’m glad my explanations helped you.
It’s a bit of an unusual usage of the switch
statement. Normally, you’ll see and use examples like at the top of the switch article where you have a variable as the switch expression and constant values in the cases. This exercise shows how flexible the switch statement is.
Working through the MDN JS courses is certainly a great start. Beside from that I think it’s important to be curious. When you see a JS method that you don’t know or don’t understand, read its MDN article, try out the examples, change them to see if the code behaves like you think it should.
When you are comfortable with the basics of JS, the next step would be to read about and experiment with front-end frameworks like ReactJS, Vue.js or Svelte. There are introductions to these on MDN as well. These will help you build (interactive) websites.
First, it calculates the switch expression and then it will calculate one case after the other until it finds one that matches the switch expression. When looking at our example the steps are as follows:
- Calculate the switch expression: Nothing to do because it’s already the value
true
.
- Calculate first case:
(score < 0 || score > 100)
becomes false
because the score
is 75.
- Compare the switch expression to the first case:
true === false
evaluates to false
, therefore the code of the first case won’t be executed.
- Same thing for cases two, three and four.
- Calculate fifth case:
(score >= 70 && score <= 89)
becomes true
because score
is between these values.
- Compare the switch expression to the fifth case:
true === true
evaluates to true
, therefore the code of the fifth case will be executed.
- The browser sees the
break
statement and leaves the switch
.
The same goes for more classic examples like the one at the top of the the switch article:
const expr = 'Papayas';
switch (expr) {
case 'Oranges':
console.log('Oranges are $0.59 a pound.');
break;
case 'Mangoes':
case 'Papayas':
console.log('Mangoes and papayas are $2.79 a pound.');
// Expected output: "Mangoes and papayas are $2.79 a pound."
break;
default:
console.log(`Sorry, we are out of ${expr}.`);
}
- The switch expression evaluates to
'Papayas'
.
-
'Papayas' === 'Oranges'
false
.
-
'Papayas' === 'Mangoes'
false
.
-
'Papayas' === 'Papayas'
true
.
- The code of the third case will be executed.
Yes, this is fine. Personally, I can’t guarantee that I have the time to look at it, but maybe someone else can help out.
It’s my pleasure to help you.
This is fine.
See you,
Michael