javascript - Expand a ternary statement or switch to if-else -


i have following works fine 2 conditions:

var value = this.value === "foo" ? function(d) {     return d.foo; } : function(d) {     return d.bar; }; 

what doing wrong when try expand above following using if-else?

var value =  if (this.value === "foo") {         function(d) {             return d.foo;         };     } else if (this.value === "bar") {     function(d) {         return d.bar;     }; } else {     function(d) {         return d.qux;     }; } 

i'm happy stick operators or switching if-else : whatever more readable me.

if cannot used on right-hand side of assignment statement (which part of why have conditional operator).

instead, assign in each branch:

var value; if (this.value === "foo") {     value = function(d) {         return d.foo;     }; } else if (this.value === "bar") {     value = function(d) {         return d.bar;     }; } else {     value = function(d) {         return d.qux;     }; } 

although note that particular code can simplified:

var key = this.value == "foo" || this.value == "bar" ? this.value : "qux"; var value = function(d) {     return d[key]; }; 

Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -