javascriptfunctionoperatorsconditional-operator

Function declaration with ternary operator


Is it possible to use a ternary operator to declare the function name?

var foo,
    bar = 'bar';

(foo || bar) = function(){ // Invalid left-hand side in assignment [Bad assignment]
    alert(true);
};

[foo || bar] = function(){ // Invalid left-hand side in assignment [Bad assignment]
    alert(true);
};

(foo ? foo : bar) = function(){ // Invalid left-hand side in assignment [Bad assignment]
    alert(true);
};

Solution

  • this[foo || bar] = function(){alert(true)}
    

    Thing is, if bar equals "bar", you're going to overwrite yourself with a function...