Switch for a object
-
Others
// Switch case example
function processFruit(fruit) {
switch (fruit) {
case 'apple':
console.log('Selected fruit: apple');
// Process apple
break;
case 'banana':
console.log('Selected fruit: banana');
// Process banana
break;
case 'orange':
console.log('Selected fruit: orange');
// Process orange
break;
default:
console.log('Invalid fruit selection');
// Handle invalid selection
break;
}
}
processFruit('banana');
// Object example
const fruitProcessors = {
apple: () => {
console.log('Selected fruit: apple');
// Process apple
},
banana: () => {
console.log('Selected fruit: banana');
// Process banana
},
orange: () => {
console.log('Selected fruit: orange');
// Process orange
},
default: () => {
console.log('Invalid fruit selection');
// Handle invalid selection
},
};
function processFruit(fruit) {
const processor = fruitProcessors[fruit] || fruitProcessors.default;
processor();
}
processFruit('banana');