DEV Community

Discussion on: A Case Against Switches

aodev profile image
AoDev • Edited on

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
jckuhl profile image
Jonathan Kuhl Author

That's a good point.

miguelpinero profile image
Miguel Piñero • Edited on

Maybe you can do something like this:

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

This would not work. I have explained why above.