Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write an IF else statement without 'else' in JavaScript [closed]

Tags:

javascript

I can't use else in my script; how can I implement an if else statement without using else?

I'm trying to resize a div:

function hideTable(){
    var table = document.getElementById('PDemo');
    if(table.style.width == "50%") table.style.width = "150px";
    if(table.style.width == "150px") table.style.width = "50%";
}

This script doesn't work because as soon as the first if statement is executed, the condition for the second if statement becomes true, so that executes too, and thus nothing changes.

like image 583
code511788465541441 Avatar asked Mar 22 '11 13:03

code511788465541441


1 Answers

The ternary operator:

condition ? execTrue() : execFalse();

This is equivalent to:

if (condition) {
    execTrue();
}
else {
    execFalse();
}

You can write an if/else in 1 line, just don't press enter...

if (condition) { execTrue(); } else { execFalse(); }

Further, you can write any statement of arbitrary complexity on one line:

if(condition1) { exec1(); } else if(condition2) { exec2(); } else { execFalse() }

If you're having the issue where the second if statement executes as well, you want to impose mutual exclusion, i.e., using else if instead of just if on each subsequent conditional.

like image 159
Travis Webb Avatar answered Nov 15 '22 11:11

Travis Webb