learning2code
learning2code

Reputation: 83

Expressions in ternary operators as functions

3>4?function1():function2()

Is it allowed to use functions in ternary operators? I know you can use it for values, but for functions I am not certain.

Upvotes: 0

Views: 40

Answers (3)

Keith Nicholas
Keith Nicholas

Reputation: 44298

you can do

var f = 3>4?function(){console.log("left")}:function(){console.log("right")}

or with your edit

var f = 3>4?function1:function2

then f will be the function ( not the result of the function )

f()

or if you want the value that those functions return

var v = 3>4?function1():function2()

v will now be whatever those functions returned

Upvotes: 1

Amit Joki
Amit Joki

Reputation: 59252

You can. But like this

var func = 3 > 4 ? function(){
  console.log("3 is not greater than 4");
} : function(){
  console.log("3 IS greater than 4");    
};

Now func has a function reference that has been set conditionally. Calling it func() will result in "3 IS greater than 4"

However, if you already have created the function, then just reference would be enough. You should not call it. Just pass the reference.

var func = 3 > 4 ? func1 : func2;

Upvotes: 3

jdphenix
jdphenix

Reputation: 15425

This is valid JavaScript:

var b = true; 
var a = b == true ? function(){ return 1; } : function(){return 2; } 

a is a function that depended upon the ternary condition, exactly as you'd (hopefully) expect.

If you're wanting a to instead be the return value of the function - call it.

var b = true; 
var a = b == true ? (function(){ return 1; }()) : (function(){return 2; }())

Upvotes: 0

Related Questions