Search code examples
javascriptecmascript-6ternary

JavaScript Ternary for function names?


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)()

Solution

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

    files.audio.current[buttonPressed ? 'play' : 'stop']()