JavaScript Object Methods: A Complete Tutorial with Examples

In JavaScript, object methods are functions that belong to an object. Methods allow objects to perform actions using their properties. They are useful for manipulating and working with the data inside objects.

This tutorial will guide you through various techniques to define, use, and manipulate object methods in JavaScript.

1. Defining Object Methods

Methods can be added to objects in multiple ways: using object literals, after the object is created, or using ES6 shorthand syntax.

Example 1: Defining Methods in an Object Literal

let car = {
  brand: 'Toyota',
  model: 'Corolla',
  year: 2022,
  start: function() {
    console.log(`${this.brand} ${this.model} is starting...`);
  },
  stop: function() {
    console.log(`${this.brand} ${this.model} has stopped.`);
  }
};

car.start(); // Output: Toyota Corolla is starting...
car.stop();  // Output: Toyota Corolla has stopped.

Explanation

The car object has two methods: start and stop.
The this keyword refers to the current object (car in this case).
Methods are defined using function expressions within the object.

Example 2: Using ES6 Shorthand Method Syntax

let user = {
  name: 'Alice',
  greet() { // Shorthand syntax
    console.log(`Hello, my name is ${this.name}.`);
  }
};

user.greet(); // Output: Hello, my name is Alice.

Explanation

The ES6 shorthand syntax allows you to define methods without the function keyword.

2. Adding Methods to an Existing Object

You can add methods to an object after it has been created.

Example 3: Adding Methods to an Object

let person = {
  name: 'John',
  age: 30
};

// Adding a method to the object
person.sayHello = function() {
  console.log(`Hello, I am ${this.name} and I am ${this.age} years old.`);
};

person.sayHello(); // Output: Hello, I am John and I am 30 years old.

Explanation

The sayHello method is added to the person object after it was created.
The method uses this to refer to the object's properties.

3. Using this Keyword in Methods

In JavaScript, the this keyword within a method refers to the object on which the method was called.

Example 4: Using this in Object Methods

let book = {
  title: 'JavaScript Essentials',
  author: 'John Doe',
  printDetails() {
    console.log(`${this.title} by ${this.author}`);
  }
};

book.printDetails(); // Output: JavaScript Essentials by John Doe

Explanation

this.title and this.author refer to the properties of the book object.
The this keyword is essential when you need to reference the object’s properties from within its methods.

4. Common Built-In Object Methods

JavaScript provides several built-in methods to work with objects, such as Object.keys(), Object.values(), Object.entries(), Object.assign(), and Object.freeze().

Example 5: Using Object.keys(), Object.values(), and Object.entries()

let car = {
  brand: 'Toyota',
  model: 'Corolla',
  year: 2022
};

console.log(Object.keys(car));   // Output: ['brand', 'model', 'year']
console.log(Object.values(car)); // Output: ['Toyota', 'Corolla', 2022]
console.log(Object.entries(car)); // Output: [['brand', 'Toyota'], ['model', 'Corolla'], ['year', 2022]]

Explanation

Object.keys() returns an array of the object's keys.
Object.values() returns an array of the object's values.
Object.entries() returns an array of key-value pairs.

Example 6: Using Object.assign()

The Object.assign() method is used to copy properties from one or more source objects to a target object.

let target = { name: 'John' };
let source = { age: 30, city: 'New York' };

Object.assign(target, source);

console.log(target); // Output: { name: 'John', age: 30, city: 'New York' }

Explanation

Object.assign() copies properties from the source object to the target object.
The target object is modified to include the properties of the source.

Example 7: Using Object.freeze()

The Object.freeze() method freezes an object, preventing new properties from being added, existing properties from being removed, or values from being modified.

let user = {
  name: 'Alice',
  age: 25
};

Object.freeze(user);
user.age = 30; // This will not change the age property

console.log(user.age); // Output: 25

Explanation

Object.freeze(user) freezes the user object.
Any attempts to modify the properties of a frozen object will have no effect.

5. Method Chaining

You can define multiple methods in an object and return the object itself (this) to allow method chaining.

Example 8: Method Chaining

let calculator = {
  result: 0,
  
  add(value) {
    this.result += value;
    return this; // Returning 'this' for chaining
  },
  
  subtract(value) {
    this.result -= value;
    return this; // Returning 'this' for chaining
  },
  
  multiply(value) {
    this.result *= value;
    return this; // Returning 'this' for chaining
  },
  
  reset() {
    this.result = 0;
    return this; // Returning 'this' for chaining
  },
  
  printResult() {
    console.log(this.result);
    return this; // Returning 'this' for chaining
  }
};

calculator.add(10).subtract(2).multiply(3).printResult(); // Output: 24
calculator.reset().add(5).multiply(4).printResult(); // Output: 20

Explanation

Each method (add, subtract, multiply, reset, printResult) returns this, which allows subsequent method calls to be chained together.
This pattern is often used in libraries (e.g., jQuery) for concise, readable code.

6. Using Getter and Setter Methods

JavaScript objects support getter and setter methods to get and set property values dynamically.

Example 9: Getters and Setters

let person = {
  firstName: 'John',
  lastName: 'Doe',
  
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  },
  
  set fullName(name) {
    let parts = name.split(' ');
    this.firstName = parts[0];
    this.lastName = parts[1];
  }
};

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

person.fullName = 'Jane Smith';
console.log(person.firstName); // Output: Jane
console.log(person.lastName); // Output: Smith

Explanation

The fullName getter returns the full name.
The fullName setter splits a name string and updates the firstName and lastName properties.

Summary

JavaScript object methods provide powerful ways to define behavior for objects, manipulate object data, and implement reusable code. Here's a quick recap of the key points:

Defining Methods

Object Literal: Define methods directly within an object.
ES6 Shorthand: Use the shorthand syntax for defining methods (methodName() { … }).
Adding Methods: Add methods to objects after creation using dot notation.

Built-In Object Methods

Object.keys(), Object.values(), Object.entries(): Work with object properties and values.
Object.assign(): Copy properties from one or more source objects to a target object.
Object.freeze(): Prevent modifications to an object.

Using this Keyword
this refers to the current object within a method and is essential for accessing the object's properties.

Advanced Techniques

Method Chaining: Return this from methods to enable chaining.
Getters and Setters: Use getter and setter methods for controlled access to properties.

By mastering object methods, you can create more dynamic, flexible, and powerful JavaScript objects, enhancing your ability to write clean and efficient code.

Related posts

JavaScript for…of Loop: A Comprehensive Tutorial

JavaScript Promises: A Complete Tutorial

JavaScript for…in Loop: A Complete Tutorial