Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Conditional shortcut. More then one else if

Tags:

javascript

Can we have more then one else if statement using the conditional shortcut.

var x = this.checked ? y : z;
like image 965
Pinkie Avatar asked Dec 09 '22 05:12

Pinkie


1 Answers

You can abuse the comma operator, since it evaluates both its operands and returns the second one:

var x = this.checked ? y : doSomething(), doSomethingElse(), z;

However, that makes the code less readable (and maintainable) than the corresponding if statement:

var x;
if (this.checked) {
    x = y;
} else {
    doSomething();
    doSomethingElse();
    x = z;
}

So I would recommend using an if statement in your case.

like image 162
Frédéric Hamidi Avatar answered Dec 26 '22 12:12

Frédéric Hamidi