Methods of dynamically selecting objects in JavaScript

Learn how to dynamically access objects in JavaScript

Sometimes you have an object and you need to call a method or other methods based on certain conditions.

For example, you have acarObject, you either wantdrive()It orpark()It dependsdriver.sleepyvalue.

If the driver’s drowsiness exceeds 6, we need to park the car before we can fall asleep while driving.

This is how you passif/elseState of health:

if (driver.sleepy > 6) {
} else {

Let's rewrite it to be more dynamic.

We can use the ternary operator to dynamically select the method name and use it as a string value.

We can use square brackets to select it from the available methods of the object:

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

Through the above statement, we have obtained the method reference. We can call it directly by adding parentheses:

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

Download mine for freeJavaScript beginner's manual

More js tutorials: