⬅ Back

OBJECT METHODS IN JAVASCRIPT - COMPLETE NOTE WITH DIAGRAMS

This note explains object methods in simple language.

Until now, objects were used only to store data. But objects can also store functions.

This is very important because in real JavaScript, objects often contain:

That is why object methods are used everywhere in full-stack development:

1. What is an object method?

An object method is a function stored inside an object.

So an object can contain:

If the value of a property is a function, that property is called a method.

Diagram 1. Object with data and methods

Object
│
├─ data
│  ├─ name
│  ├─ age
│  └─ books
│
└─ methods
   ├─ getBooks()
   ├─ addBook()
   └─ changeRating()

Explanation

A normal property stores information. A method stores an action.

2. Why object methods are useful

Look at this idea:

const books = ["The Last Kingdom", "Dream Guardian"];

function getBooks() {}
function addBook() {}

This works as code, but the parts are weakly connected.

These things belong together logically, but they are written separately.

Diagram 2. Weak connection vs grouped object

Weak connection:
books
getBooks()
addBook()

Better:
bookShelf
│
├─ books
├─ getBooks()
└─ addBook()

Explanation

It is better when the data and the actions for that data are grouped in one place.

3. A method is just a function inside an object

Example

const obj = {
  method(value) {
    console.log(`I'm a method with ${value}!`);
  },
};

obj.method(5);  // "I'm a method with 5!"
obj.method(10); // "I'm a method with 10!"

Diagram 3. Method syntax

const obj = {
  method(value) {
    // code
  }
};

Explanation

This is just a function written inside an object.

You call it with dot notation:

obj.method()

4. Calling an object method

To run a method, use dot notation.

Example

obj.method(5);

This means:

Diagram 4. Method call

obj.method(5)

1. obj
2. method
3. call it
4. pass value 5

Explanation

This is the same style as accessing properties, but methods also need parentheses ().

5. Objects that combine data and methods

When an object stores both:

it acts like a simple model of something real.

Example idea:

Diagram 5. Data + behavior together

bookShelf
│
├─ data
│  └─ books
│
└─ behavior
   ├─ getBooks()
   └─ addBook()

Explanation

This makes the code more organized and easier to understand.

6. Example: bookShelf object

const bookShelf = {
  books: ["The Last Kingdom", "Dream Guardian"],

  getBooks() {
    return "Returning all books";
  },

  addBook(bookName) {
    return `Adding book ${bookName}`;
  },
};

bookShelf.getBooks(); // "Returning all books"
bookShelf.addBook("New book 1"); // "Adding book New book 1"
bookShelf.addBook("New book 2"); // "Adding book New book 2"

Diagram 6. bookShelf structure

bookShelf
│
├─ books    → ["The Last Kingdom", "Dream Guardian"]
├─ getBooks()
└─ addBook(bookName)

Explanation

Now the data and the actions are kept in one object.

7. Methods usually work with object properties

A method is most useful when it works with the object's own data.

For example:

That is where this becomes important.

Diagram 7. Method working with object data

bookShelf
│
├─ books
└─ methods use books

Explanation

A method should know how to reach the data inside its own object.

8. What is this?

Inside an object method, this means:

the object that called the method

Example

const bookShelf = {
  books: ["The Last Kingdom", "The Mist"],
  getBooks() {
    console.log(this);
  },
};

bookShelf.getBooks();

Here this refers to bookShelf.

Diagram 8. Meaning of this

bookShelf.getBooks()
↓
inside getBooks():
this = bookShelf

Explanation

this gives the method access to the object that called it.

9. Why this is used instead of the object name

You may think:

Why not just write bookShelf.books inside the method?

Because the object name is not reliable.

A method may later be:

this is safer because it always points to the object before the dot.

Diagram 9. Why this is better

Using object name:
bookShelf.books
→ fixed name

Using this:
this.books
→ current calling object

Explanation

this makes the method more flexible and more correct.

10. Accessing properties with this

Example

const bookShelf = {
  books: ["The Last Kingdom", "The Mist"],
  getBooks() {
    return this.books;
  },
};

console.log(bookShelf.getBooks()); // ["The Last Kingdom", "The Mist"]

Diagram 10. this.books

this.books

this
↓
current object
↓
books property

Explanation

Inside getBooks(), this.books means:

"get the books property of the current object."

11. Changing an array by reference

The books property stores an array.

Arrays are changed by reference.

So this works:

const bookShelf = {
  books: ["The Last Kingdom"],
};

bookShelf.books.push("The Mist");
console.log(bookShelf.books); // ["The Last Kingdom", "The Mist"]

Diagram 11. Changing the books array

