Function vs. Method — What’s the Difference?

It’s easy to get confused about JavaScript terminology, especially because some term definitions sound similar to others. Methods vs function are no exception.

First, let’s establish two facts:

  • A method is a function.
  • A function is, well a function (something that you can call to run/execute code).

The difference between functions and methods lies in how they are used.

A normal function lives on its own and is triggered by a function call.

A normal function example:

function alertMessage() {
  alert("Alert message triggered!")
}

// Call alertMessage function
alertMessage()

A method is a type of function that is assigned to an object property.

Another way of phrasing it: a method is a function that is a property of an object.

A method example:

const blackFridayDeals = {
  sony: 'Playstation 5',
  discountPopup: function () {
    alert(`Get 50% off ${this.sony} only today!`)
  },
}

blackFridayDeals.discountPopup()

In the code example above, you have an object called blackFridayDeals.

One of the blackFridayDeals object properties is called discountPopup.

discountPopup has a function assigned, which executes the alert() dialog (which is a built-in JavaScript method).


Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on