call(), apply() and bind() in JavaScript explained
Tags: javascript, functional
Published: 2020-10-10 10:21:10

In my last post, I discussed the Function constructor. How the function object created from it and the properties and methods of the function object.

In this article, we will go into the details of the following three function methods.
- call()
- apply()
- bind() 

They are basically used to call the function (except bind, bind() returns a new function that we can use as per our need). They all take a `this` value depending upon the context to execute the function in that context. Let's take a look at each one in detail. 

----------------
# call()

[MDN definition](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) : The call() method calls a function with a given `this` value and arguments provided individually.

> **[Syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call)**: func.call([thisArg[, arg1, arg2, ...argN]])
> - **thisArg**: optional (this will be the value upon which the function would call)
> - **arg1**, **arg2**, **...argN**: optional (arguments of the function)

>> - the first argument represents a value on which the function would call (it refers to the current object/the calling object)
>> - other arguments represent the value to the parameter of the function

Let's take a look at an example:

```
// defining a global variable
var lastName = 'global_name';

const func = function(firstName) {
    return firstName + " " + this.lastName; /** the value of 'this' 
    is defined how we call the function */
}

// this object is passed as the first argument to the call method
var person = {
    lastName: 'person_name'
}

// calling the function usually
func('Sachin'); // Sachin global_name

/** calling the function using the call method and setting the 
'this' value to the 'person' object */
func.call(person, 'Sachin'); // Sachin person_name

// using call method without passing the first argument
func.call(); // undefined global_name

// passing the first argument as null or undefined
func.call(null, 'Sachin'); // Sachin global_name
func.call(undefined, 'Sachin'); // Sachin global_name

/******************** in strict mode*****************/
func.call(); /** Cannot read property 'lastName' of undefined*/
func.call(null, 'Sachin'); /** Cannot read property 'lastName' of null*/
func.call(undefined, 'Sachin'); /** Cannot read property 
'lastName' of undefined*/
```

As seen from the example, we can use the call method to call a function on any object. 

> - When usually calling the function then `this` value will set to the global object `window`. This `window` object is having a property `lastName` which we defined globally in our code will return from the function.

> - When calling the function using the call method and passing the first argument a `person` object then `this` value will set to that `person` object (not `window` object this time) and its `lastName` property will return.

> - Using the call method without passing any arguments, `this` value will set to the global object `window` and its property `lastName` will return.

> - When the first argument passed is `null` or `undefined` then still the `this` will set to the global `window` object in this case.

>> #### Caution: For strict mode
In 'strict mode', the value of `this` will be `undefined`. To know about strict mode refer to this [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode).

----------------
# apply()
> **[Syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply)**: func.apply(thisArg, [ argsArray])
> - **thisArg**: (this will be the value upon which the function would call)
> - **argsArray**: optional (arguments of the function passed in an array)

apply() is almost similar to call() except that it takes an array as a second argument and passes the members of that array as arguments to the calling function.

Example:
```
var name = 'Sachin';

const func = function (age, hobby) {
  return (this.name + ' is ' + age + ' years old and his hobby is '
  + hobby);
};

var person = {
    name: 'John'
}

func(); /** Sachin is undefined years old and his 
hobby is undefined*/
func.apply(); /** Sachin is undefined years old and his 
hobby is undefined*/

console.log(func() === func.apply()); /** true*/

func('15', 'writing'); /** Sachin is 15 years old and his 
hobby is writing*/
func.apply(undefined, ['15', 'writing']); /** Sachin is 15 years 
old and his hobby is writing*/
func.apply(null, ['15', 'writing']); /** Sachin is 15 years 
old and his hobby is writing*/

/********* changing 'this' to 'person' object*********/
func.apply(person, ['20', 'music']); /** John is 20 years 
old and his hobby is music*/

/**************** strict mode ***************/
/** Cannot read property 'name' of undefined*/
func(); 
func('15', 'writing'); 
func.apply();
func.apply(undefined, ['15', 'writing']);

/** Cannot read property 'name' of null */
func.apply(null, ['15', 'writing']); 

```

----------------
# bind()

> **[Syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind)**: func.bind(thisArg[, arg1[, arg2[, ...argN]]])

- bind() method creates and returns a copy of the function `func`.
- when that new function is called, it has it's `this` value set to the value provided by `thisArg`.
- arg1, arg2,..., argN are arguments that prepends to the arguments of that new returned function.

Let's understand this with an example:
```
// defining a person object
/** this object has a property 'age' and a method 
'getNameAndAge' */
const person = {
    age: 42,
    getNameAndAge: function(name) {
        return name + ' ' + this.age;
    }
}

// calling the method on the 'person' object directly
person.getNameAndAge('Sachin'); // Sachin 42

// assigning the reference of the method to variable nameAndAge
const nameAndAge = person.getNameAndAge;

// calling the function assigned to nameAndAge by referencing it 
nameAndAge('Sachin'); /** Sachin undefined (the function gets
invoked at the global scope)*/

// use of bind method
const boundNameAndAge = nameAndAge.bind(person, 'Sachin');
boundNameAndAge() /** Sachin 42 (bind method creates
a new function and bounds 'this' value to 'person' object)*/

// bind without any arguments
const boundNameAndAge = nameAndAge.bind();
boundNameAndAge('Sachin') // Sachin undefined

// setting 'this' to 'undefined'
const boundNameAndAge = nameAndAge.bind(undefined, 'Sachin'); 
boundNameAndAge() // Sachin undefined

// setting 'this' to 'null'
const boundNameAndAge = nameAndAge.bind(null, 'Sachin'); 
boundNameAndAge() // Sachin undefined
```

- When we are executing `nameAndAge('Sachin');`, we are executing that function in the global scope and `this` here refers to the global `window` object and we have not defined `age` in the global scope, that's why it returns `undefined`.

- `const boundNameAndAge = nameAndAge.bind(person, 'Sachin');`
    - `bind` method creates and returns a copy of nameAndAge function and sets `this` to `person` object. We are assigning that newly created function to variable `boundNameAndAge`. When we execute `boundNameAndAge()`, has it's `this` set to `person` and `age` property of `person` object returns.

- In case of no arguments or `this` set to `null` or `undefined`, the `this` value for the newly created function is decided by the `this` of the executing scope.


# Conclusion
- call() and apply() executes the function immediately, whereas bind() returns a new function.
- the object/value on which the function executes depends on the `this` value defined by the context.


> Thanks for reading. If you found this article helpful please like and share it with others so that they will also get the benefit. Feedbacks are welcome: [Twitter](https://twitter.com/toocoolsachin8) | [Instagram](https://instagram.com/toocoolsachin) | [LinkedIn](https://linkedin.com/in/sachin-koli)