bookShelf.books
↓
array reference
↓
push("The Mist")
↓
array changes

Explanation

The array itself changes because push() modifies the original array.

12. Adding books through a method

Now let's do the same thing through a method using this.

const bookShelf = {
  books: ["The Last Kingdom"],

  getBooks() {
    return this.books;
  },

  addBook(bookName) {
    this.books.push(bookName);
  },
};

console.log(bookShelf.getBooks()); // ["The Last Kingdom"]

bookShelf.addBook("The Mist");
bookShelf.addBook("Dream Guardian");

console.log(bookShelf.getBooks());
// ["The Last Kingdom", "The Mist", "Dream Guardian"]

Diagram 12. How addBook() works

addBook("The Mist")
↓
this.books.push("The Mist")
↓
books array becomes longer

Explanation

The method changes the object's books property directly.

13. A method does not always need return

Look at this method:

addBook(bookName) {
  this.books.push(bookName);
}

It does not return anything.

That is okay.

Its job is not to return a value. Its job is to change the array.

Diagram 13. Two different method jobs

Method can:
1. return data
2. change data

Explanation

getBooks() returns data. addBook() changes data.

Both are valid.

14. Array of objects inside an object

Often, instead of storing simple strings, we store an array of objects.

Example

const bookShelf = {
  books: [
    { title: "The Last Kingdom", rating: 8 },
    { title: "The Mist", rating: 6 },
  ],
  getBooks() {
    return this.books;
  },
};

Diagram 14. books as an array of objects

bookShelf
│
└─ books
   │
   ├─ { title: "The Last Kingdom", rating: 8 }
   └─ { title: "The Mist", rating: 6 }

Explanation

Now each book is a full object, not just a string.

This is much more useful in real applications.

15. Adding a new book object

If books contains objects, then addBook() should also expect an object.

const bookShelf = {
  books: [
    { title: "The Last Kingdom", rating: 8 },
    { title: "The Mist", rating: 6 },
  ],

  getBooks() {
    return this.books;
  },

  addBook(newBook) {
    this.books.push(newBook);
  },
};

bookShelf.addBook({ title: "Dream Guardian", rating: 9 });

Diagram 15. Adding object to array

newBook
↓
{ title: "Dream Guardian", rating: 9 }
↓
push into this.books

Explanation

Now the method adds full book objects to the array.

16. Iterating over an array of objects inside a method

Because this.books is now an array of objects, we must remember that each element is an object.

That means when looping, we use:

and not just book.

Diagram 16. Inside the books loop

for (const book of this.books)

book
│
├─ title
└─ rating

Explanation

Every element of this.books is one book object.

17. Method: get average rating

const bookShelf = {
  books: [
    { title: "The Last Kingdom", rating: 8 },
    { title: "The Mist", rating: 6 },
  ],

  getAverageRating() {
    let totalRating = 0;

    for (const book of this.books) {
      totalRating += book.rating;
    }

    return totalRating / this.books.length;
  },
};

console.log(bookShelf.getAverageRating()); // 7

Diagram 17. How getAverageRating() works

Books:
8
6

totalRating = 0
↓
0 + 8 = 8
8 + 6 = 14

books.length = 2

14 / 2 = 7

Explanation

The method:

  1. starts with total 0
  2. adds all book ratings
  3. divides by the number of books

18. General plan for this method

To write getAverageRating(), we:

  1. create a method
  2. create a variable for the total
  3. loop through this.books
  4. add each book.rating
  5. divide by this.books.length

Diagram 18. Average rating algorithm

Start total = 0
↓
Loop through books
↓
Add each rating
↓
Divide by number of books
↓
Return average

Explanation

This is a very common method pattern.

19. Changing an object inside an array

Another very common task is updating one object inside an array.

For example:

Example start

const bookShelf = {
  books: [
    { title: "The Last Kingdom", rating: 8 },
    { title: "The Mist", rating: 6 },
  ],

  changeRating(bookName, newRating) {
    // code here
  },
};

Diagram 19. Goal of changeRating()

Need to:
1. find the right book
2. change its rating

Explanation

This is one of the most useful real-world object method tasks.

20. First step: find the correct object

const bookShelf = {
  books: [
    { title: "The Last Kingdom", rating: 8 },
    { title: "The Mist", rating: 6 },
  ],

  changeRating(bookName, newRating) {
    for (const book of this.books) {
      if (book.title === bookName) {
        // correct object found
      }
    }
  },
};

Diagram 20. Search inside method

Loop through this.books
↓
Check:
book.title === bookName ?
↓
If yes → found the needed object

Explanation

The loop checks every book until the needed title is found.

21. Second step: change the property

