Cleaner Nested Conditionals

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.


To view or add a comment, sign in

More articles by Vishal Sharma

  • Debounce in JavaScript - Improve Your Application’s Performance

    What is Debouncing? Debouncing is a programming practice used to reduce unnecessary time-consuming computations so as…

    1 Comment
  • Memoization In JavaScript

    Memoization is an optimization technique used in many programming languages to reduce the number of redundant expensive…

    1 Comment

Explore content categories