Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)()
like image 911
Kjell Connelly Avatar asked Jun 04 '26 15:06

Kjell Connelly


2 Answers

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

files.audio.current[buttonPressed ? 'play' : 'stop']()
like image 148
Ori Drori Avatar answered Jun 06 '26 10:06

Ori Drori


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!

like image 28
zmferrell Avatar answered Jun 06 '26 10:06

zmferrell



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!