โ† flaviocopes.com

What's the difference between a method and a function?

Published Jun 12 2020

Psssst! The 2023 WEB DEVELOPMENT BOOTCAMP is starting on FEBRUARY 01, 2023! SIGNUPS ARE NOW OPEN to this 10-weeks cohort course. Learn the fundamentals, HTML, CSS, JS, Tailwind, React, Next.js and much more! โœจ

A function lives on its own:

const bark = () => {
  console.log('wof!')
}

bark()

or

function bark() {
  console.log('wof!')
}

bark()

A method is a function assigned to an object property:

const dog = {
  bark: () => {
    console.log('wof!')
  },
}

dog.bark()

The method can access the object properties, but only when itโ€™s a regular function, not an arrow function:

const dog = {
  name: 'Roger',
  bark: function () {
    console.log(`I am ${this.name}. wof!`)
  },
}

dog.bark()


I write books for developers ๐Ÿ‘‡๐Ÿผ

© 2023 Flavio Copes Flavio Copes made in Italy ๐Ÿ‡ฎ๐Ÿ‡น using Notion to Site Notion to Site