user1853128
user1853128

Reputation: 1114

shortHand if else-if and else statement

I have nested if else statements, which I added below in two statements, Instead of having a lot of lines I am looking to shorthand it.

Can anyone help me out.

In Below statements in Statement1: a&&b and C&&d, a,b,c,c are arrays. In statement2 its a keywords.

Statement1:

        if((a && b)!== -1){
            abc ="hai"
        }
        else if ((c && d)!== -1) {
            abc="hello"
        }
        else{
           abc="Hurray"
        }

Statement 2:

               if(a==="abc"){
                if(bb==="def"){
                    amd ="hello"
                }
                else if(bb==="ghi"){
                    amd ="hai"
                }
                else{
                    amd = "Hurray";
                }
            }
            else if(a==="qwe"){
                if(aaa==="ddd") {
                    amd = "Hurray Hi";
                }
                else{
                    amd = "Hurray bye";
                }
            }

Upvotes: 15

Views: 64210

Answers (3)

Md Masud
Md Masud

Reputation: 2711

var a = 1;

var result  =  a == 1 ? 'kid' : a == 2 ? 'boy' : 'girl';

equivalent of :

var a = 1;
var result = '';
if(a == 1){
   result = 'kid';
}elseif(a == 2){
   result = 'boy';
}else{
   result = 'girl';
}

Upvotes: 3

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

Statement : 1 can be written as,

abc = (a !== -1 && b!== -1) ? "hai" : (c !== -1 && d!== -1) ? "hello" : "hurray";

So based on this try to write your own code for the statement 2 [Hint : use switch for that]

Upvotes: 37

user3704987
user3704987

Reputation: 43

The short hand version is know as Ternary logic. It is pretty simple but if you have conditions that need a lot of updating, it might get confusing. But here it is:

Statement 1:

var a = -1;
var b = -1;
var c = -1;
var d = -1;

result = ((a && b) !== -1) ? 'hai' :
     ((c && d) !== -1) ? 'hello' : 'hurray';

alert(result);

Statement 2:

var a = 'abc';
var bb = 'def';

// plug in the remaining variables to test further 

result = (a === 'abc') ? (bb === 'def') ? amd = 'hello' :
         (bb === 'ghi') ? amd = 'hai' : amd = 'Hurray' :
     (a === 'que') ? (aaa === 'ddd') ? amd = 'Hurray Hi' : amd = 'Hurray Bye' : 
     'default result was missing from your statment';

alert(result);

That should do it. Although it is 'shorthand', it can be more confusing in the long run.

Upvotes: 4

Related Questions