Dynamically Select a Method of an Object in JavaScript
Learn how to dynamically access a method of an object in JavaScript and improve code flexibility.
Sometimes, you may encounter a situation where you have an object and need to call different methods based on certain conditions. For instance, you might have a car
object and want to either drive()
or park()
it based on the driver.sleepy
value.
Traditionally, you can achieve this using an if/else
condition:
1 | if (driver.sleepy > 6) { |
However, there is a more dynamic approach using JavaScript’s ternary operator and square bracket notation. Instead of hardcoding the method name in the condition, we can select it from the object’s available methods:
1 | car[driver.sleepy > 6 ? 'park' : 'drive'] |
By using this statement, we obtain a reference to the desired method. To invoke it, simply append the parentheses:
1 | car[driver.sleepy > 6 ? 'park' : 'drive'](); |
This approach enhances the flexibility of your code, allowing you to dynamically select a method based on a condition. By leveraging JavaScript’s native features, you can write more concise and adaptable code.
tags: [“JavaScript”, “object”, “method”, “dynamic coding”]