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:

if (driver.sleepy > 6) {
  car.park();
} else {
  car.drive();
}

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:

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:

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.