Once the correct object is found, we change its rating.

const bookShelf = {
  books: [
    { title: "The Last Kingdom", rating: 8 },
    { title: "The Mist", rating: 6 },
  ],

  changeRating(bookName, newRating) {
    for (const book of this.books) {
      if (book.title === bookName) {
        book.rating = newRating;
      }
    }
  },
};

bookShelf.changeRating("The Mist", 9);
bookShelf.changeRating("The Last Kingdom", 4);

console.log(bookShelf.books);

Diagram 21. Changing the right object

Search for "The Mist"
↓
Found object:
{ title: "The Mist", rating: 6 }
↓
Change:
rating = 9

Explanation

book is a reference to the real object inside the array, so changing book.rating changes the original object.

22. Important correction in the original example

This is wrong:

changeRating("The Mist", 9);

because changeRating is a method of bookShelf.

The correct call is:

bookShelf.changeRating("The Mist", 9);

Diagram 22. Function call vs method call

Wrong:
changeRating(...)

Correct:
bookShelf.changeRating(...)

Explanation

Methods must be called through the object they belong to.

23. Why changing works

This works because objects inside arrays are also accessed by reference.

So when the loop variable book gets one object, it refers to the actual object in the array.

That is why this changes the real data:

book.rating = newRating;

Diagram 23. Reference to object in array

this.books
↓
one object
↓
book variable points to that object
↓
change property
↓
original object updates

Explanation

You are not changing a copy. You are changing the real object inside the array.

24. Full final example

const bookShelf = {
  books: [
    { title: "The Last Kingdom", rating: 8 },
    { title: "The Mist", rating: 6 },
  ],

  getBooks() {
    return this.books;
  },

  addBook(newBook) {
    this.books.push(newBook);
  },

  getAverageRating() {
    let totalRating = 0;

    for (const book of this.books) {
      totalRating += book.rating;
    }

    return totalRating / this.books.length;
  },

  changeRating(bookName, newRating) {
    for (const book of this.books) {
      if (book.title === bookName) {
        book.rating = newRating;
      }
    }
  },
};

bookShelf.addBook({ title: "Dream Guardian", rating: 9 });
bookShelf.changeRating("The Mist", 10);

console.log(bookShelf.getBooks());
console.log(bookShelf.getAverageRating());

Diagram 24. Full bookShelf model

bookShelf
│
├─ books
│  ├─ { title, rating }
│  ├─ { title, rating }
│  └─ { title, rating }
│
├─ getBooks()
├─ addBook(newBook)
├─ getAverageRating()
└─ changeRating(bookName, newRating)

Explanation

This is a strong example of an object that stores both data and methods.

25. Common beginner mistakes

Mistake 1. Using object name instead of this

Wrong inside the method:

bookShelf.books.push(bookName);

Better:

this.books.push(bookName);

Mistake 2. Forgetting to call the method through the object

Wrong:

changeRating("The Mist", 9);

Correct:

bookShelf.changeRating("The Mist", 9);

Mistake 3. Forgetting that books is an array of objects

Wrong idea:

totalRating += book;

Correct:

totalRating += book.rating;

Mistake 4. Returning nothing when you actually need a result

getBooks() and getAverageRating() should return values.

Mistake 5. Forgetting that addBook() may not need return

It can just change the data.

Diagram 25. Common mistakes summary

1. Use this, not object name
2. Call methods through the object
3. Remember books may be objects, not strings
4. Return values only when needed
5. Changing data is also a valid method job

Explanation

These are some of the most common beginner mistakes with object methods.

26. Quick summary

Object method

A function stored inside an object.

this

The object that called the method.

this.books

The books property of the current object.

getBooks()

Returns the object's books.

addBook()

Adds a book to the array.

getAverageRating()

Calculates the average rating.

changeRating()

Finds the correct book and updates its rating.

Diagram 26. Final map of object methods

Object methods
│
├─ object stores data
├─ object stores methods
├─ methods use this
├─ methods can return data
├─ methods can change data
└─ methods can work with arrays of objects

Explanation

This is the full beginner picture of object methods.

27. Revision block

1. An object method is a function inside an object
2. Methods are called with dot notation
3. this means the object that called the method
4. this is used to access the object's own properties
5. Methods can return data
6. Methods can also change data
7. Object properties can store arrays
8. Those arrays can contain objects
9. You can loop through this.books with for...of
10. You can find one object in the array and change its property

28. Final conclusion

Object methods are one of the most important steps in learning JavaScript objects properly.

If you understand:

then you already have a strong base for writing more realistic JavaScript code.

Object methods are used everywhere in full-stack development:

⬅ Back