Understanding JavaScript's 'this' Keyword

💡 JavaScript Concept Every Developer Should Understand — this One concept that often confuses beginners in JavaScript is the this keyword. A simple way to understand it is by remembering 4 basic rules. 🚀 The 4 Rules of this in JavaScript 1️⃣ Global Context Rule If this is used outside any function, it refers to the global object. In browsers, the global object is window. console.log(this); Output: Window {. . .} So here: this → window 2️⃣ Object Method Rule When a function is called using an object, this refers to that object. const person = { name: "Rahul", greet: function() { console.log(this.name); } }; person.greet(); Execution: person.greet() So: this → person Output: Rahul 3️⃣ Normal Function Rule If a function is called normally (not through an object), this refers to the global object (window) in browsers. function show() { console.log(this); } show(); Execution: show() So: this → window 4️⃣ Arrow Function Rule Arrow functions do not create their own this. They inherit this from the surrounding scope. const obj = { value: 10, show: function() { const arrow = () => { console.log(this.value); }; arrow(); } }; obj.show(); Here: this → obj Output: 10 🧠 Simple way to remember GLOBAL SCOPE │ ├── Normal function → this = window │ OBJECT METHOD │ ├── this = object │ ARROW FUNCTION │ └── this = inherited from parent #JavaScript #WebDevelopment #CodingConcepts #FrontendDevelopment #LearnToCode

To view or add a comment, sign in

Explore content categories