3

I’ve come across the situation multiple times that I call a function based on a binary situation where ternary would work fine:

buttonPressed ? files.audio.current.play() : files.audio.current.stop()

But see all that extra wasted code? Is there a way instead to do something more like:

files.audio.current.(buttonPressed ? play : stop)()
Kjell Connelly
  • 247
  • 3
  • 9
  • 1
    This might appear "wasted code", but is actually way more readable than brackets or similar tricks. KISS! – georg Jan 18 '18 at 17:53
  • @georg - readability and KISS are subjective. I find WET less readable. – Ori Drori Jan 18 '18 at 17:59
  • @OriDrori: besides looking horrible, you get zero support from your IDE for this type of code (think validation, autocompletion etc) – georg Jan 18 '18 at 18:08
  • I agree that the IDE auto completion/validation are major drawbacks. And It should require a unit test anyway to offset the possibility of runtime errors . – Ori Drori Jan 18 '18 at 18:12

2 Answers2

8

Use the brackets notation, and return the function name as a string from the trinary:

files.audio.current[buttonPressed ? 'play' : 'stop']()
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
1

Expanding a little on Ori Drori's answer:

In JavaScript functions are equivalent to fields on an object.

Therefore in a js object like so:

var person = {
    name: "Steve",
    sayHello: function() {
        alert("Hello!");
    }
}

both person.name and person['name'] are valid ways of referencing the name field.

So, the sayHello method can be called by either person.sayHello() or person['sayHello']()

To solidify your understanding, try person['sayHello'] and look at what is returned!

Hope that helps!

zmferrell
  • 21
  • 4