js switch check object code example
Example 1: javascript object instead of switch
const dogSwitch = (breed) => ({
"border": "Border Collies are good boys and girls.",
"pitbull": "Pit Bulls are good boys and girls.",
"german": "German Shepherds are good boys and girls."
})[breed]
dogSwitch("border")
Example 2: javascript object instead of switch
function getDrink (type) {
var drinks = {
'coke': function () {
return 'Coke';
},
'pepsi': function () {
return 'Pepsi';
},
'lemonade': function () {
return 'Lemonade';
},
'default': function () {
return 'Default item';
}
};
return (drinks[type] || drinks['default'])();
}
Example 3: javascript object instead of switch
function getSnack (type) {
var snack;
function isDrink () {
return snack = 'Drink';
}
function isFood () {
return snack = 'Food';
}
var snacks = {
'coke': isDrink,
'pepsi': isDrink,
'cookies': isFood,
'crisps': isFood,
};
return snacks[type]();
}
var snack = getSnack('coke');
console.log(snack);