HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

5) Arrays, Objects and Useful Tools Lesson

Understanding Methods vs Functions in JavaScript

12 min to complete · By Ian Currie

In JavaScript, the properties of an object can hold various types of data, including functions. When a function is situated within an object, it is referred to as a method. There's more to the difference between functions and methods than just a name. There are nuances that are important for any JavaScript developer to be aware of. In this lesson, you'll explore these subtleties.

An Object with Methods: Function Expressions vs Function Declarations

Take a look at this object which has a few methods:

let human = {
  greet: function (name) {
    alert(`Hello, ${name}!`);
  },
  farewell: function (name) {
    alert(`Goodbye, ${name}!`);
  },
};

In this object, the functions are defined with function expressions. Alternatively, the same functionality can be achieved by defining the functions separately and then referencing them in the object:

function greet(name) {
  alert(`Hello, ${name}!`);
}

function farewell(name) {
  alert(`Goodbye, ${name}!`);
}

let human = {
  greet: greet,
  farewell: farewell,
};

In this structure, the object human has properties (greet and farewell) whose values are functions. This approach, while more verbose, separates the function definitions from the object which may be desirable, especially if you are reusing the functions elsewhere.

Colorful illustration of a light bulb

The alert() function called from the methods in the example is a globally defined function in the browser environment. It makes a small modal window pop up with the message passed in as an argument.

Methods are functions that are defined as part of an object's properties due to their close association with the object's data. You'll typically see methods defined in either expression or declaration form within the object.

No matter how they are defined, you call methods in the same way you call a function:

human.greet("nomad");

If you run this in the browser console, you'll see an alert pop up with whatever name you have used as an argument! Try it now!

Context of Execution: Functions vs. Methods

In JavaScript, understanding the context of execution is crucial for functions and methods, as it fundamentally affects how they are used and what data they can access.

Functions are typically independent entities callable from anywhere in their scope which could be either global or local. A global function is one that's defined outside of other functions and the scope in which a function is defined determines what data it can access.

Methods, however, are functions that are properties of objects. They are always called in the context of the object they belong to, which means they have special access to other properties and methods of that object by using the this keyword. Here's a simple example:

let person = {
  name: "Nomad",
  greet: function() {
    console.log(`Hello, my name is ${this.name}!`);
  }
};

person.greet(); // Outputs: "Hello, my name is Nomad!"

In this case, greet is a method of the person object. When greet is called, it has access to the person object's data, so this.name refers to person.name.

Colorful illustration of a light bulb

You can actually use the this keyword anywhere. If you try and use it on the console in a browser, you'll see the Window global object:

console.log(this);
Window{window: Window, self: Window, document: document, name: '', location: Location…}

Using the this keyword can be confusing because it changes depending on the execution context. In the global scope in a browser console, that means that the context is the Window object. In a method in an object, this usually points to the object the method is a part of.

While methods can still access functions and variables in the global scope, you won't see many objects relying on that pattern because it can cause confusion. In the next section, you'll start to understand how methods are typically used and why they are preferable for certain use cases over normal functions.

Methods and Their Impact on Objects

Methods often play a pivotal role in modifying or interacting with the data within their respective objects. In contrast, standalone functions typically perform operations that are not tied to a specific object's state.

A method usually manipulates the properties of the object to which it belongs. This is one of the primary characteristics that distinguish methods from regular functions. Here's an example to illustrate this:

let counter = {
  value: 0,
  increment: function () {
    this.value += 1;
  },
  decrement: function () {
    this.value -= 1;
  }
};

console.log(counter.value); // Outputs: 0
counter.increment();
console.log(counter.value); // Outputs: 1
counter.decrement();
console.log(counter.value); // Outputs: 0

In this counter object, the increment and decrement methods modify the value property of the object. The this keyword is used to access and change the value property of counter. Each call to increment or decrement changes the state of the counter object.

On the other hand, a standalone function usually does not modify the state of an object unless it is explicitly passed an object to modify. Functions often perform tasks independently of any specific object's state. Here's an example:

function add(a, b) {
  return a + b;
}

let result = add(2, 3);
console.log(result); // Outputs: 5

In this case, the add function simply takes two numbers and returns their sum. It doesn't rely on or modify the state of any object.

The key distinction between functions and methods in JavaScript lies in their relationship with data:

  • Methods: These are closely tied to the objects they are a part of, often tasked with altering or utilizing the object's internal state. This tight integration allows methods to directly manipulate the data they're associated with.
  • Functions: In contrast, functions usually operate independently, performing tasks without being bound to a specific object. This independence lends them a broader versatility in various contexts.

Grasping this difference is crucial for effective JavaScript code organization. It guides you in determining whether a particular operation should manifest as an object's method or as an independent function. Embracing methods means embracing the principles of object-oriented programming, where behaviors are encapsulated within the data structures they manipulate.

However, JavaScript's flexible nature allows for deviation from these norms. There are scenarios where bending these rules is justifiable, particularly when it aligns better with the specific requirements of your project or makes the code more comprehensible for your team. Remember, the ultimate goal is clarity and efficiency in your coding practice, and sometimes that means adapting conventions to fit the real-world context of your project.

Summary: Javascript Methods vs Functions

This article examines the differences between functions and methods in JavaScript, emphasizing their significance for developers.

  • Functions and methods differ in JavaScript, with methods being functions that are properties of objects.
  • Function expressions and function declarations are two ways to define functions in objects. Function expressions are defined within the object, while function declarations are defined separately and then referenced in the object.
  • The context of execution is key: functions are independent, whereas methods are part of objects and make use of the this keyword.
  • Methods often play a role in modifying or interacting with their object's data, distinguishing them from standalone functions that operate independently of any specific object's state.
  • Methods encapsulate behavior with the data they operate on, aligning with object-oriented programming principles, while functions are more versatile and not tied to any particular object.