How to convert switch-case to objects in JavaScript

In JavaScript, we use the switch case in a place where we need to handle multiple if...else if...else if... statements. For example:

function getEmoji(mood) {
if(mood === "happy") {
return 'πŸ˜ƒ';
} else if (mood === "sad") {
return 'πŸ˜”';
} else if (mood === "angry") {
return '😑';
} else {
return 'πŸ˜‘';
}
}
console.log("Getting angry emoji", getEmoji("angry"));

The above if statement can be replaced with:

function getEmoji(mood) {
switch(mood){
case 'happy':
return '😊';
case 'sad':
return 'πŸ˜”';
case 'angry':
return '😑';
default :
return 'πŸ˜‘';
}
}
console.log("Getting sad emoji", getEmoji("sad"));

You can replace the above switch statement with Object literals:

function getEmoji(mood) {
let emoji= {
'happy': '😊',
'sad': 'πŸ˜”',
'angry': '😑',
}[mood];
return emoji || 'πŸ˜‘';
}
console.log("Getting happy emoji", getEmoji("happy"));
console.log("Getting default emoji", getEmoji());
console.log("Getting haa emoji", getEmoji("haa"));

Why I changed from switch to Object-literal

  • Easily understandable
  • No need for a break statement
  • Minimal code
  • Can add new cases in object easily

Examples

Handling the default case

Define the default property in the object and check if the case label is found in the object. Otherwise, return the β€˜default’ property defined in the object:

function getEmoji(mood) {
let emojiObj = {
'happy': '😊',
'sad': 'πŸ˜”',
'angry': '😑',
'default': 'πŸ˜‘'
};
let emoji = emojiObj[mood] || emojiObj['default'];
return emoji;
}
console.log("Getting happy emoji", getEmoji("happy"));
console.log("Getting default emoji", getEmoji());
console.log("Getting haa emoji", getEmoji("haa"));

Handling functions

function getEmoji(mood) {
let emojiObj = {
'happy': () => "😊",
'sad': () => 'πŸ˜”',
'angry': () => '😑',
'default': () => 'πŸ˜‘'
};
let emoji = emojiObj[mood] || emojiObj['default'];
return emoji();
}
console.log("Getting angry emoji", getEmoji("angry"));

Handling single action for multiple cases

Let’s write it in switch-case first:

function getEmoji(mood) {
switch(mood){
case "happy":
case "haha":
case "hahaha":
return '😊';
default :
return 'πŸ˜‘';
}
}

We can implement this in Object literals by adding a possible label with the same value:

function getEmoji(mood) {
let emojiObj = {
'happy': '😊',
'haha' : '😊',
'hahaha' : '😊',
'default': 'πŸ˜‘'
};
let emoji = emojiObj[mood] || emojiObj['default'];
return emoji;
}
console.log("Getting happy emoji", getEmoji('happy'));
console.log("Getting default emoji", getEmoji());

Free Resources