Back to articles
Understanding the this Keyword in JavaScript

Understanding the this Keyword in JavaScript

via Dev.toSouvik Guha Roy

JavaScript has a special keyword called this that often confuses beginners. The key idea: this refers to the object that is “calling” the function. Let’s break it down with simple examples. 🧠 this in the Global Context In the global scope: ```js id="global1" console.log(this); * In a browser → points to `window` object * In Node.js → points to `global` object ```id="viz1" Global scope → this = window (browser) / global (Node) 🔹 this Inside Objects When a function is called as a method of an object , this points to that object. `` js id="obj1" const user = { name: "Rahul", greet: function() { console.log( Hello, ${this.name}`); } }; user.greet(); // Hello, Rahul * `this` refers to `user` because `user` is the **caller** of `greet()` --- ### 📊 Visual Representation ```id="viz2" user → greet() → this = user 🔹 this Inside Functions In a regular function : ```js id="func1" function sayHello() { console.log(this); } sayHello(); // Global object (window/global) * Here, `this` does **not** poi

Continue reading on Dev.to

Opens in a new tab

Read Full Article
3 views

Related Articles