0

I am currently writing a compare function for js's Array.prototype.sort(). The question now is: I have an object instance a with both variables and functions I want to sort after. I learned yesterday that I can access functions (I have the method name of) like this a['fct']().

So what I would like to do is something like

a['fct'] (typeof a['fct'] === 'function' ? () : nothing)

So I basically want to execute it if it's a function and just use it as a variable if it's a variable. I would like to omit a whole block with the same sorting logic, so I would like to keep it with the ternary operator style. Is this possible?

Chris Jung
  • 974
  • 2
  • 8
  • 17

1 Answers1

1

You should do like:

typeof a["fct"] == "function" ? a["fct"]() : a["fct"]

You may also use optional chaining as in my other answer how to use it like:

a["fct"]?.()

This will call method if a["fct"] is a function else result from a["fct"].

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
  • Thank you very much - I was looking for something more like the second, and overlooking the obvious first option. :D – Chris Jung Sep 06 '19 at 05:30