Master the Javascript - call(), bind() and apply() functions

Photo by Andrew Neel on Unsplash

Master the Javascript - call(), bind() and apply() functions

Let's dive into a frequently asked JavaScript interview question: the distinction between "Call," "Bind," and "Apply" functions. But before we tackle these functions, it's crucial to grasp the concept of 'this'. Understanding 'this' is like having the foundation for comprehending how "Call," "Bind," and "Apply" work, making it an essential starting point. For understanding the concept of this in depth checkout my previous article on this which is an essential concept for understanding javascript in depth!

Checkout the this article: https://shorturl.at/glG18

Demystifying JavaScript's Call, Bind, and Apply Functions

JavaScript is a versatile language, and it provides several powerful tools to manipulate functions and their context. In this blog, we'll unravel the mysteries of call, bind, and apply functions in JavaScript, explaining them in a simplest way.

So let us understand the concept of function borrowing. Whenever we want to borrow or use a function with the data of another object, it is known as function borrowing.

So, for function borrowing, we use the call, bind and apply methods. All of them have the same functionality but there is a little difference in implementation.

1) Call() function

The call function is a way to call a function with a specific context (the 'this' value) and arguments.

Syntax:

functionName.call(context, arg1, arg2, ...)

Let us understand working of call function by following example:

const person = {
  name: 'Kartik',
  greet: function() {
    console.log(`Hello, ${this.name}!`);
  }
};

const newPerson = { name: 'Disha' };
person.greet.call(newPerson);
// Output: Hello, Disha

So, let's understand the above example in detail. We have an object person having two attributes, a variable, 'name' and a function 'greet' which accesses the variable to console it to the terminal. We can have different use cases when we want to use the greet function with a different this value so for this we can use the call method to use the greet function by pointing and describing this to a different object. To understand this better we can go through the following example as well:

function displayDetails(stars, points){
    console.log(`Hello I am ${this.name} and I am ${this.description} and I have stars and points of ${stars} and ${points} respectively`);
}

var language = {
    name: 'JS',
    desc: 'The Language of web'
}

displayDetails.call(language, "10", "100");
// Guess the output - The above syntax is for using a function using call methodby providing different parameters.

2) Apply() function

This method is similar to the call() method above. The only difference between call() & apply() methods is how we pass arguments to the function. In the call() method we pass arguments using comma-separated. In the apply() method we pass an array of arguments. Let us understand this by the following example:


let studentObj = {
  firstname: "Kartik",
  lastname: "Dwivedi",
  school: "CMS, GN-1",
};
//declaring the function
let myFunc = function (city, state) {
  console.log(
    this.firstname +
      " " +
      this.lastname +
      " is from" +
      this.school +
      ", " +
      city +
      ", " +
      state
  );
};
myFunc.apply(studentObj, ["Lucknow", "Uttar Pradesh"]);
// output: Kartik Dwivedi is from, CMS, GN-1, Lucknow, Uttar Pradesh

This is how we can use the apply method instead of the call method. There is just a small syntactical difference between the two.

3) Bind() function

Bind method's functionality is quite similar to the call() method, but the main difference is using the call() method, we directly invoke the function but the bind() method first binds the function or the method and then returns a copy of the method which can be invoked or called later anytime.

It creates a copy of the function and it will bind it to the object and then return a function. It doesn't directly call the function rather it will return us a method that can be called later.

This might seem confusing but this is simple as well. Let us understand with the previous example:


let studentObj = {
  firstname: "Kartik",
  lastname: "Dwivedi",
  school: "CMS, GN-1",
};
//declaring the function
let myFunc = function (city, state) {
  console.log(
    this.firstname +
      " " +
      this.lastname +
      " is from" +
      this.school +
      ", " +
      city +
      ", " +
      state
  );
};

const bindFunction = myFunc.bind(studentObj, "Lucknow", "Uttar Pradesh");
//we can invoke or call copyFunc anytime 
copyFunc();

In the above example, we have made a bound function that can be invoked or called at any point of time in the code by directly calling the bindFunction.

In JavaScript, call, bind, and apply functions are handy for controlling the context in which a function is executed and passing arguments. Understanding these concepts is crucial for writing efficient and flexible JavaScript code.

These functions may seem complex at first, but with practice, they become valuable tools in your JavaScript toolkit. We must try to use these methods instead of using the complex this syntax of using these use cases.

Happy Coding.