JavaScript 'this' Keyword Explained

🔥 Understanding this keyword in JavaScript The value of this depends on how a function is called, not where it is written. >> In the global scope console.log(this); this → refers to the global object (window in browsers) >> Inside an object method const user = { name: "Javascript", greet() { console.log(this.name); } }; user.greet(); // Javascript this → refers to the object calling the method ✔️ user.greet() → this is user >> In a regular function function show() {  console.log(this);} show(); this → undefined (in strict mode) or → global object (non-strict mode) >> In arrow functions const obj = {  name: "Javascript",  greet: () => {    console.log(this.name);}}; obj.greet(); // undefined this → does NOT have its own value It borrows from the surrounding scope 👉 That’s why arrow functions can surprise you! >> In event handlers button.addEventListener("click", function() {  console.log(this);}); this → refers to the element that triggered the event #JavaScript #FrontendDevelopment #WebDevelopment #Coding #LearnToCode

To view or add a comment, sign in

Explore content categories