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

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

this keyword in javascript is arguably one the most confusing topics ever, which sometimes makes even senior developers scratch their heads. ] And that is why this is one the most important topics for Javascript interviews because it allows interviewers to ask tricky questions and confuse the candidates.

Before this article you can go through a video on Objects. Here is the link

Javascript Interview Questions ( Objects )

P.S. This is the written format of this video. FInd video here.

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

The value of this is determined by how a function is called (runtime binding). So, there are two types of binding when it comes to object binding in JS, one is implicit and other is explicit.

Implicit Binding

Implicit Binding is applied when you invoke a function in an Object using the dot notation. this in such scenarios will point to the object using which the function was invoked. Or simply the object on the left side of the dot.

Explicit Binding

In Explicit Binding, you can force a function to use a certain object as its this. Explicit Binding can be applied using call(), apply(), and bind().

Interview Questions on "this"

Question 1 - Explain ‘this’ keyword?

In the English language, we use the pronoun ‘this’ to reference something:

Like suppose we have a bucket of fruits, when we say “this” inside of it so that will mean the bucket itself.

Fruits are kept in this bucket

Similarly, in the JavaScript language, the ‘this’ keyword is used to reference something — an object!

It can't be set by assignment during execution, and it may be different each time the function is called.

Global

So for example if we console.log this here, we get the window object.

let a = 5

console.log(this.a); //undefined

This inside a function

  • Normally it targets the window object.

In it, this points to the owner of the function call, I repeat, THE FUNCTION CALL, and NOT the function itself. The same function can have different owners in different scenarios.

function myFunction() {
    console.log(this)
}
myFunction(); // window object
  • **What about Arrow Functions? **

It takes it's this from the outer “normal” function, this won't make much sense now, since as you can see it’s also pointing to window object.

const myFun=()=> {
    console.log(this)
}
myFun(); // window object
  • So lets see the behaviour of this inside of an Object

Method inside object

let user = {
  name: "Piyush",
  age: 24,
    getDetails() {
        console.log(this.name); //Piyush
    }
};

What happens when we have functions inside a nested object key?

let user = {
  name: "Piyush",
  age: 24,
    childObj:{
        newName:"Roadside Coder",
        getDetails() {
            console.log(this.newName, "and" ,this.name);
        }
    }
};

let us know in the comments what will be the output of user.childObj.getDetails()?

What if the same functions are arrow functions inside the object?

let user = {
  name: "Piyush",
  age: 24,
    getDetails: () => {
        console.log(this.name); 
    }
};

Does user.getDetails() give you any output? Well it is empty since it points to window object.

let user = {
  name: "Piyush",
  age: 24,
    getDetails() {
        const nestedArrow = () => console.log(this.name); //Piyush
        nestedArrow();
    }
};

user.getDetails() gives "Piyush" as the output since it points to the parent's context i.e. the user object.

Class / Constructors

class user {
    constructor(n){
        this.name = n
    }
    getName(){
        console.log(this.name);
    }
}

const User = new user("Piyush") // => This will generate a user object from the above class
User.getName();

Question -2 Give the output of the following snippet.

const user = {
  firstName: 'Piyush!',
  getName() {
    const firstName = 'Jen!';
    return this.firstName;
  }
};
console.log(user.getName()); // What is logged?

Piyush! is logged to the console. user.getName() is a method invocation, that's why this inside the method equals object.

There's also a variable declaration const firstName = 'Jen!' inside the method. The variable doesn't influence anyhow the value of this.firstName.

Question 3 -What is the result of accessing its ref? Why?

function makeUser() {
  return {
    name: "John",
    ref: this
  };
}

let user = makeUser();

alert( user.ref.name ); // What's the result?

Answer: an error.

That’s because rules that set this do not look at object definition. Only the moment of call matters.

Here the value of this inside makeUser() is undefined, because it is called as a function, not as a method with “dot” syntax.

The value of this is one for the whole function, code blocks and object literals do not affect it.

So ref: this actually takes current this of the function.

We can rewrite the function and return the same this with undefined value:

Follow up -

How do u make it work?

function makeUser() {
  return {
    name: "Piyush Agarwal",
    ref() {         
      return this;
    }
  };
}

let user = makeUser();

alert( user.ref().name ); // Piyush Agarwal

