JavaScript Interview Questions

23 Questions
JavaScript

JavaScript

Web DevelopmentFrontendBackend

Question 5

What is the 'this' keyword in JavaScript?

Answer:

The 'this' keyword in JavaScript refers to the object it belongs to. Its value depends on where it is used: in a method, it refers to the owner object; alone, it refers to the global object; in a function, it refers to the global object (in non-strict mode) or undefined (in strict mode); and in an event, it refers to the element that received the event. Understanding the behavior of 'this' is essential for writing object-oriented code and managing the context within functions.

Here is an example demonstrating the use of 'this':

var obj = {
    name: 'John',
    greet: function() {
        console.log('Hello, ' + this.name);
    }
};

obj.greet(); // 'Hello, John'

In this example, this.name refers to the name property of obj when greet is called as a method of obj.

Recent job openings