Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call foo if true else bar

Tags:

javascript

Just out of curiosity, anything like this possible in JavaScript ?

var c, flag = true;
c = Math.(flag ? min : max)(a, b); // c = flag ? Math.min(a, b) : Math.max(a, b);
like image 988
YHAI Goregaon Avatar asked Dec 06 '25 23:12

YHAI Goregaon


1 Answers

You’re almost right. But it won’t work because what are min and max in that context referring to?

You either have to specify a qualified identifier:

(flag ? Math.min : Math.max)(a, b)

Or you use the bracket syntax and just specify the property’s identifier name:

Math[flag ? "min" : "max"](a, b)
like image 81
Gumbo Avatar answered Dec 08 '25 13:12

Gumbo