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"));
switch
to Object-literal
break
statementDefine 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"));
function getEmoji(mood) {let emojiObj = {'happy': () => "π",'sad': () => 'π','angry': () => 'π‘','default': () => 'π'};let emoji = emojiObj[mood] || emojiObj['default'];return emoji();}console.log("Getting angry emoji", getEmoji("angry"));
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());