This content originally appeared on DEV Community and was authored by Bernardo Torres
Introduction
In this example we have a 'color' variable and a 'colorPsychology' variable, 'colorPsychology' will be assigned a string depending of the value of 'color', so in this case a switch statement works fine. The problem is that since we're just executing one line of code, it ends up being unnecessary long, so we could use a different approach. Lets see
Using an object instead
A good approach would be using an object where the keys are the names of the color and the values are their respective color psychology
The value assignment of 'colorPsychology' could be a little confusing, but here's what's happening:
- the colorPsychology variable is created
- JS looks for the the value of the key color in our colorPsyOptions object
- since the key is the color variable and this contains a string 'blue', JS will look for the value of the 'blue' key in our object
- If the 'color' variable contains a value that doesn't isn't a key in our object, it will assign a string 'unknow'
Don't understand objects yet? check the MDN docs
Using an array when using numbers
In case we're using numbers as keys, we could use a shorter version with an array, like this:
We can do something like this:
When to use these approaches
When you're just assigning values in the switch statement
Exercises
Replace the following switch statements with the previous approach
You can use playcode
Fruit names translation
Planet names
Results
Exercise 1
Exercise 2
I hope this was useful to you and consider following me on Twitter as @pallascodes, I'll be posting daily JavaScript content there
This content originally appeared on DEV Community and was authored by Bernardo Torres
Bernardo Torres | Sciencx (2021-08-02T19:58:48+00:00) Stop using switches the wrong way, use this instead. Retrieved from https://www.scien.cx/2021/08/02/stop-using-switches-the-wrong-way-use-this-instead/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.