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 @BernardoT0rres, I'll be posting daily JavaScript content there
Top comments (3)
Your first code image switch statement uses
colorPsychology
when it should usecolor
as the condition. Other than that, it's a good approach when your switch statement produces basic results 👍My only other suggestion to your article would be to use actual code snippets instead of screenshots so readers with assistive technology can benefit.
Oohh no, I uploaded the wrong image. Hahahah thanks for the comment
You can also use this approach to break more complex switch cases into object functions, allowing you to turn this
into this