JavaScript this Operator Interview Questions (original) (raw)
In JavaScript, **this is a special keyword that refers to the current object or context. It behaves differently depending on where it's used. If you use this in a regular function, it refers to the global object (in browsers, this is the window). In an object's method, this refers to the object itself.
We are going to discuss some Interview Questions related to This keyword.
1. Why this is Necessary in JavaScript?
- To provide access to an object's properties & methods from methods within that object.
- Efficiency via code reuse.
- Enables reusability and flexibility of functions across different objects.
- Supports object-oriented design principles by linking data (properties) with behavior (methods)
- Enables objects to manage their own state and behavior effectively.
2. What is the default value of this in the global context?
JavaScript `
console.log(this); // Window (browser) or global object (Node.js)
`
3. How does this behave inside a simple function?
JavaScript `
function show() { console.log(this); // Global object or undefined in strict mode } show();
`
Output
<ref *1> Object [global] { global: [Circular *1], clearInterval: [Function: clearInterval], clearTimeout: [Function: clearTimeout], setInterval: [Function: setInterval], setTimeout: [Functio...
4. What is the value of this in strict mode?
JavaScript `
"use strict"; function test() { console.log(this); } test();
`
5. How does 'this' work in an object method?
JavaScript `
const obj = { name: "GeeksforGeeks", greet() { console.log(this.name); } }; obj.greet();
`
6. How does 'this' work with nested functions?
JavaScript `
const obj = { name: "GeeksforGeeks", greet() { function inner() { console.log(this); } inner(); } }; obj.greet();
`
Output
<ref *1> Object [global] { global: [Circular *1], clearInterval: [Function: clearInterval], clearTimeout: [Function: clearTimeout], setInterval: [Function: setInterval], setTimeout: [Functio...
- In strict mode, this inside a regular function is undefined because regular functions do not automatically bind this to their enclosing object.
- To fix this, use an arrow function inside greet() as arrow functions inherit this from their outer context, ensuring this refers to obj.
7. How does this behave in an arrow function?
JavaScript ``
const obj = {
name: "Geeks",
greet: () => {
console.log(this.name); // undefined, as this
refers to the enclosing scope
}
};
obj.greet();
``
8. What is the value of this inside a class?
JavaScript `
class Person { constructor(name) { this.name = name; } greet() { console.log(this.name); // Refers to the instance of the class } } const p = new Person("GeeksforGeeks"); p.greet(); // "GeeksforGeeks"
`
9. What happens to 'this' in an IIFE?
JavaScript `
(function () { console.log(this); // Global object or undefined in strict mode })();
`
Output
<ref *1> Object [global] { global: [Circular *1], clearInterval: [Function: clearInterval], clearTimeout: [Function: clearTimeout], setInterval: [Function: setInterval], setTimeout: [Functio...
The output of the code depends on whether you are running it in strict mode or non-strict mode.
**Non-strict mode (default in regular JavaScript): In non-strict mode, when a function is called without an object context (like in your case), this refers to the global object (in the browser, it’s window).
JavaScript `
// In a browser: Window { ... } // Represents the global window object in a browser
`
**Strict mode: In strict mode ('use strict';), this inside a function call refers to undefined instead of the global object.
10. How does 'this' behave in setTimeout?
JavaScript `
const obj = { name: "GeeksforGeeks", greet() { setTimeout(function () { console.log(this.name); // undefined in strict mode }, 1000); } }; obj.greet();
`
11. How to fix 'this' in setTimeout using arrow functions?
JavaScript `
const obj = { name: "GeeksforGeeks", greet() { setTimeout(() => { console.log(this.name); // "GeeksforGeeks" }, 1000); } }; obj.greet();
`
**In this code:
- When setTimeout is used with an arrow function, this inside the arrow function refers to the outer scope's this, which is the object (obj).
- As a result, the arrow function correctly accesses the name property of obj, and the output will be "GeeksforGeeks".
12. What is 'this' when a function is bound?
JavaScript `
const obj = { name: "GeeksforGeeks" }; function greet() { console.log(this.name); } const boundGreet = greet.bind(obj); boundGreet();
`
**In this code:
- greet() is a regular function where this would normally depend on how it's called.
- greet.bind(obj) creates a new function (boundGreet) where the value of this is permanently set to the object obj.
- When boundGreet() is called, this inside the function refers to obj, so this.name outputs "GeeksforGeeks".
13. How does 'this' behave in call and apply?
JavaScript `
const obj = { name: "GeeksforGeeks" }; function greet() { console.log(this.name); } greet.call(obj); greet.apply(obj);
`
Output
GeeksforGeeks GeeksforGeeks
**In this code:
- This method calls the function immediately and sets this to obj. It then prints "GeeksforGeeks" because this.name refers to o obj.name.
- Like call(), apply() also calls the function immediately and sets this to obj. The difference is that apply() expects arguments to be passed as an array, but in this case, no arguments are needed, so the result is the same: "GeeksforGeeks".
Output
GeeksforGeeks GeeksforGeeks
14. What happens when "this" is used in a constructor function?
JavaScript `
function Person(name) { this.name = name; } const p = new Person("GeeksforGeeks"); console.log(p.name);
`
**In this code
- In a constructor function, this refers to the new object being created during the invocation of the function with the new keyword.
- When new Person("GeeksforGeeks") is called, this.name = name sets the name property of the new object to "GeeksforGeeks". The new object is returned and assigned to p, so p.name outputs "GeeksforGeeks".
15. How does "this" behave in chaining methods?
JavaScript `
const obj = { count: 0, increment() { this.count++; return this; }, show() { console.log(this.count); return this; } }; obj.increment().increment().show();
`
**In this code
- In this example, obj has two methods: increment and show. The increment method increases the count by 1 and returns the object itself (this), allowing method chaining.
- The show method prints the current count and also returns the object. Calling obj.increment().increment().show() increases count to 2 and prints 2 because the methods are chained together.
16. What is "this" in an ES module?
In an ES module, this is undefined at the top level because ES modules run in strict mode by default
JavaScript `
console.log(this); // Undefined in Es modules
`
17. What is " **this " inside the an object returned by the function?
JavaScript `
function createObject() { return { name: "GeeksforGeeks", greet() { console.log(this.name); } }; } const obj = createObject(); obj.greet();
`
In this example, the createObject function returns an object with a name property and a greet method. When obj.greet() is called, this refers to the obj itself, so it accesses obj.name and prints "GeeksforGeeks".
18 . How does "this" behave in a factory function when used inside a method of the returned object?
JavaScript `
function create(name) { return { name, greet() { console.log(this.name); } }; } const person = create("GeeksforGeeks"); person.greet();
`
**In this code
- The createPerson function creates an object with a name property and a greet method.
- When person.greet() is called, this inside the greet method refers to the person object, allowing it to access person.name and print "GeeksforGeeks".
19 . How does "this" behave in a forEach callback?
JavaScript `
[1, 2, 3].forEach(function () { console.log(this); }, { name: "GeeksforGeeks" });
`
Output
{ name: 'GeeksforGeeks' } { name: 'GeeksforGeeks' } { name: 'GeeksforGeeks' }
**In this code
- The forEach method iterates over the array [1, 2, 3], with the second argument { name: "GeeksforGeeks" } explicitly set as this inside the loop.
- During each iteration, this refers to { name: "GeeksforGeeks" }, so the object is printed for every element in the array.
20. How can you pass "this" explicitly in a Promise chain?
JavaScript `
const obj = { name: "GeeksforGeeks", greet() { return Promise.resolve(this.name).then(name => { console.log(name); }); } }; obj.greet();
`
- In this example, obj.greet() returns a promise that resolves with this.name (which is "GeeksforGeeks").
- Once the promise is resolved, the .then() method prints the value of name, which is "". So, the output is Alice.
20. How does "this" behave with getters and setters?
JavaScript ``
const obj = {
name: "Geeks",
get greet() {
return Hello, ${this.name}
;
},
set greet(newName) {
this.name = newName;
}
};
console.log(obj.greet); // Output: Hello, Geeks
obj.greet = "forGeeks";
console.log(obj.greet); // Output: Hello, forGeeks
``
Output
Hello, Geeks Hello, forGeeks
In this example, obj has a getter and setter for the greet property. The getter returns a greeting message with this.name, and the setter updates this.name. Initially, obj.greet prints "Hello, Geeks". After setting obj.greet = "forGeeks", it updates name and prints "Hello, forGeeks".
21. How does " this " behave with async iteration?
JavaScript ``
const obj = {
name: "GeeksforGeeks",
async *greet() {
yield Hello, ${this.name}
;
}
};
(async () => {
for await (const message of obj.greet()) {
console.log(message);
}
})();
``
Output
Hello, GeeksforGeeks
**In this code
- The obj.greet() method is an asynchronous generator that yields a greeting message using this.name.
- The for await...of loop iterates over the yielded values and prints "Hello, GeeksforGeeks" because this.name refers to "GeeksforGeeks".
22. How does "this" behave with Map key iteration in JavaScript?
JavaScript `
const map = new Map(); map.set("key1", { name: "Geeks" }); map.set("key2", { name: "forGeeks" }); map.forEach(function (value, key) { console.log(this.name); }, { name: "GeeksforGeeks" });
`
Output
GeeksforGeeks GeeksforGeeks
- The map.forEach method iterates through the map, with the second argument { name: "GeeksforGeeks" } being explicitly set as this inside the loop.
- For each item in the map, it prints "GeeksforGeeks" because this.name consistently refers to "GeeksforGeeks".
Output
GeeksforGeeks GeeksforGeeks
23 .How does "this" behave with async/await in JavaScript?
JavaScript `
const obj = { name: "GeeksforGeeks", async greet() { console.log(this.name); } }; obj.greet();
`
In this example, obj.greet() is an asynchronous function that logs this.name. Since this refers to the obj object, it prints "GeeksforGeeks", which is the value of obj.name.
24. What is the value of " this " in an event handler in a DOM element?
JavaScript `
const obj = { name : "GeeksforGeeks", greet() { document.getElementById("btn").addEventListener( "click", function() { console.log(this.name); // Output: undefined }); } }; obj.greet();
`
25. How does " this " work with new and constructor functions in JavaScript?
JavaScript ``
function Animal(name)
{
this.name = name;
this.speak = function() {
console.log(${this.name} makes a sound
);
};
}
const dog = new Animal("Dog");
dog.speak();
``
**In this code
- **Animal(name): This is a constructor function. It creates a new object with a name property and a speak method.
- **dog.speak(): After creating the dog object, we call the speak() method. It prints "Dog makes a sound", because the name property of dog is "Dog".