Skip to content

Dynamically select a method of an object in JavaScript

Learn how to access a method of an object dynamically in JavaScript

Sometimes you have an object and you need to call a method, or a different method, depending on some condition.

For example you have a car object and you either want to drive() it or to park() it, depending on the driver.sleepy value.

If the driver has a sleepy level over 6, we need to park the car before it fells asleep while driving.

Here is how you achieve this with an if/else condition:

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

Let’s rewrite this to be more dynamic.

We can use the ternary operator to dynamically choose the method name, get it as the string value.

Using square brackets we can select it from the object’s available methods:

car[driver.sleepy > 6 ? 'park' : 'drive']

With the above statement we get the method reference. We can directly invoke it by appending the parentheses:

car[driver.sleepy > 6 ? 'park' : 'drive']()

→ Get my JavaScript Beginner's Handbook

→ I wrote 17 books to help you become a better developer:

  • C Handbook
  • Command Line Handbook
  • CSS Handbook
  • Express Handbook
  • Git Cheat Sheet
  • Go Handbook
  • HTML Handbook
  • JS Handbook
  • Laravel Handbook
  • Next.js Handbook
  • Node.js Handbook
  • PHP Handbook
  • Python Handbook
  • React Handbook
  • SQL Handbook
  • Svelte Handbook
  • Swift Handbook
...download them all now!

Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list