What is “this” in JavaScript?

Sumit kumar Singh
3 min readMay 5, 2023

In JavaScript, the “this” keyword is a special reference that refers to the current execution context or the current object that the code is interacting with. The behavior of “this” can vary depending on how and where it is used within a function or method. Understanding “this” is crucial for writing effective and maintainable JavaScript code.

In this article, we will explore the various uses of “this” in JavaScript and provide examples to illustrate each scenario.

  1. Global Context: In the global context, “this” refers to the global object, which is “window” in web browsers and “global” in Node.js.

Example:

console.log(this === window); // true in browser environment 
console.log(this === global); // true in Node.js environment

2. Function Invocation: When a function is invoked, “this” is set to the global object if the function is called directly. However, if the function is called a method of an object, “this” refers to the object that the method is called on.

Example:

function greet() {
console.log(this);
}
greet(); // logs window object in browser environment

const person = {
name: "John",
greet: function() {
console.log(this);
}
}
person.greet(); // logs person object

--

--

Sumit kumar Singh

YouTube: https://www.youtube.com/@tech..Design/ 📚 HTML,Angular, React,and JavaScript 🧑‍💻 Tips & tricks on Web Developing 👉 FULL STACK DEVELOPER