Call foo if true else bar

Just out of curiosity, something like that in JavaScript?

var c, flag = true;
c = Math.(flag ? min : max)(a, b); // c = flag ? Math.min(a, b) : Math.max(a, b);
+3
source share
1 answer

You are almost right. But this will not work because min, and maxin this context refer to?

You either need to specify a qualified identifier:

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

Or you use the parenthesis syntax and simply specify the name of the property identifier:

Math[flag ? "min" : "max"](a, b)
+5
source

Source: https://habr.com/ru/post/1793533/


All Articles