What's the difference between a method and a function?
What is a method? And what is a function? What's the difference?
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()
β Get my JavaScript Beginner's Handbook
I wrote 21 books to help you become a better developer:
- HTML Handbook
- Next.js Pages Router Handbook
- Alpine.js Handbook
- HTMX Handbook
- TypeScript Handbook
- React Handbook
- SQL Handbook
- Git Cheat Sheet
- Laravel Handbook
- Express Handbook
- Swift Handbook
- Go Handbook
- PHP Handbook
- Python Handbook
- Linux Commands Handbook
- C Handbook
- JavaScript Handbook
- Svelte Handbook
- CSS Handbook
- Node.js Handbook
- Vue Handbook