DEV Community

Discussion on: A Case Against Switches

Collapse
 
aodev profile image
AoDev • Edited

With your example it works because values are non empty strings.
But since you are explaining a pattern here, it must be said that the check for default value is actually buggy.

Any falsy value will lead to the default "branch" because using "if" like this will check the value at key "x" and not if the key exists, unlike switch that actually matches against case.

You should be checking if the key is defined instead.
An example could be:

return choices.hasOwnProperty(x) ? choices[x] : choices.default
Collapse
 
jckuhl profile image
Jonathan Kuhl

That's a good point.

Collapse
 
miguelpinero profile image
Miguel Piñero • Edited

Maybe you can do something like this:

return choices[x] || choices.default
Collapse
 
aodev profile image
AoDev

This would not work. I have explained why above.