What is the difference between method and function?

What is the method? What is the function? what's the difference?


A function exists independently:

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

bark()

or

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

bark()

Methods are functions assigned to object properties:

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

dog.bark()

This method can access object properties, but only when it is a regular function and not an arrow function:

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

dog.bark()

Download mine for freeJavaScript beginner's manual


More js tutorials: