DEV Community

Cover image for Stop using switches the wrong way, use this instead
Bernardo Torres
Bernardo Torres

Posted on • Updated on

Stop using switches the wrong way, use this instead



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:

  1. the colorPsychology variable is created
  2. JS looks for the the value of the key color in our colorPsyOptions object
  3. 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
  4. 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:

Instead of using this:

We can do something like this:

When to use these approaches

When you're just assigning values in the switch statement


Replace the following switch statements with the previous approach

You can use playcode

Fruit names translation


Planet names



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)

jamesthomson profile image
James Thomson

Your first code image switch statement uses colorPsychology when it should use color 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.

pallascodes profile image
Bernardo Torres

Oohh no, I uploaded the wrong image. Hahahah thanks for the comment

thepeoplesbourgeois profile image
Josh • Edited

You can also use this approach to break more complex switch cases into object functions, allowing you to turn this

switch (fruit) {
  case 'banana': = 'yellow';
  case 'grape': = 'purple'; = 'white';
Enter fullscreen mode Exit fullscreen mode

into this

const fruitThemes = {
  set_banana() { = 'yellow';
  set_grape() { = 'purple'; = 'white';

Enter fullscreen mode Exit fullscreen mode