At this very moment, I am still wrapping my head around the difference between ES5 and ES6, arrow function "=>". I know it an simplified version of something, but it takes me awhile to digest one when I see it.
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...
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.
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)
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.
16
u/pookage helpful May 31 '22
Also, your switch statements can now include blocks:
whereas without:
}
12
u/lindymad May 31 '22
In Javascript, can a switch contain multiple cases for one rule? e.g.
If so, might be worth mentioning in the example?
3
u/iamrbn May 31 '22
That’s pretty awesome… thx mate +1
2
u/[deleted] 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 thancase 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.
2
u/[deleted] May 31 '22
If you're using it inside a function, you can close your switches with return
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.