Explain Codes LogoExplain Codes Logo

Switch Statement for Multiple Cases in JavaScript

javascript
switch-statement
higher-order-functions
best-practices
Nikita BarsukovbyNikita Barsukov·Aug 4, 2024
TLDR

Group multiple cases in a switch statement by listing them one after the other, without a break statement between them:

switch (fruit) { case 'apple': case 'pear': console.log('Brrr! Feel the chill, non-citrus fruit here.'); break; case 'orange': console.log("Oh, it's a bit tangy! Citrus fruit detected."); break; }

Here, when fruit is either apple or pear, the message "Brrr! Feel the chill, non-citrus fruit here." will display.

Utilizing Array Techniques and Object Mapping

Switch cases aren't just about fruit, they can dance with arrays too using includes():

const citrusFruits = ['orange', 'lemon', 'lime', 'grapefruit']; switch (true) { case citrusFruits.includes(fruit): console.log("Woah, that's citrusy! Stand back everyone!"); break; default: console.log("Phew, this one's tamer. Non-citrus fruit, folks."); }

Feeling rad? We can skip the switch completely and layout a map of functions in an object living up to the DRY (Don't Repeat Yourself) life:

const fruitCheck = { apple: () => console.log('Hold the vitamin C, non-citrus fruit here.'), pear: () => console.log('No need for the citrus press, got a pear here.'), orange: () => console.log('Stand back, citrusy deliciousness incoming!'), default: () => console.log('Unknown fruit, possibly alien. Approach with caution.') }; (fruitCheck[fruit] || fruitCheck.default)();

Be it an apple or orange, this fruity function's got it covered.

Advanced Techniques: Mining the JavaScript Gold

Harnessing the Power of Higher-Order Functions

Elevate the switch alternative game with higher-order functions:

const performAction = (action, ...args) => { const actions = { 'cook': food => console.log(`Cooking ${food}. Keep the extinguisher handy...just in case.`), 'clean': item => console.log(`Cleaning ${item}. Brace yourselves, bubbles coming!`) }; return (actions[action] || actions.default)(...args); }; performAction('cook', 'pasta');

performAction function here is like a personal assistant. Tell it what action you want done, it gets it handled.

Matrix-Level Guard Clauses

Become a code-ninja by roping in guard clauses:

const handleFruit = fruit => { if (!fruit) return console.log('No fruit was provided. You do realize humans need vitamins, right?'); const actions = /* as above */; (actions[fruit] || actions.default)(); }; handleFruit(null); // Will output: No fruit was provided. You do realize humans need vitamins, right?

Mastering Complex Scenarios

Turn into a JavaScript samurai by managing complex scenarios:

const complexFruitHandler = { apple: { color: 'red', taste: 'sweet' }, banana: { color: 'yellow', taste: 'mild' }, default: { color: 'unknown', taste: 'unknown' } }; const describeFruit = (fruit) => { const { color, taste } = complexFruitHandler[fruit] || complexFruitHandler.default; console.log(`This fruit is ${color} and tastes ${taste}. Who says you can't play food critic for a day?`); }; describeFruit('apple'); // Outputs: This fruit is red and tastes sweet. Who says you can't play food critic for a day?

Best Practices to Be the Code Master

  • Keep it DRY—Don't repeat yourself. You are not a parrot.
  • Make use of object literals to bring order in complex settings.
  • Include a default case. It's like a safety net, it's good to have one.
  • If repetition is your villain, make functions your superhero.
  • Code clean, code well. It's not just a mantra, but also a date magnet!