Skip to content Skip to sidebar Skip to footer

Ternary Operator With Multiple Operations

Can I use a ternary operator when I have more than one operation to perform per case? For example can I use it here?: if (dwelling) { dwelling = dwelling[0].nodeValue;

Solution 1:

Although i highly advice against it for the sake of readability and extensibility you could:

dwelling ? (dwelling = dwelling[0].nodeValue, letterDwelling=dwelling[0].toUpperCase()) : (dwelling = letterDwelling = "");

Solution 2:

To avoid the side effects using the comma-notation you could use self-invoking functions instead which can handle your code:

(foo == bar) ? doSomething() : (function(){
    // here you can write all your code// and even return something useful
})();

Solution 3:

Yes, see: Conditional (ternary) Operator

var dwelling = true;
(dwelling) ? (
    dwelling = 'a',      //first operation
    letterDwelling = 'a'//second operation
) : (
    dwelling = 'b',
    letterDwelling = 'b'
);
alert(dwelling);

jsfiddle example

Post a Comment for "Ternary Operator With Multiple Operations"