Hello Everyone, Welcome to my blog 🙏. I hope you are all safe and that this blog finds you in good health ❤️.
In this blog, we will learn about
Switch vs Object Literals
Switch
const returnFruit = (number) => {
switch (number) {
case 1:
console.log("Orange");
break;
case 2:
console.log("Mango");
break;
case 3:
console.log("Banana");
break;
case 4:
console.log("Apple");
break;
default:
console.log("unknown");
break;
}
};
returnFruit(1); // Orange
returnFruit(2); // Mango
returnFruit(3); // Banana
returnFruit(4); // Apple
returnFruit(5); // unknown
Object Literal without default
const returnFruit = (number) => {
return {
1: "Orange",
2: "Mango",
3: "Banana",
4: "Apple"
}[number];
};
console.log(returnFruit(1)); // Orange
console.log(returnFruit(2)); // Mango
console.log(returnFruit(3)); // Banana
console.log(returnFruit(4)); // Apple
console.log(returnFruit(5)); // undefined
Object with default
const returnFruit = (number) => {
return (
{
1: "Orange",
2: "Mango",
3: "Banana",
4: "Apple"
}[number] || "unknown"
);
};
console.log(returnFruit(1)); // Orange
console.log(returnFruit(2)); // Mango
console.log(returnFruit(3)); // Banana
console.log(returnFruit(4)); // Apple
console.log(returnFruit(5)); // unknown
--------------------------------------------------------------------------------------------------------
Here we go, That’s it folks for this blog.
Hope everyone liked it. If you like it, give it a love ❤️ , and share it with your friend.
For more exciting content on Frontend,
Please do follow me 🎯.
Thanks a lot, Everyone 🙏. Until Next time, Happy Learning ✍️
Abhishek Kovuri, UI developer