Cleaner Nested Conditionals
Using if statement we will get so much of nesting and if statement readability will reduce if the code size increases.
If Statement example:
if (item) {
if(item === 'palladium') {
printPalladiumPrice();
}
else if (item === 'silver') {
printSilverPrice();
}
else if (item === 'gold') {
printGoldPrice();
}
else if (item === 'platinum') {
printPlatinumPrice();
}
else if (item === 'diamond') {
printDiamonPrice();
}
else {
printAllItemPrice();
}
}
The same problem we will face with the Switch statement. If the size increases the Switch Case readability will reduce as shown below.
Switch Case example:
switch (item) {
case 'palladium':
printPalladiumPrice();
break;
case 'silver':
printSilverPrice();
break;
case 'gold':
printGoldPrice();
break;
case 'platinum':
printPlatinumPrice();
break;
case 'diamond':
printDiamondPrice();
break;
default:
printAllItemPrice();
}
If we use JSON OBJECT our conditions will reduce to one single if statement and code will be much readable. Below is the example to write Cleaner Nested Conditions using the JSON Object.
JSON Object example:-
const itemObj = {
'palladium': printPalladiumPrice,
'silver': printSilverPrice,
'gold': printGoldPrice,
'platinum': printPlatinumPrice,
'diamond': printDiamondPrice,
};
if (item in itemObj) {
itemObj[item]();
}
Our conditions are now reduced to one single if and code is much readable.
Good point nice logic
Thanks for sharing
What about default value in this case?