Switch Vs If/Else
Hi @chrscheuer,
in this code, you advised using if/else instead of switch:
this is what you said:
- "switch statement unfortunately doesn't make much sense, since you're switching on a constant, not a variable. AFAIK you can't make it work this way."
After some reading I noticed that an If/Else would be better for this case because it's more stable for booleans but couldn't understand where switching a constant is a problem, I thought I was switching boolean. In my mind was "switch to first true case".
Could you help me understand this better?
thank you so much for the time. ( and feel free to change the title for something more appropriate )
- Christian Scheuer @chrscheuer2021-04-19 15:20:37.368Z
Hi Samuel,
You were reversing how a switch statement works. In if/else statements, if you're testing for equality (comparing true to a variable) it doesn't matter if you're comparing true to a variable, or if you're comparing a variable to true.
But in a switch statement it works differently. In the switch(...), the ... needs to be the variable, and then what you have in your "case ..." clauses, those need to be the constants.
This is because the code under the hood takes your variable and tests it against a number of constants. I encourage you to google switch statements in general for Javascript, as I'm sure somebody else can explain it much better than me :)