DEV Community

Cover image for Switching up the switch statement
Miqotes
Miqotes

Posted on

Switching up the switch statement

Let us talk a little about switch statements!

Switch statements can replace multiple if statements. You can compare values against multiple variants in a not as clunky-looking way as if statements.

You don't want to burn yourself out doing this:

When you can do this instead:

let a = 2 + 2;

switch (a) {
  case 3:
    alert( 'Not enough.' );
  case 4:
    alert( 'Perfect!' );
  case 5:
    alert( 'No more, stop.' );
  default:
    alert( 'What even is this?' );
}
Enter fullscreen mode Exit fullscreen mode
  • The value of a is being checked for strict equality against each case. case 3 would fail because 2 + 2 isn't equal to 4.
  • The switch statement will continue on until it hits a case that matches. Then it will execute the corresponding code until it hits a break or until the end of the switch.
  • If zero cases match, then the default code is executed instead.

This feels comfortable, right?

But did you know you could use objects?

let thing = {
    "abc": () => "meow",
    "chonk": () => "very angry",
    "littlecat": (how_many) => {
        if(how_many > 5) { return "MEGAMEOW" }
        else { return `${how_many}x meow/scream` }
    },
};
Enter fullscreen mode Exit fullscreen mode

This is an object.

This object is the same as this switch statement.

switch("littlecat") {
    case "abc": () => "meow"
    break;

    case "chonk": () => "very angry"
    break;

    case "littlecat": (how_many) => {
        if(how_many > 5) { return "MEGAMEOW" }
        else { return `${how_many}x meow/scream` }
    }
    break;
}()

Enter fullscreen mode Exit fullscreen mode

You can call one of the fields of this object like so.
thing.chonk()

Another way you can access it is by:
thing["chonk"]()

Calling thing["littlecat"](6) will return you "MEGAMEOW". If you change the input to 3, it will return "3x meow/scream"

This is how you can use an object like a switch statement!

Top comments (0)