📖 JavaScript Methods

Methods are functions that are properties of objects. They provide a way to perform actions or operations on the data contained within the object. Understanding methods is crucial for working with objects and creating modular, reusable code in JavaScript.

Definition and Syntax

A method is a function associated with an object. Methods are defined as properties on the object using function expressions or arrow functions. Here's the basic syntax for defining a method within an object:


// Defining a method within an object
const object = {
    methodName: function() {
        // Method body
    }
};

// Alternatively, using ES6 shorthand syntax
const object = {
    methodName() {
        // Method body
    }
};
        

Creating and Using Methods within Objects

To create and use methods, you define them within an object and call them using the dot notation. Methods can access the object's properties using the this keyword. In this context, this refers to the owner of the method, which is the object the method belongs to. Here are some examples:

Example 1: Simple Method


const person = {
    name: 'Alice',
    greet: function() {
        return `Hello, my name is ${this.name}`;
    }
};

console.log(person.greet()); // Output: Hello, my name is Alice
        

In this example, the greet method is defined within the person object. The method accesses the name property using this.name.

Example 2: Method with Parameters


const calculator = {
    add: function(a, b) {
        return a + b;
    },
    subtract: function(a, b) {
        return a - b;
    }
};

console.log(calculator.add(5, 3)); // Output: 8
console.log(calculator.subtract(5, 3)); // Output: 2
        

This example defines a calculator object with two methods, add and subtract. These methods take parameters and perform arithmetic operations.

Use Cases for Methods

Methods are used in various scenarios, including:

Encapsulation
Methods allow you to encapsulate functionality within objects, making your code modular and easier to manage.
Data Manipulation
Methods can manipulate the data within an object, providing a way to interact with the object's properties.
Event Handling
In web development, methods are often used to handle events such as clicks, form submissions, and other user interactions.
Code Reusability
By defining methods, you can reuse the same functionality across different parts of your codebase, reducing redundancy.

Putting It Into Action

To see these examples in action, create an HTML file and include the following script. This script demonstrates creating and using methods within objects.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Methods Example</title>
</head>
<body>
    <script>
        const person = {
            name: 'Alice',
            greet: function() {
                return `Hello, my name is ${this.name}`;
            }
        };
        console.log(person.greet()); // Output: Hello, my name is Alice

        const calculator = {
            add: function(a, b) {
                return a + b;
            },
            subtract: function(a, b) {
                return a - b;
            }
        };
        console.log(calculator.add(5, 3)); // Output: 8
        console.log(calculator.subtract(5, 3)); // Output: 2
    </script>
</body>
</html>
        

Challenge

Modify the calculator object to add methods for multiplication and division. Then, create a new method within the person object that updates the name property and returns a new greeting.

Solution


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Methods Example</title>
</head>
<body>
    <script>
        const person = {
            name: 'Alice',
            greet: function() {
                return `Hello, my name is ${this.name}`;
            },
            updateName: function(newName) {
                this.name = newName;
                return `My name is now ${this.name}`;
            }
        };
        console.log(person.greet()); // Output: Hello, my name is Alice
        console.log(person.updateName('Bob')); // Output: My name is now Bob
        console.log(person.greet()); // Output: Hello, my name is Bob

        const calculator = {
            add: function(a, b) {
                return a + b;
            },
            subtract: function(a, b) {
                return a - b;
            },
            multiply: function(a, b) {
                return a * b;
            },
            divide: function(a, b) {
                return a / b;
            }
        };
        console.log(calculator.add(5, 3)); // Output: 8
        console.log(calculator.subtract(5, 3)); // Output: 2
        console.log(calculator.multiply(5, 3)); // Output: 15
        console.log(calculator.divide(6, 3)); // Output: 2
    </script>
</body>
</html>
                        

References