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)()
Use the brackets notation, and return the function name as a string from the trinary:
files.audio.current[buttonPressed ? 'play' : 'stop']()
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With