whytheq whytheq - 21 days ago 6
Javascript Question

Expand a ternary statement or switch to if-else

I have the following which works fine with two conditions:

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


What am I doing wrong when I try to expand the above to the 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 to stick with operators or switching to if-else : whatever is more readable for me.

Answer

if cannot be used on the right-hand side of an assignment statement (which is part of why we have the 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 that particular code can be simplified:

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