🔍 JavaScript Quirk: this behaves differently than you think This is one of the most confusing parts of JavaScript 👇 const user = { name: "Avinash", greet: function () { console.log(this.name); } }; user.greet(); // ? ✅ Output: "Avinash" Here, this refers to the object calling the function. Now look at this 👇 const greet = user.greet; greet(); // ? 💥 Output: undefined Why? Because this is no longer bound to user. In this case, this refers to the global object (or undefined in strict mode). Now the tricky part 👇 const user = { name: "Avinash", greet: () => { console.log(this.name); } }; user.greet(); // ? 💥 Output: undefined Why? Arrow functions don’t have their own this. They inherit it from their surrounding scope. 🚨 NEVER use this inside arrow functions for object methods. 💡 Takeaway: ✔ this depends on HOW a function is called ✔ Regular functions → dynamic this ✔ Arrow functions → lexical this ✔ Arrow + this in methods = bug waiting to happen 👉 Master this = fewer hidden bugs 🔁 Save this for later 💬 Comment "this" if it clicked ❤️ Like if this helped #javascript #frontend #webdevelopment #codingtips #js #developer
JavaScript this keyword quirks and best practices
More Relevant Posts
-
*🚀 JavaScript Hoisting* Hoisting is one of the most confusing but important concepts in JavaScript. 👉 Hoisting is JavaScript's behavior of moving declarations to top of their scope during execution. *🔹 1. What Gets Hoisted?* - var: Hoisted, initialized as undefined - let: Hoisted, not initialized (TDZ) - const: Hoisted, not initialized (TDZ) - function: Fully hoisted *🔹 2. Variable Hoisting (var)* console.log(x); var x = 5; 👉 Output: undefined 👉 Behind the scenes: var x; console.log(x); // undefined x = 5; *🔹 3. let & const Hoisting (TDZ)* console.log(a); let a = 10; 👉 Output: ReferenceError 👉 Why? Because of Temporal Dead Zone (TDZ) 👉 Variable exists but cannot be accessed before declaration *🔹 4. Function Hoisting* ✅ Function Declaration (Fully Hoisted) greet(); function greet(){ console.log("Hello"); } 👉 Works perfectly ❌ Function Expression (Not Fully Hoisted) greet(); var greet = function(){ console.log("Hello"); } 👉 Output: TypeError: greet is not a function *🔹 5. Temporal Dead Zone (TDZ)* 👉 Time between: Variable hoisted Variable declared During this time → ❌ cannot access variable { console.log(x); // ❌ Error let x = 5; } *🔹 6. Common Mistakes* ❌ Using variables before declaration ❌ Confusing var with let ❌ Assuming all functions behave the same *⭐ Most Important Points* ✅ var → hoisted with undefined ✅ let/const → hoisted but in TDZ ✅ Function declarations → fully hoisted ✅ Function expressions → not fully hoisted *🎯 Quick Summary* - JavaScript moves declarations up, not values - var → usable before declaration (but undefined) - let/const → cannot use before declaration - Functions → behave differently based on type *Double Tap ❤️ For More* #js #js #javascript #js #growaccout #growpage
To view or add a comment, sign in
-
🤯 One of the most confusing concepts in JavaScript — 'this' keyword If you've worked with JavaScript, you’ve probably asked: 👉 “What exactly does ‘this’ refer to?” Here’s the simple rule: 👉 “this = Who called me?” Let’s understand with examples 👇 📌 1. Object Method const user = { name: "Vinay", greet() { console.log(this.name); } }; user.greet(); // Vinay 👉 Here, 'this' refers to the user object 📌 2. Normal Function function show() { console.log(this); } show(); // window (in browser) 👉 Here, 'this' refers to the global object 📌 3. Arrow Function const obj = { name: "Vinay", greet: () => { console.log(this.name); } }; obj.greet(); // undefined 👉 Arrow functions don’t have their own 'this' 👉 They inherit it from the parent scope 📌 4. Event Listener button.addEventListener("click", function () { console.log(this); }); 👉 Here, 'this' refers to the clicked element 💥 Final Tip: 👉 “'this' is not about where it’s written, it’s about how it’s called.” Master this concept, and your JavaScript skills will level up 🚀 #JavaScript #WebDevelopment #Coding #DeveloperLife #Frontend #Programming #JSConcepts
To view or add a comment, sign in
-
-
🧠 JavaScript Scope & Lexical Scope Explained Simply Many JavaScript concepts like closures, hoisting, and this become much easier once you understand scope. Here’s a simple way to think about it 👇 🔹 What is Scope? Scope determines where variables are accessible in your code. There are mainly 3 types: • Global Scope • Function Scope • Block Scope (let, const) 🔹 Example let globalVar = "I am global"; function test() { let localVar = "I am local"; console.log(globalVar); // accessible } console.log(localVar); // ❌ error 🔹 What is Lexical Scope? Lexical scope means that scope is determined by where variables are written in the code, not how functions are called. Example 👇 function outer() { let name = "Frontend Dev"; function inner() { console.log(name); } inner(); } inner() can access name because it is defined inside outer(). 🔹 Why this matters Understanding scope helps you: ✅ avoid bugs ✅ understand closures ✅ write predictable code 💡 One thing I’ve learned: Most “confusing” JavaScript behavior becomes clear when you understand how scope works. Curious to hear from other developers 👇 Which JavaScript concept clicked for you only after learning scope? #javascript #frontenddevelopment #webdevelopment #reactjs #softwareengineering #developers
To view or add a comment, sign in
-
-
🧠 JavaScript Hoisting Explained Simply Hoisting is one of those JavaScript concepts that can feel confusing — especially when your code behaves unexpectedly. Here’s a simple way to understand it 👇 🔹 What is Hoisting? Hoisting means JavaScript moves declarations to the top of their scope before execution. But there’s a catch 👇 🔹 Example with var console.log(a); var a = 10; Output: undefined Why? Because JavaScript internally treats it like: var a; console.log(a); a = 10; 🔹 What about let and const? console.log(b); let b = 20; This throws a ReferenceError. Because "let" and "const" are hoisted too — but they stay in a “temporal dead zone” until initialized. 🔹 Function hoisting Functions are fully hoisted: sayHello(); function sayHello() { console.log("Hello"); } This works because the function is available before execution. 🔹 Key takeaway • "var" → hoisted with "undefined" • "let/const" → hoisted but not initialized • functions → fully hoisted 💡 One thing I’ve learned: Many “weird” JavaScript bugs come from not understanding hoisting properly. Curious to hear from other developers 👇 Did hoisting ever confuse you when you started learning JavaScript? #javascript #frontenddevelopment #webdevelopment #reactjs #softwareengineering #developers
To view or add a comment, sign in
-
-
🧠 Understanding the “this” Keyword in JavaScript (Simple Explanation) The this keyword is one of the most confusing parts of JavaScript. Early on, I used to assume this always refers to the current function — but that’s not actually true. 👉 The value of this depends on how a function is called, not where it is written. Let’s break it down 👇 🔹 1. Global Context console.log(this); In browsers, this refers to the window object. 🔹 2. Inside a Regular Function function show() { console.log(this); } Here, this depends on how the function is invoked. 🔹 3. Inside an Object Method const user = { name: "John", greet() { console.log(this.name); } }; user.greet(); // "John" Here, this refers to the object calling the method. 🔹 4. Arrow Functions Arrow functions do NOT have their own this. They inherit this from the surrounding (lexical) scope. 🔹 5. call, apply, bind These methods allow you to manually control what this refers to. 💡 One thing I’ve learned: Understanding this becomes much easier when you focus on how the function is called, not where it is defined. Curious to hear from other developers 👇 What part of JavaScript confused you the most when you were learning? #javascript #frontenddevelopment #webdevelopment #reactjs #softwareengineering #developers
To view or add a comment, sign in
-
-
💡 Understanding Closures in JavaScript (Simple & Clear) Closures are one of the most powerful concepts in JavaScript — and also one of the most confusing at first! 👉 A closure is created when a function remembers variables from its outer scope, even after the outer function has finished executing. 🔹 Example: function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); // 1 counter(); // 2 counter(); // 3 👉 Let’s break what’s really happening: • The outer() function runs and creates a variable count • It creates the inner() function • outer() returns inner() (not calling it, just returning it) ⚠️ Normally: When a function finishes execution, its variables are destroyed. ✅ But here: inner() is still using count 👉 So JavaScript keeps count in memory 👉 This preserved memory is called a closure 💡 Important insights: • Functions in JavaScript are first-class (can be returned and stored) • inner() runs later, not inside outer() • It keeps a reference to count, not a copy • That’s why the value updates (1 → 2 → 3) 🔥 Closure in Action (Tricky Example): for (var i = 1; i <= 3; i++) { setTimeout(function() { console.log(i); }, 1000); } 👉 Output: 4 4 4 ❓ Why? • var is function-scoped (only one shared variable i) • Loop finishes first → i becomes 4 • All callbacks use the same i ✅ Fix using let: for (let i = 1; i <= 3; i++) { setTimeout(function() { console.log(i); }, 1000); } 👉 Output: 1 2 3 ✔ Because: • let is block-scoped • Each iteration gets its own i • Each callback closes over a different variable ✅ Why closures are useful: • Data privacy (private variables) • Maintaining state • Used in callbacks and async programming 📌 One-line takeaway: A closure is a function that remembers its outer variables even after the outer function has finished execution. #JavaScript #WebDevelopment #Frontend #Coding #LearnToCode
To view or add a comment, sign in
-
-
🔍 JavaScript Behavior You Might Have Seen (Array methods: mutate vs not) You write this: const arr = [1, 2, 3]; const newArr = arr.push(4); console.log(arr); // ? console.log(newArr); // ? You expect: 👉 newArr to be a new array But you get: 👉 arr → [1, 2, 3, 4] 👉 newArr → 4 This happens because of mutating array methods 📌 What does “mutate” mean? 👉 It means changing the original array In this case: 👉 push() modifies arr directly 👉 And returns the new length (not a new array) Now look at this 👇 const arr = [1, 2, 3]; const newArr = arr.map(x => x * 2); console.log(arr); // ? console.log(newArr); // ? 👉 arr → [1, 2, 3] 👉 newArr → [2, 4, 6] This is a non-mutating method 👉 It creates a new array 👉 Original array stays unchanged 📌 Common mutating methods: ✔ push ✔ pop ✔ shift ✔ unshift ✔ splice ✔ sort ✔ reverse 📌 Common non-mutating methods: ✔ map ✔ filter ✔ slice ✔ concat ✔ reduce 📌 Real problem: You think you’re creating a new array… 👉 But you accidentally modify the original one 💡 Takeaway: ✔ Mutating methods change original array ✔ Non-mutating methods return a new array ✔ Always be careful when updating state (especially in React) 👉 One wrong method can break your logic silently 🔁 Save this for later 💬 Comment “array” if this made sense ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
🔍 JavaScript Quirk: Hoisting (var vs let vs const) JavaScript be like: 👉 “I know your variables… before you even write them” 😅 Let’s see the magic 👇 console.log(a); var a = 10; 💥 Output: undefined Wait… no error? 🤯 Why? Because `var` is **hoisted** 📌 What is Hoisting? Hoisting is JavaScript’s behavior of **moving variable and function declarations to the top of their scope before execution**. 👉 JS internally does this: var a; console.log(a); // undefined a = 10; So the variable exists… but has no value yet. Now try with `let` 👇 console.log(b); let b = 20; 💥 Output: ReferenceError ❌ Same with `const` 👇 console.log(c); const c = 30; 💥 Error again ❌ Why? Because `let` & `const` are also hoisted… BUT they live in something called: 👉 “Temporal Dead Zone” (TDZ) Translation: 🧠 “You can’t touch it before it’s declared” --- 💡 Simple Breakdown: ✔ `var` → hoisted + initialized as `undefined` ✔ `let` → hoisted but NOT initialized ✔ `const` → same as let (but must assign value) 💀 Real dev pain: Using `var`: 👉 “Why is this undefined?” Using `let`: 👉 “Why is this error?” JavaScript: 👉 “Figure it out yourself” 😎 💡 Takeaway: ✔ Avoid `var` (legacy behavior) ✔ Prefer `let` & `const` ✔ Understand hoisting = fewer bugs 👉 JS is not weird… You just need to know its secrets 😉 🔁 Save this before hoisting confuses you again 💬 Comment “TDZ” if this finally made sense ❤️ Like for more JS quirks #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
#js #14 **What is Function Hoisting?** 👉 Function hoisting means: JavaScript moves function declarations to the top of their scope during the memory phase 🔹 1. Function Declaration (Fully Hoisted) sayHello(); function sayHello() { console.log("Hello"); } ✅ Output: Hello 🤔 Why does this work? Because internally JavaScript treats it like: function sayHello() { console.log("Hello"); } sayHello(); 👉 The entire function (code + body) is hoisted ✔ You can call it before declaration 🔹 2. Function Expression (NOT fully hoisted) sayHi(); var sayHi = function() { console.log("Hi"); }; ❌ Output: TypeError: sayHi is not a function 🤔 Why? Internally: var sayHi = undefined; // hoisted sayHi(); // ❌ undefined() sayHi = function() { console.log("Hi"); }; 👉 Only the variable is hoisted, not the function 🔹 3. let / const Function Expression sayBye(); let sayBye = function() { console.log("Bye"); }; ❌ Output: ReferenceError 🤔 Why? Because of TDZ (Temporal Dead Zone) sayBye is hoisted But not initialized So you cannot access it before declaration 🧩 How it works internally (Memory Phase) Example: function a() {} var b = function() {}; let c = function() {}; 👉 Memory creation: a → full function stored ✅ b → undefined c → uninitialized (TDZ) 🧑🍳 Simple analogy Think of it like tools 🧰: Function Declaration 👉 Full tool ready before work starts Function Expression 👉 Only box is there, tool comes later let/const 👉 Box is locked (TDZ) until opened 🎯 Important Points Function declarations are fully hoisted Function expressions behave like variables var → undefined let/const → TDZ Only declarations (not assignments) are hoisted 🧾 Final Summary Function declaration → fully hoisted Function expression → partially hoisted let/const → TDZ applies 💡 One-line takeaway 👉Only function declarations are completely hoisted; function expressions follow variable hoisting rules #Javascript #ObjectOrientedProgramming #SoftwareDevelopment
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development