Graduated in Digital Media M.Sc. now developing the next generation of educational software. Since a while I develop full stack in Javascript using Meteor. Love fitness and Muay Thai after work.
Little OT here. I think switches are great for revealing unexpected program flows in a multi branch szenario, which is why the exact match condition is so important.
You want your program being as deterministic as possible and therefore throw exceptions when the program deviates at any point. Switches are a nice way to do that:
f=value=>{case'foo':returnstateA()case'bar':returnstateB()default:thrownewError(`No state for ${value}`)}
Relying on truthy/falsy for branching is a great feature of Js but can also lead to false positives / false negatives (think empty Strings, Number 0) that require much more tests than being explicit in the first place.
I agree with your initial point, but not necessarily that switches are the answer.
In your example, I'd probably do something like:
conststates={foo:stateA,bar:stateB};constf=(value)=>{if(!(valueinstates)){thrownewError(`No state for ${value}`);}returnstates[value]();}
...or more generically assuming things weren't as 1-to-1...
constf=(value)=>{if(value==='foo'){returnstateA();}if(value==='bar'){returnstateB();}thrownewError(`No state for ${value}`);}
The second is probably the easiest to understand out of all of them (including the switch imo) so I'd probably lean towards that, but in every case, undefined behaviours are caught appropriately.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Little OT here. I think switches are great for revealing unexpected program flows in a multi branch szenario, which is why the exact match condition is so important.
You want your program being as deterministic as possible and therefore throw exceptions when the program deviates at any point. Switches are a nice way to do that:
Relying on truthy/falsy for branching is a great feature of Js but can also lead to false positives / false negatives (think empty Strings, Number 0) that require much more tests than being explicit in the first place.
I agree with your initial point, but not necessarily that switches are the answer.
In your example, I'd probably do something like:
...or more generically assuming things weren't as 1-to-1...
The second is probably the easiest to understand out of all of them (including the switch imo) so I'd probably lean towards that, but in every case, undefined behaviours are caught appropriately.