Javascript Interview Questions ( Call, Bind and Apply ) - Polyfills, Output Based, Explicit Binding

Javascript Interview Questions ( Call, Bind and Apply ) - Polyfills, Output Based, Explicit Binding

Working with JavaScript “this” keyword can be tricky.

Have you encountered with the famous thought "it works, but I don’t know why" in your interviews when you work with "this". If you want to know about "this" keyword then you can watch this video

Javascript Interview Questions ( 'this' Keyword ) - Output Based, Scope, Implicit Binding, etc.

Call, bind and Apply are three super important JavaScript methods that are available to all JavaScript functions, which are used to set the this keyword independent of how the function is called. You can use these methods to tie a function into an object and call the function as if it belonged to that object.Therefore, these are incredibly important for all Javascript Developers to know how they work and when to use them, and that is why this is such an important topic for javascript interviews. 💵\

So let's go and have a deep dive into explicit object binding in javascript i.e., Call, Bind and Apply methods and discuss some of the most commonly asked interview questions on it!

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 : "Piyush"};
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 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: "Piyush"};

sayHello.call(obj); //Hello Piyush

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: "Piyush"};

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

Here we are passing the arguments as an array.As we can the the length of the arguments array should be equal to the no. 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. Let's see our initial code in action using bind().

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

var obj = {name: "Piyush"};

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".

Let's head to some interview Questions now. Since we want you to clear your dream company interviews pretty soon. 🎉

Interview Questions

1. Give the output of the following question.

const person = { name: 'Piyush' };

function sayHi(age) {
  return `${this.name} is ${age} years`;
}

console.log(sayHi.call(person, 24)); ---1?
console.log(sayHi.bind(person, 24)); ---2?

Output

  1. It will give "Piyush is 24 years"

  2. It will return the function "sayHi"

Comment down below if your answer was same as mine. We get the bonus points since that means you got the fundamental of call(), apply() and bind().

2. Give the output of the following code snippet.

const age = 10;
var person = {
    name: "Piyush",
  age: 20,
  getAge: function(){
    return this.age;
  }
}

var person2 = {age:  24};
person.getAge.call(person2); // show with apply and bind as well

Explaination

First of all what do you think will be the output of the following line.

console.log(person.getAge());

Hmm.....🤔

getAge() is a method of a person object. Where would this point to? Obviously it will point to the age variable of person object so it will output 20.

What if we want to use the getAge() method to fetch age from another object? Well, here comes call() to the rescue. WOhoo!

console.log(person.getAge().call(person2));

This will call getAge() with person2 object and will print 24 since it has the age variable.

Let's try with bind() and apply() too.

console.log(person.getAge().apply(person2));

Where is the arguments array? 😡 Umm well getAge() doesn't require any arguments so this line of code will print 24

console.log(console.log(person.getAge().bind(person2)());

Well this will return a function remember? So we need to add an additional function call to call that returned function.

Okay next question!

3. What will the output of the below code snippet?

var status = '😎';

setTimeout(() => {
  const status = '😍';

  const data = {
    status: '🥑',
    getStatus() {
      return this.status;
    },
  };

  console.log(data.getStatus()); ---1?
  console.log(data.getStatus.call(this)); ---2?
}, 0);
  1. 🥑

  2. 😎

Explaination

The value of the this keyword is dependent on where you use it.

In a method, like the getStatus method, the this keyword refers to the object that the method belongs to. The method belongs to the data object, so this refers to the data object. When we log this.status, the status property on the data object gets logged, which is "🥑".

With the call method, we can change the object to which the this keyword refers.

In functions, the thiskeyword refers to the the object that the function belongs to.

We declared the setTimeout function on the global object, so within the setTimeout function, the this keyword refers to the global object. On the global object, there is a variable called status with the value of "😎". When logging this.status, "😎" gets logged.

Was your answer correct? Comment down below if yes!

4. write printAnimals() in such a way that it prints all animals in object below.

const animals = [
  { species: 'Lion', name: 'King' },
  { species: 'Whale', name: 'Queen' }
];

function printAnimals(i) {
    this.print = function() {
      console.log('#' + i + ' ' + this.species
                  + ': ' + this.name);
    }
    this.print();
  }

Explaination

Let's try to call the function using call method

printAnimals.call(animals); // #undefined undefined: undefined

It gives output of undefined. Why? Well call demands object to be the parameter not array of objects like animals.

Approach will be run a for loop iterate through array of objects and call it on every object.

for (let i = 0; i < animals.length; i++) {
  printAnimals.call(animals[i], i);  #0 Lion: King #1 Whale: Queen
}

5. How to append an array to another array.

example

const array = ['a', 'b'];
const elements = [0, 1, 2];
array.push(elements);

explaination

array.push will push the array instead of elements rather we can do

array.push.apply(array, elements); //[a,b,0,1,2]

elements is an arrayList paased as an argument where it will push each element to the array.

6. Find min/max in an array and use apply to enhance a built-in function.

const numbers = [5, 6, 2, 3, 7];

// using Math.min/Math.max apply

let max = Math.max.apply(null, numbers); // equal to Math.max

let min = Math.min.apply(null, numbers); // equal to Math.min 

// vs. simple loop based algorithm

max = -Infinity, min = +Infinity;

for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] > max) {
    max = numbers[i];
  }
  if (numbers[i] < min) {
    min = numbers[i];
  }
}

I have simply given the solution since we have seen the same concept in the above question as well.

7. Create a bound function

function f() {
  alert( this ); // ?
}

let user = {
  g: f.bind(null)
};

user.g();

Explaination

The context of a bound function is hard-fixed. There’s just no way to further change it. It will return a window object.

And that's it for the blog. If you are liking the blogs give a big like. This would motivate me to write more such blogs.

We will creating a github repo soon with all the interview questions curated. So that next time you prepare for your interviews you don't have to search anywhere else. 😎

Connect with us on Twitter 👇🏻

📌 Piyush Agarwal (RoadsideCoder)

Did you find this article valuable?

Support Roadside Coder by becoming a sponsor. Any amount is appreciated!