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";
}
}
Shorthand if and if else is nothing but a way to write the if statements in one line when we have only one statement to execute in the if block and the else block.
Conditional StatementsUse if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.
The if-else statement in C language is used to execute the code if the condition is true or false. It is also called a two-way selection statement.
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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With