16
u/pookage helpful May 31 '22
Also, your switch statements can now include blocks:
switch(grade){
case "A": {
const message = "Great job!";
console.log(message);
break;
}
case "B": {
const message = "OK Job";
console.log(message);
break;
}
...etc...
}whereas without:
switch(grade){
case "A":
const message = "Great job!";
console.log(message);
break;
case "B":
const message = "OK Job"; // ERROR - const message already declared
console.log(message);
break;
...etc...}
1
8
May 31 '22
[removed] — view removed comment
5
1
u/opticsnake Jun 01 '22
If you don't break, it will execute the block and then still fall through to the default block.
Although, this does feel like a special case for break anyways since the scope it would be breaking on would be the case block and not the whole switch statement...
12
u/lindymad May 31 '22
In Javascript, can a switch contain multiple cases for one rule? e.g.
switch(grade){
case "A":
case "B":
console.log("Above Average");
break;
case "C":
console.log("Average");
break;If so, might be worth mentioning in the example?
2
3
2
May 31 '22
I don't really use switch cases often as I was under the impression that the cases can only be exact values like case 'a': rather than case if (grade>75): and I often end up using multiple if statements. I've often seen advice like ' if you are using more than three if statements it's time to refactor to a switch statement' but I've never been able to do that.
I've just learned of enums in C and I do see switch cases used a lot more there because of it, but unless I'm misunderstanding switch statments it seems less useful in JS than other languages.
1
u/Jay_Hogwarts May 31 '22 edited May 31 '22
So I had a scenario like this recently where one of my cases needed to be a conditional. I used a ternary operator to solve it e.g. case (grade > 75 ? grade : null)
2
1
u/Tintin_Quarentino May 31 '22
Switch case is <3... Wonder why hasn't Python done it yet? I know we can do dict & use that as switch case, but official low level implementation would be so much better.
2
u/BlitzAtk Jun 01 '22
Please more of these explanation pieces. I get confused easily with the more complex JS examples.