Skip to content Skip to sidebar Skip to footer

How To Shorten A Long If Else Statement

I'm trying to figure out how I can streamline a possible long if else statement. There are 8 possibilities that can be chosen and for each option 1-8 I want to display a message. F

Solution 1:

Use a map:

var messages = {
    '1' : 'Greater than 1',
    '2' : 'Greater than 2',
   ....etc
}

console.log(messages[this.cv]);

Solution 2:

If that is the exact format of your message (for all cases), then you could simply write:

console.log('Greater Than ' + this.cv);

However, if you need more flexibility with each case, then you can use a switch statement as other answers have suggested.

Solution 3:

Use a switch statement:

switch(this.cv)
{
case'1':
  console.log('Greater Than 1');
  break;
case'2':
  console.log('Greater Than 2');
  break;
default:
  //executed if no matches are found
}

Or a map would work also work well per adeneo's answer, since that is essentially how a switch statement is implemented. Both are good options for compressing several if-statements.

Solution 4:

This is what the switch statement was made for.

switch(this.cv) {
case'1':
    console.log("Greater than 1");
    break;
case'2':
    console.log("Greater than 2");
    break;
}

You can even add a "catch-all" default action:

default:
    console.log("I don't know what to do with "+this.cv);

Solution 5:

switch(n)
{
case'1':
  execute code block 1break;
case'2':
  execute code block 2break;
default:
  code to be executed if n is different fromcase1and2
}

Post a Comment for "How To Shorten A Long If Else Statement"