end

Next lesson: Immediately Invoked Function Expression To the next lesson →

Lesson: Method chaining Repeat

§ Method chaining

In this video, we will discuss method chaining in JavaScript and how it allows you to invoke multiple methods on an object in a concise and readable way. We will also look at some common pitfalls to avoid when using method chaining.

Method chaining is a programming pattern that allows us to call multiple methods on an object in a single statement, by returning the object from each method call. This can make our code more concise, readable and expressive.

The most common use case of method chaining is in combination with the jQuery library, where it allows you to perform multiple actions on a selected set of elements in a single statement.

$("#myId").css("color", "red").slideUp().slideDown();

This example is using the jQuery library to select the element with the id "myId" and change its color to red, slide it up and then slide it down.

Method chaining can also be used with plain JavaScript objects, by returning the object from each method call.

let obj = {
  value: 0,
  increment: function() {
    this.value += 1;
    return this;
  },
  decrement: function() {
    this.value -= 1;
    return this;
  }
};

obj.increment().increment().decrement();
console.log(obj.value); // 1

In this example the object obj has two methods increment and decrement that increments or decrements the value property of the object and returns the object. Using the method chaining pattern, you can chain multiple method calls together, making the code more concise and readable.

questionnaire

Practice

Practice is the fastest way to learn knowledge permanently. I have prepared a small task for you related to the lesson.

Practice
discussion

Materials

Materials related to the lesson:
Files associated with the lesson

Materials

Next: Immediately Invoked Function Expression(04:29)

To the lesson →