DEV Community

Cover image for Switching up the switch statement
Miqotes
Miqotes

Posted on

3 2

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!

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay