When it comes to programming, it’s essential to distinguish between methods and functions. While they may seem similar at first glance, there are important differences to consider.

Functions: A function is a self-contained piece of code that performs a specific task. It can be called and executed independently. Here are a couple of examples:

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

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

bark();

In both cases, the bark function stands on its own and can be invoked directly.

Methods: On the other hand, a method is a function that is associated with an object property. It is defined within an object and can be accessed using that object. Here’s an example:

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

dog.bark();

In this case, the bark function is assigned to the object property bark of the dog object. Calling dog.bark() will invoke the method.

What sets methods apart is their ability to access and manipulate the properties of the object they belong to. However, it’s worth noting that they can only do so when defined as regular functions rather than arrow functions. Here’s an example:

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

dog.bark();

In this example, the bark method can access the name property of the dog object using this.

By understanding the distinction between methods and functions, you can effectively utilize and organize your code. Functions enable code reusability, while methods allow for object-specific behavior.

Tags: programming, methods, functions, JavaScript