Javascript Interview Questions ( Call, Bind and Apply )

Aashi Gangrade
2 min readJan 26, 2024

--

We will take a code snippet and solve it using call(), bind() and apply() and know how it is used to set this.

var obj = {name : "Aashi"};
function sayHello(){
return "Hello " + this.name;
}

console.log(sayHello());

What do you think the console will print the name as ?

Output : Hello

Do you want it to say “Hello” to you? Okay, let’s try it out using the above methods.

call(), apply() and bind() methods belong to the Function.prototype property.

call()

The call() method calls the function with a given this value and arguments provided individually.

function sayHello(){
return "Hello " + this.name;
}

var obj = {name: "Aashi"};

sayHello.call(obj); //Hello Aashi

Here we are passing the obj to the call() and then this points to “obj” object.

apply()

The apply() method calls the specified function with a given this value, and arguments provided as an array (or an array-like object).

function sayHello(day,status){
return "Hello " + this.name + " today is " + day + " and feel "+ status;
}

var obj = {name: "Aashi"};

sayHello.apply(obj,["tuesday", "good"]); // 'Hello Aashi today is tuesday'

Here we are passing the arguments as an array. The length of the arguments array should be equal to the number of arguments to be passed to the function.

apply() is almost identical to call() except for the fact call() accepts an argument list, while apply() accepts a single array of arguments — for example, func.apply(this, [‘eat’, ‘bananas’]) vs. func.call(this, ‘eat’, ‘bananas’).

bind ()

This works a little bit different from call() and apply().

According to MDN,The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Basically we use a bind() method to call a function with this value. Now, let's witness the execution of our initial code using bind().

function sayHello(){
return "Hello " + this.name;
}

var obj = {name: "Aashi"};

const helloFn = sayHello.bind(obj);

console.log(helloFn());

helloFn has the binded method and when we call helloFn it gives us the value of “this”.

--

--