What is the difference between a method and a function?

In this article, we will learn about the difference between a method and a function in JavaScript. While both execute code blocks, the key difference is that a function is standalone code, while a method is a function that belongs to an object.

What is a Function?

A function is a reusable block of code that can be called anywhere in your program. Functions help create modular code by eliminating repetition.

JavaScript functions can be defined using function expressions, arrow functions, or the function keyword.

Syntax

function functionName(parameter1, parameter2) {
    // code to be executed
    return value; // optional
}

Example

function greet(name) {
    return "Hello, " + name + "!";
}

// Function call
let message = greet("Bob");
console.log(message);
Hello, Bob!

What is a Method?

A method is a function that belongs to an object. It's a property of an object that contains a function definition. Methods can access and modify the object's properties using the this keyword.

Methods are fundamental in object-oriented programming for defining object behavior.

Example

let person = {
    name: 'Alice',
    age: 25,
    greet: function() {
        return 'Hello, I am ' + this.name + ' and I am ' + this.age + ' years old.';
    },
    celebrateBirthday: function() {
        this.age++;
        return 'Happy birthday! Now I am ' + this.age + '.';
    }
};

console.log(person.greet());
console.log(person.celebrateBirthday());
Hello, I am Alice and I am 25 years old.
Happy birthday! Now I am 26.

Key Differences

Feature Function Method
Definition Standalone block of code Function that belongs to an object
Invocation functionName() object.methodName()
Context No implicit this binding this refers to the owner object
Usage General-purpose, reusable operations Defines object-specific behavior

Converting Functions to Methods

Any function can become a method when assigned to an object property:

// Standalone function
function sayGoodbye() {
    return "Goodbye!";
}

// Convert to method
let obj = {
    farewell: sayGoodbye
};

console.log(sayGoodbye());    // Function call
console.log(obj.farewell());  // Method call
Goodbye!
Goodbye!

Conclusion

Functions are independent code blocks, while methods are functions attached to objects. Understanding this distinction is crucial for effective JavaScript programming and object-oriented design.

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2026-03-15T21:12:46+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements