Object Methods

Functions stored as object properties.

Examples

Defining a Method

A method accessing object properties using 'this'.

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

Adding a Method Later

Adding a function as a property to an existing object.

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

console.log(person.name());

Short Syntax

ES6 shorthand for defining methods.

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

Test Your Knowledge

JavaScript Quiz

No quiz available for this topic yet.