When used as object properties, functions are called methods:

const car = {
  brand: 'Ford',
  model: 'Fiesta',
  start: function() {
    console.log(`Started`)
  }
}

car.start()

Inside a method defined using a function() {} syntax we have access to the current object by referencing this:

const car = {
  brand: 'Ford',
  model: 'Fiesta',
  start: function() {
    console.log(`Started ${this.brand} ${this.model}`)
  }
}

car.start()

We don’t have access to this if we use an arrow function:

const car = {
  brand: 'Ford',
  model: 'Fiesta',
  start: () => {
    console.log(`Started ${this.brand} ${this.model}`) //not going to work
  }
}

car.start()

because arrow functions are not bound to the object. So, for object methods regular functions are the way to go.

Parameters

Methods can accept parameters, like regular functions:

const car = {
  brand: 'Ford',
  model: 'Fiesta',
  start: function(destination) {
    console.log(`Going to ${destination}`)
  }
}

car.start()

Dynamically select a method of an object 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']()

Go to the next lesson