You make ref a method and then there will be no error. You will get the output as Piyush Agarwal.

Question 4 -What logs to console the following code snippet?


const user = { name: 'Piyush Agarwal!', logMessage() { console.log(this.name); // What is logged? } }; setTimeout(user.logMessage, 1000);

```plaintext

After a delay of 1 second, `undefined` is logged to console. 

While `setTimeout()` function uses the `object.logMessage` as a callback, still, it invokes `object.logMessage` as a regular function, rather than a method.

And during a regular function invocation *this* equals the global object which is `window` in the case of the browser environment.

That's why `console.log(this.message)` inside `logMessage` method logs `window.message`, which is `undefined`.

How can you fix this code so that 'Piyush Agarwal!' is logged to console? 
Write your solution in a comment below!

### Question 5 -What logs to console of the following code snippet?

const user = { name: 'Piyush', greet() { return Hello, ${this.name}!; }, farewell: () => { return Goodbye, ${this.name}!; } }; console.log(user.greet()); // What is logged? console.log(user.farewell()); // What is logged?


'Hello, Piyush!' and 'Goodbye, undefined!' are logged to console.

When calling `object.greet()`, inside the method `greet()` `this` value equals `object`because `greet` is a regular function. Thus `object.greet()` returns `'Hello,Piyush!'`.

But `farewell()` is an arrow function, so *[this* value inside of an arrow function]*always* equals `this` of the outer scope.

The outer scope of `farewell()` is the global scope, where `this` is the global object. Thus `object.farewell()` actually returns `'Goodbye, ${window.name}!'`, which evaluates to `'Goodbye, undefined!'`.

### Question 6

Create an object `calculator` with three methods:

- `read()` prompts for two values and saves them as object properties with names `a` and `b` respectively.
- `sum()` returns the sum of saved values.
- `mul()` multiplies saved values and returns the result.

Example :

let calculator = { // ... your code ... };

calculator.read(); alert( calculator.sum() ); alert( calculator.mul() );


Close this window and try to solve it on your own. 

Let's check the solution.

let calculator = { sum() { return this.a + this.b; },

mul() { return this.a * this.b; },

read() { this.a = +prompt('a?', 0); this.b = +prompt('b?', 0); } };

calculator.read(); alert( calculator.sum() ); alert( calculator.mul() );


Was your solution different than this? Comment below and we will discuss.


### Question 7 Give output of the following code snippet.

var length = 4; function callback() { console.log(this.length); // What is logged? } const object = { length: 5, method(callback) { callback(); } }; object.method(callback, 1, 2);


`4` is logged to console.

`callback()` is called using regular function invocation inside `method()`. Since this value during a regular function invocation equals the global object, `this.length` is evaluated as `window.length` inside `callback()` function.

The first statement `var length = 4`, being in the outermost scope, creates a property `length` on the global object: `window.length` becomes `4`.

Finally, inside the `callback()` function `this.length` evaluates as `window.length` — `4` being logged to console.

### Question 8 -What is the output of the following code snippet?

var length = 4; function callback() { console.log(this.length); // What is logged? } const object = { length: 5, method() { arguments0; } }; object.method(callback, 1, 2);


`3` is logged to console. 

`obj.method(callback, 1, 2)` is invoked with 3 arguments: `callback`, `1` and `2`. As result the `arguments` special variable inside `method()` is an array-like object of the following structure:

{ 0: callback, 1: 1, 2: 2, length: 3 }


Because `arguments[0]()` is a method invocation of `callback` on `arguments` object, `this` inside the `callback` equals `arguments`. As result `this.length` inside `callback()` is same as `arguments.length` — which is `3`.

### Question-9 Write the implementation of this calc()

const result = calc.add(10).multiply(5).subtract(30).add(10) console.log(result.total) ---- What is logged?



Solution : 👇🏼

var calc = { total: 0, add(a) { this.total += a; return this; }, subtract(a) { this.total -= a; return this; }, multiply(a) { this.total *= a; return this; }, };


Finally coming to the end of this blog. Hope you had a great read.

Do give a 👍 if you liked the content. More such blogs coming on your way!

Connect with us on Twitter 👇🏻

📌 [Piyush Agarwal (RoadsideCoder)](https://twitter.com/Piyush_eon)

Did you find this article valuable?

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