How to write an IF else statement without 'else' in JavaScript
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.
Save the value into a different variable.
function hideTable(){
var table = document.getElementById('PDemo');
var width = table.style.width;
if(width == "50%") table.style.width = "150px";
if(width == "150px") table.style.width = "50%";
}
if(/*condition a*/){/*statements a*/}else if(/*condition b*/){/*statements b*/}else{/*statements c/*}
One line only.