JavaScript Fundamentals / Objects

Object Methods

🤝 Object Methods in Action

Object methods are actions that can be performed on objects.

A method is a function definition stored as a property value:

const person = {
  firstName: "John",
  lastName: "Doe",
  id: 5566,
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
};

✅ Explanation:

  • firstName, lastName, and id are properties with values.

  • fullName is a method (a function stored as a property).

  • Inside the method, this.firstName refers to person.firstName.

  • this.lastName refers to person.lastName.


🗒️ Accessing Method:

let name = person.fullName(); 
console.log(name) // Output: John Doe
  • () means the function is executed.

  • If you just write person.fullName (without ()), it will return the function definition, not the result.


The this keyword inside an object method refers to the object itself.

const person = {
    firstName: "John",
    lastName: "Doe",
    fullName: function () {
    return this.firstName + " " + this.lastName;
}
};

console.log(person.fullName()); //John Doe

So this.firstName + " " + this.lastName becomes "John" + " " + "Doe" = ”John Doe” .


❇️ Adding a Method to an Object Later

You can add new methods to an existing object after it's declared:

person.name = function () {
  return this.firstName + " " + this.lastName;
};

console.log(person.name()); // Output: John Doe

🔰 Using Built-in Methods Inside Object Methods

You can use built-in JavaScript string methods (like toUpperCase()) inside your own method:

person.name = function () {
  return (this.firstName + " " + this.lastName).toUpperCase();
};

console.log(person.name()); // Output: JOHN DOE

📝 Full Code Example:

const person = {
  firstName: "John",
  lastName: "Doe",
  id: 5566,
  fullName: function () {
    return this.firstName + " " + this.lastName;
  }
};

// Access method
console.log(person.fullName()); // John Doe

// Add new method
person.name = function () {
  return this.firstName + " " + this.lastName;
};
console.log(person.name()); // John Doe

// Use JS method in custom method
person.name = function () {
  return (this.firstName + " " + this.lastName).toUpperCase();
};
console.log(person.name()); // JOHN DOE