Movatterモバイル変換


[0]ホーム

URL:


Home
Dmitri Pavlutin
I help developers understand Frontend technologies
Post cover

7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them?

Posted February 23, 2021

In JavaScriptthis is the function invocation context.

The challenge is thatthis has a complicated behavior. That's why during a JavaScript coding interview you might be asked howthis behaves in certain situations.

Since the best way to prepare for a coding interview is to practice, in this post I compiled a list of 7 interesting interview questions onthis keyword.

If you're not familiar withthis keyword, I recommend reading the postGentle Explanation of "this" in JavaScript.

Note: JavaScript snippets below run in non-strict mode, also known as sloppy mode.

Question 1: Variable vs property

What logs to console the following code snippet:


const object = {
message: 'Hello, World!',
getMessage() {
const message = 'Hello, Earth!';
return this.message;
}
};
console.log(object.getMessage()); // What is logged?

Expand answer

'Hello, World!' is logged to console.Open the demo.

object.getMessage() is a method invocation, that's whythis inside the method equalsobject.

There's also a variable declarationconst message = 'Hello, Earth!' inside the method. The variable doesn't influence anyhow the value ofthis.message.

Question 2: Cat name

What logs to console the following code snippet:


function Pet(name) {
this.name = name;
this.getName = () => this.name;
}
const cat = new Pet('Fluffy');
console.log(cat.getName()); // What is logged?
const { getName } = cat;
console.log(getName()); // What is logged?

Expand answer

'Fluffy' and'Fluffy' are logged to console.Open the demo.

When a function is invoked as a constructornew Pet('Fluffy'),this inside the constructor function equals the constructed object.

this.name = name expression insidePet constructor createsname property on the constructed object.

this.getName = () => this.name creates a methodgetName on the constructed object. And since the arrow function is used,this inside the arrow function equals tothis of the outer scope — the constructor functionPet.

Invokingcat.getName(), as well asgetName(), returns the expressionthis.name that evaluates to'Fluffy'.

Question 3: Delayed greeting

What logs to console the following code snippet:


const object = {
message: 'Hello, World!',
logMessage() {
console.log(this.message); // What is logged?
}
};
setTimeout(object.logMessage, 1000);

Expand answer

After a delay of 1 second,undefined is logged to console.Open the demo.

WhilesetTimeout() function uses theobject.logMessage as a callback, still, it inovkesobject.logMessage as a regular function, rather than a method.

And during aregular function invocationthis equals the global object, which iswindow in the case of the browser environment.

That's whyconsole.log(this.message) insidelogMessage method logswindow.message, which isundefined.

Side challenge: how can you fix this code so that'Hello, World!' is logged to console? Write your solution in a comment below!

Question 4: Artificial method

How can you calllogMessage function so that it logs"Hello, World!"?


const object = {
message: 'Hello, World!'
};
function logMessage() {
console.log(this.message); // "Hello, World!"
}
// Write your code here...

Expand answer

There are at least 3 ways how to calllogMessage() as a method on theobject. Any of them is considered a correct answer:


const object = {
message: 'Hello, World!'
};
function logMessage() {
console.log(this.message); // logs 'Hello, World!'
}
// Using func.call() method
logMessage.call(object);
// Using func.apply() method
logMessage.apply(object);
// Creating a bound function
const boundLogMessage = logMessage.bind(object);
boundLogMessage();

Open the demo.

Question 5: Greeting and farewell

What logs to console the following code snippet:


const object = {
who: 'World',
greet() {
return `Hello, ${this.who}!`;
},
farewell: () => {
return `Goodbye, ${this.who}!`;
}
};
console.log(object.greet()); // What is logged?
console.log(object.farewell()); // What is logged?

Expand answer

'Hello, World!' and'Goodbye, undefined!' are logged to console.Open the demo.

When callingobject.greet(), inside the methodgreet()this value equalsobject becausegreet is a regular function. Thusobject.greet() returns'Hello, World!'.

Butfarewell() is an arrow function, sothis value inside of an arrow functionalways equalsthis of the outer scope.

The outer scope offarewell() is the global scope, wherethis is the global object. Thusobject.farewell() actually returns'Goodbye, ${window.who}!', which evaluates to'Goodbye, undefined!'.

Question 6: Tricky length

What logs to console 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);

Expand answer

4 is logged to console.Open the demo.

callback() is called using regular function invocation insidemethod(). Sincethis value during a regular function invocation equals the global object,this.length is evaluated aswindow.length insidecallback() function.

The first statementvar length = 4, being in the outermost scope, creates a propertylength on the global object:window.length becomes4.

Finally, inside thecallback() functionthis.length evaluates aswindow.length4 being logged to console.

Question 7: Calling arguments

What logs to console the following code snippet:


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

Expand answer

3 is logged to console.Open the demo.

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


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

Becausearguments[0]() is a method invocation ofcallback onarguments object,this inside thecallback equalsarguments. As resultthis.length insidecallback() is same asarguments.length — which is3.

Summary

If you've answered correctly 5 or more questions, then you have a good understanding ofthis keyword!

Otherwise, you need a good refresher onthis keyword. I recommend revising the postGentle Explanation of "this" in JavaScript.

Ready for a new challenge? Try to solve the7 Interview Questions on JavaScript Closures.

Like the post? Please share!

Dmitri Pavlutin

About Dmitri Pavlutin

Software developer and sometimes writer. My daily routine consists of (but not limited to) drinking coffee, coding, writing, overcoming boredom 😉, developinga gift boxes Shopify app, andblogging about Shopify. Living in the sunny Barcelona. 🇪🇸
Email addressTwitter profileFacebook pageLinkedIn profile
Dmitri Pavlutin

About Dmitri Pavlutin

Software developer and sometimes writer. My daily routine consists of (but not limited to) drinking coffee, coding, writing, overcoming boredom 😉, developinga gift boxes Shopify app, andblogging about Shopify. Living in the sunny Barcelona. 🇪🇸
Email addressTwitter profileFacebook pageLinkedIn profile

[8]ページ先頭

©2009-2025 Movatter.jp