Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ternary operator to select function

The following snippet works

if (condition)
  node.addClass('myclass');
else
  node.removeClass('myclass');

but not this one

node[condition ? 'addClass' : 'removeClass']('myclass');

nor this one

(condition ? node.addClass : node.removeClass)('myclass');

If I test it with

console.log(node[condition ? 'addClass' : 'removeClass']);

the browser prints that it's a function. Why can't I call it?

like image 718
SU3 Avatar asked May 28 '26 13:05

SU3


1 Answers

It apparently works the way I gave my examples here. It doesn't work with one extra level of indirection.

function print(x) {
  console.log(x);
  return x;
}

print(condition ? node.addClass : node.removeClass)('myclass');

With this code, Chrome tells me this:

Uncaught TypeError: Cannot read property '0' of undefined

But I found out I can circumvent the problem by using call to pass the node as this to the function.

print(condition ? node.addClass : node.removeClass).call(node,'myclass');

Obviously, the right solution in this specific case is to use toggleClass, as @epascarello pointed out. I'm a little surprised that this gets lost in this scenario.

like image 88
SU3 Avatar answered May 31 '26 04:05

SU3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!