JS Coding Questions Logo
JS Coding Questions
#452💼 Interview💻 Code

What is the purpose of the this keyword in JavaScript?

Advertisement

728x90

The this keyword in JavaScript refers to the object that is executing the current function. Its value is determined by how a function is called, not where it is defined. this is essential for writing object-oriented and event-driven code, as it allows methods to interact with the data of the object they belong to.

Example 1: this in a Global Context

javascript
1console.log(this);

- In a global context, this refers to the global object (e.g., window in a browser).

Example 2: this in a Function

javascript
1function displayThis() {
2
3console.log(this);
4}
5
6displayThis();

- In a regular function, this refers to the global object(window in browser and global in nodejs) for non-strict mode. In strict mode, it's value is undefined.

Example 3: this in a Method

javascript
1const person = {
2
3name: "John",
4
5greet: function () {
6
7console.log("Hello, " + this.name);
8},
9};
10
11person.greet();

- In a method, this refers to the object that owns the method (person in the case).

Example 4: this in an Event Handler

javascript
1document.getElementById("myButton").addEventListener("click", function () {
2  console.log(this);
3   });

- In an event handler, this refers to the element that triggered the event (the button in this case).

Example 5: this with Arrow Functions

javascript
1const obj = {
2  age: 42,
3  regular: function() { console.log(this.age); },
4  arrow: () => { console.log(this.age); }
5  };
6  obj.regular(); // 42 (this refers to obj)
7  obj.arrow();   // undefined (this refers to the outer scope, not obj)

- Arrow functions do not have their own this binding; they inherit it from their surrounding (lexical) context.

Example 6: this in Constructor Functions / Classes

javascript
1function Person(name) {
2
3this.name = name;
4}
5
6const p1 = new Person('Sudheer');
7
8console.log(p1.name); // Sudheer

- When used with new, this refers to the newly created object.

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 23

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
452of476
What is the purpose of the this keyword in JavaScript? | JSCodingQuestions.com