CodeBlanks Logo Icon CodeBlanks

Adding methods

JavaScript course · Advanced · Lesson 21/100

Add add, remove and find methods to the class.

Adding methods to a class

The internal state is ready; now let's add behavior. A method is a function defined in the class body that reaches the instance's data through this.

We'll write three core methods: add appends an item to the array, remove takes out the first match, and find returns the first item that matches a condition. Each one works on this.items.

Method chaining

If a method returns this, we can link calls back to back. This is called method chaining. For example, list.add("a").add("b") adds two items in a row.

To allow this, add and remove must end with return this. find returns the found item, so it doesn't join the chain; it gives back the item as the result.

Exercise Add the add, remove and find methods

Add three methods to the class: add(item) pushes the item and returns this; remove(item) removes the first match and returns this; find(callback) returns the first item that matches.

Show example solution
The add method pushes the item with push and returns this. remove finds the index with indexOf, splices it out, and returns this. find loops, calls callback for each item, and returns the first one that returns true.

Example solution:
// Utility library
class Collection {
  constructor() {
    this.items = [];
  }
  add(item) {
    this.items.push(item);
    return this;
  }
  remove(item) {
    const index = this.items.indexOf(item);
    if (index !== -1) {
      this.items.splice(index, 1);
    }
    return this;
  }
  find(callback) {
    for (const item of this.items) {
      if (callback(item)) {
        return item;
      }
    }
    return undefined;
  }
}

Test yourself

  1. What does method chaining require?

    • The method must return this
    • The method must return undefined
    • The method must be static
    • The method must be async
    Show answer

    The method must return this — Correct! Methods that return this can be called in a chain.

  2. Add the item in the add body

        this.items.____;
    Show answer
        this.items.push(item);
  3. Match each method to its purpose

    add
    adds an item
    remove
    removes an item
    find
    returns first match
    return this
    enables chaining

All lessons in Advanced