Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose function according to ternary operators

Tags:

javascript

I've a code:

a=function(x){alert(x)}
b=function(x){document.write(x)}
c=1;
[c==1?a:b](':p');

but it's not working. Is possible to do what I want?

like image 263
user3073240 Avatar asked Feb 02 '26 07:02

user3073240


1 Answers

Yes, just replace the square brackets with parentheses. You are creating an array literal, but you want to isolate an expression:

(c==1?a:b)(':p');

This would also work, but there is no reason to use it:

[c==1?a:b][0](':p');
like image 135
bfavaretto Avatar answered Feb 04 '26 21:02

bfavaretto