DEV Community

DevLogBook
DevLogBook

Posted on

JavaScript Objects with Methods

What Are Methods in Objects?

A function that lives inside an object. Think of an object like a toolbox, and methods are the tools inside it!

// Object with data and methods (functions inside!)
let person = {
    name: "Alice",
    age: 25,
    sayHello: function() {
        console.log("Hello!");
    }
};

// Using the method
person.sayHello();  // "Hello!"
Enter fullscreen mode Exit fullscreen mode

See? sayHello is a method - it's a function inside the object!

Visual Example

Object = Toolbox 🧰
   β”‚
   β”œβ”€ Property (data) πŸ“Š
   β”œβ”€ Property (data) πŸ“Š
   β”œβ”€ Method (function) πŸ”§
   └─ Method (function) πŸ”§

Usage: toolbox.method()
Enter fullscreen mode Exit fullscreen mode

Real-Life Example

function createAccount(username, initialBalance) {
    let balance = initialBalance;

    return {
        deposit: function(amount){
            balance += amount;
            console.log(`Deposited $${amount}. New balance: $${balance}`);
        },
        withdraw: function(amount){
            balance -= amount;
            console.log(`Withdrew $${amount}. New balance: $${balance}`);
        },
        checkBalance: function(){
             console.log(`Alice's balance: $${balance}`);
        }
    }
}

let account = createAccount("David", 100);
account.deposit(50);       // "Deposited $50. New balance: $150"
account.withdraw(30);      // "Withdrew $30. New balance: $120"
account.checkBalance();    // "David's balance: $120"
Enter fullscreen mode Exit fullscreen mode

Important: NO () When Defining!

❌ WRONG:
let obj = {
    method(): function() { }  // Syntax error!
};
Enter fullscreen mode Exit fullscreen mode
βœ… CORRECT:
let obj = {
    method: function() { }  // Good!
};
Enter fullscreen mode Exit fullscreen mode

Using this Keyword

Methods can access other properties in the same object using this:

let person = {
    name: "David",
    age: 25,

    introduce() {
        console.log(`Hi! I'm ${this.name} and I'm ${this.age} years old.`);
    },

    birthday() {
        this.age++;
        console.log(`Happy birthday! I'm now ${this.age}!`);
    }
};

person.introduce();  // "Hi! I'm David and I'm 25 years old."
person.birthday();   // "Happy birthday! I'm now 26!"
person.introduce();  // "Hi! I'm David and I'm 26 years old."
Enter fullscreen mode Exit fullscreen mode

Why Use Methods in Objects?

βœ… Organization

Group related functions together:

// ❌ Messy
function addNumbers(a, b) { return a + b; }
function subtractNumbers(a, b) { return a - b; }
function multiplyNumbers(a, b) { return a * b; }

// βœ… Clean
let math = {
    add(a, b) { return a + b; },
    subtract(a, b) { return a - b; },
    multiply(a, b) { return a * b; }
};

math.add(5, 3);  // Much cleaner!
Enter fullscreen mode Exit fullscreen mode
βœ… Reusability

Create multiple instances:

function createDog(name) {
    return {
        bark: function() {
            console.log(`${name} says: Woof!`);
        }
    };
}

let dog1 = createDog("Buddy");
let dog2 = createDog("Max");

dog1.bark();  // "Buddy says: Woof!"
dog2.bark();  // "Max says: Woof!"
Enter fullscreen mode Exit fullscreen mode
βœ… Data Privacy

Keep data private using closures:

function createPassword(pwd) {
    let password = pwd;  // Private variable!

    return {
        check: function(attempt) {
            return attempt === password;
        },

        change:  function(oldPwd, newPwd) {
            if (oldPwd === password) {
                password = newPwd;
                return "Password changed!";
            }
            return "Wrong password!";
        }
    };
}

let myPassword = createPassword("secret123");

console.log(myPassword.password);  // undefined - can't access directly!
console.log(myPassword.check("secret123"));  // true
console.log(myPassword.change("secret123", "newPass"));   // "Password changed!"
Enter fullscreen mode Exit fullscreen mode

Quick Comparison

Method in Object vs Regular Function

Object Method:

let calculator = {
    add: function(a, b) {
        return a + b;
    }
};

calculator.add(2, 3);  // Must use object.method() => calculator.___
Enter fullscreen mode Exit fullscreen mode

Regular Function:

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

add(2, 3);  // Call directly
Enter fullscreen mode Exit fullscreen mode

Use object methods when functions are related and belong together!

How to Define Methods

There are 3 ways to write methods:

1️⃣ Traditional Way

let calculator = {
    add: function(a, b) {
        return a + b;
    }
};
Enter fullscreen mode Exit fullscreen mode

2️⃣ Shorthand (Modern - Recommended!)

let calculator = {
    add(a, b) {
        return a + b;
    }
};
Enter fullscreen mode Exit fullscreen mode

3️⃣ Arrow Function

let calculator = {
    add: (a, b) => {
        return a + b;
    }
};
Enter fullscreen mode Exit fullscreen mode

Common Mistakes

❌ Mistake 1: Adding () when defining
let obj = {
    method(): function() { }  // Wrong!
};
Enter fullscreen mode Exit fullscreen mode
❌ Mistake 2: Forgetting () when calling
obj.method;  // Returns the function, doesn't call it!
obj.method();  // Calls the function βœ“
Enter fullscreen mode Exit fullscreen mode
❌ Mistake 3: Wrong template literal syntax
console.log`Hello`;   // Wrong!
console.log(`Hello`);  // Correct!
Enter fullscreen mode Exit fullscreen mode

Happy Coding...!
Found this helpful? Give it a ❀️!

Top comments (0)