So, "this" in JavaScript is a total wild card. You ask 10 devs, you get 10 different answers. It's a bug magnet, especially for those coming from other languages where "this" is straightforward. It's simple: "this" is all about how a function is called, not where it's defined. That's the root of most confusion. Now, let's break it down - there are four binding rules. Default binding: "this" goes global (or undefined in strict mode) when a function is called on its own. Implicit binding:this is the object before the dot when a function is called as a method. Explicit binding: you can setthis using call(), apply(), or bind(). And new binding: "this" is bound to the new object when you call a function with new. Arrow functions are different - they lexically bind "this" from their surrounding scope. So, losing "this" in callbacks is a common gotcha - just use arrow functions or bind(). In React, class components need binding in the constructor or arrow functions. But functional components with hooks? They avoid "this" altogether. The key takeaways: "this" depends on the function call, not definition. Arrow functions inherit "this" lexically. And in React, event handlers need binding because they're called as standalone functions. Check out this explanation for more: https://lnkd.in/gYxS529W #JavaScript #ThisKeyword #React
Understanding JavaScript's 'this' Keyword
More Relevant Posts
-
So, "this" in JavaScript is a total wild card. You ask 10 devs, you get 10 different answers. It's a bug magnet, especially for those coming from other languages where "this" is straightforward. It's simple: "this" is all about how a function is called, not where it's defined. That's the root of most confusion. Now, let's break it down - there are four binding rules. Default binding: "this" goes global (or undefined in strict mode) when a function is called on its own. Implicit binding:this is the object before the dot when a function is called as a method. Explicit binding: you can setthis using call(), apply(), or bind(). And new binding: "this" is bound to the new object when you call a function with new. Arrow functions are different - they lexically bind "this" from their surrounding scope. So, losing "this" in callbacks is a common gotcha - just use arrow functions or bind(). In React, class components need binding in the constructor or arrow functions. But functional components with hooks? They avoid "this" altogether. The key takeaways: "this" depends on the function call, not definition. Arrow functions inherit "this" lexically. And in React, event handlers need binding because they're called as standalone functions. Check out this explanation for more: https://lnkd.in/gYxS529W #JavaScript #ThisKeyword #React
To view or add a comment, sign in
-
𝗪𝗲𝗹𝗰𝗼𝗺𝗲 𝘁𝗼 𝗗𝗮𝘆 𝟴 Have you ever seen JavaScript behave correctly… but still give the wrong output? 🤔 𝘉𝘦𝘧𝘰𝘳𝘦 𝘴𝘤𝘳𝘰𝘭𝘭𝘪𝘯𝘨, 𝘨𝘶𝘦𝘴𝘴 𝘵𝘩𝘦 𝘰𝘶𝘵𝘱𝘶𝘵 𝘰𝘧 𝘵𝘩𝘪𝘴 𝘴𝘪𝘮𝘱𝘭𝘦 𝘤𝘰𝘥𝘦 𝚏𝚘𝚛 (𝚟𝚊𝚛 𝚒 = 𝟷; 𝚒 <= 𝟹; 𝚒++) { 𝚜𝚎𝚝𝚃𝚒𝚖𝚎𝚘𝚞𝚝(() => { 𝚌𝚘𝚗𝚜𝚘𝚕𝚎.𝚕𝚘𝚐(𝚒); }, 𝟷𝟶𝟶𝟶); } 𝗘𝘅𝗽𝗹𝗲𝗰𝘁𝗲𝗱 1, 2, 3 𝗔𝗰𝘁𝘂𝗮𝗹𝗹𝘆 𝗿𝗲𝘀𝘂𝗹𝘁 4,4,4 𝗧𝗵𝗶𝘀 𝗶𝘀 𝗮 𝗰𝗹𝗼𝘀𝘂𝗿𝗲 𝗯𝘂𝗴 — 𝗼𝗻𝗲 𝗼𝗳 𝘁𝗵𝗲 𝗺𝗼𝘀𝘁 𝗰𝗼𝗺𝗺𝗼𝗻 (𝗮𝗻𝗱 𝗰𝗼𝗻𝗳𝘂𝘀𝗶𝗻𝗴) 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗽𝗶𝘁𝗳𝗮𝗹𝗹𝘀. 𝗪𝗵𝘆 𝗧𝗵𝗶𝘀 𝗛𝗮𝗽𝗽𝗲𝗻𝘀 • var is function-scoped • setTimeout creates a closure • All callbacks reference the same variable i • When they execute, the loop has already finished Closures don’t capture values — they capture references. 𝗧𝗵𝗲 𝗙𝗶𝘅 𝚏𝚘𝚛 (𝚕𝚎𝚝 𝚒 = 𝟷; 𝚒 <= 𝟹; 𝚒++) { 𝚜𝚎𝚝𝚃𝚒𝚖𝚎𝚘𝚞𝚝(() => { 𝚌𝚘𝚗𝚜𝚘𝚕𝚎.𝚕𝚘𝚐(𝚒); }, 𝟷𝟶𝟶𝟶); } 𝗪𝗵𝘆 𝘁𝗵𝗶𝘀 𝘄𝗼𝗿𝗸𝘀: • let is block-scoped • Each iteration gets its own binding • Each closure remembers a different i 𝗬𝗼𝘂’𝗹𝗹 𝘀𝗲𝗲 𝘁𝗵𝗶𝘀 𝗽𝗮𝘁𝘁𝗲𝗿𝗻 𝗶𝗻: • Event handlers • Async loops • API callbacks • Timers • React effects If you don’t understand closures, You don’t see the bug — you just debug longer. #JavaScript #JSFundamentals #Closures #FrontendDevelopment #WebDevelopment #BugFixing #ReactJS #LearningInPublic
To view or add a comment, sign in
-
-
“JavaScript is easy.” Until this happens… 🤐 console.log(1 + "11") 👉 111 😵 Wait… what? Here’s what’s happening 👇 In JavaScript, the `+` operator does TWO jobs: ➕ Math addition ➕ String concatenation If one operand is a string, JavaScript silently converts the other one into a string too. So: 1 + "11" becomes "1" + "11" = "111" This is called **Type Coercion** (implicit conversion). 🔄 And that’s just the beginning… JavaScript also has something called - Truthy & Falsy values 👇 Falsy values (remember: FUNN0""): ❌ false ❌ undefined ❌ null ❌ NaN ❌ 0 ❌ "" (empty string) Everything else? ✅ Truthy. That’s why: if ("0") { console.log("Runs") } 👉 It runs 😅 Because "0" is a string — and it's truthy. JavaScript isn’t hard. But it’s full of silent behavior that can trick you. Have you ever been stuck because of type coercion? 👇 Comment your weirdest JS bug. #JavaScript #WebDev #Frontend #CodingTips #JSLearning
To view or add a comment, sign in
-
-
𝐮𝐧𝐝𝐞𝐟𝐢𝐧𝐞𝐝 𝐯𝐬. 𝐮𝐧𝐝𝐞𝐜𝐥𝐚𝐫𝐞𝐝 𝐯𝐬. 𝐮𝐧𝐢𝐧𝐢𝐭𝐢𝐚𝐥𝐢𝐳𝐞𝐝 (𝐚𝐤𝐚 𝐓𝐃𝐙) 𝐢𝐧 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 — 𝐞𝐯𝐞𝐫𝐲𝐭𝐡𝐢𝐧𝐠 𝐲𝐨𝐮 𝐧𝐞𝐞𝐝 𝐭𝐨 𝐤𝐧𝐨𝐰 • 𝐮𝐧𝐝𝐞𝐟𝐢𝐧𝐞𝐝 - Variable exists, but currently has no value - Common with declared variables that were never assigned • 𝐮𝐧𝐝𝐞𝐜𝐥𝐚𝐫𝐞𝐝 - Variable does not exist in any accessible scope - Accessing it throws an error - typeof is the only exception (returns "undefined") • Why this is confusing - JavaScript treats undeclared variables as "undefined" when using typeof - This is a historical design quirk • 𝐮𝐧𝐢𝐧𝐢𝐭𝐢𝐚𝐥𝐢𝐳𝐞𝐝 (𝐚𝐤𝐚 𝐓𝐃𝐙) - Introduced with let and const (ES6) - Variable exists, but cannot be accessed yet • TDZ is NOT undefined - Accessing a TDZ variable immediately throws an error - It is completely off-limits until initialized • Three kinds of “𝐞𝐦𝐩𝐭𝐢𝐧𝐞𝐬𝐬” in JavaScript – undeclared → never created – undefined → created, but no value – uninitialized (TDZ) → created, but inaccessible 𝐑𝐮𝐥𝐞: 👉 𝐓𝐡𝐞𝐬𝐞 𝐚𝐫𝐞 𝐍𝐎𝐓 𝐬𝐲𝐧𝐨𝐧𝐲𝐦𝐬 — 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐭𝐫𝐞𝐚𝐭𝐬 𝐭𝐡𝐞𝐦 𝐯𝐞𝐫𝐲 𝐝𝐢𝐟𝐟𝐞𝐫𝐞𝐧𝐭𝐥𝐲. Follow HAREESH BHITTAM for more JavaScript internals and edge cases. #JavaScript #Scopes #TDZ #Frontend #CleanCode #YouDontKnowJS
To view or add a comment, sign in
-
-
🚀 JavaScript Hoisting: A Practical Breakdown Hoisting describes how JavaScript processes declarations before code execution. What actually gets hoisted — and how — depends on the type of declaration, which is why different keywords behave differently. 🔹 Function Declarations Function declarations are fully hoisted, so they can be called before they appear in the code. greet(); // Works function greet() { console.log("Hello!"); } 🔹 var Variables var declarations are hoisted, but their values are not. Before assignment, the variable is undefined. console.log(count); // undefined var count = 3; 🔹 let Variables let is hoisted but placed in the Temporal Dead Zone (TDZ). Accessing it before declaration throws an error. console.log(total); // ReferenceError let total = 10; 🔹 const Variables const behaves like let in terms of hoisting and TDZ, but its value cannot be reassigned. console.log(rate); // ReferenceError const rate = 5; 🔹 Function Expressions & Arrow Functions These are hoisted only as variables, not as functions. sayHi(); // TypeError const sayHi = () => { console.log("Hi!"); }; #JavaScript #Hoisting #WebDevelopment #Frontend #CleanCode #Developers
To view or add a comment, sign in
-
🤔 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗤𝘂𝗶𝗿𝗸 𝗔𝗹𝗲𝗿𝘁: 𝗪𝗵𝘆 𝗱𝗼𝗲𝘀 𝘵𝘺𝘱𝘦𝘰𝘧 𝘯𝘶𝘭𝘭 === "𝘰𝘣𝘫𝘦𝘤𝘵"? Ever wondered why JavaScript thinks null is an object? It's not a feature—it's a bug from 1995 that we're stuck with forever! 𝗧𝗵𝗲 𝗢𝗿𝗶𝗴𝗶𝗻 𝗦𝘁𝗼𝗿𝘆: In JS v1, values had type tags. Objects got 000, and null (the NULL pointer) was all zeros. Boom—misidentified as an object. 𝗪𝗵𝘆 𝗖𝗮𝗻'𝘁 𝗪𝗲 𝗙𝗶𝘅 𝗜𝘁? 𝗦𝗶𝗺𝗽𝗹𝗲: backwards compatibility. In 2011, they tried fixing it by making 𝘵𝘺𝘱𝘦𝘰𝘧 𝘯𝘶𝘭𝘭 === "𝘯𝘶𝘭𝘭". 𝗥𝗲𝘀𝘂𝗹𝘁? Mass breakage across the web. 🔥 𝗠𝗶𝗹𝗹𝗶𝗼𝗻𝘀 𝗼𝗳 𝗰𝗼𝗱𝗲𝗯𝗮𝘀𝗲𝘀 𝗵𝗮𝘃𝗲: 𝘫𝘢𝘷𝘢𝘴𝘤𝘳𝘪𝘱𝘵𝘪𝘧 (𝘵𝘺𝘱𝘦𝘰𝘧 𝘷𝘢𝘭𝘶𝘦 === "𝘰𝘣𝘫𝘦𝘤𝘵" && 𝘷𝘢𝘭𝘶𝘦 !== 𝘯𝘶𝘭𝘭) { // 𝘩𝘢𝘯𝘥𝘭𝘦 𝘰𝘣𝘫𝘦𝘤𝘵𝘴 } Remove that && 𝘷𝘢𝘭𝘶𝘦 !== 𝘯𝘶𝘭𝘭 check, and chaos ensues. 𝗧𝗵𝗲 𝗟𝗲𝘀𝘀𝗼𝗻: Sometimes, the web's greatest strength (never breaking old sites) is also its biggest constraint. We live with legacy bugs because stability > theoretical perfection. What's your favorite JavaScript quirk? 👇 #JavaScript #WebDevelopment #Programming #DeveloperLife #TechTrivia #TechInnovation
To view or add a comment, sign in
-
-
🧩 JavaScript Output-Based Question (this + setTimeout) ❓ What will be the output? 👉 Comment your answer below (Don’t run the code ❌) Output: undefined 🧠 Why this output comes? (Step-by-Step) 1️⃣ print() is called as a method obj.print(); So inside print, this correctly refers to obj. 2️⃣ But inside setTimeout… setTimeout(function () { console.log(this.name); }, 0); The callback is a regular function, not a method of obj. When it executes: • this does NOT refer to obj • In non-strict mode → this points to the global object • In strict mode → this is undefined Either way: this.name → undefined 3️⃣ The key mistake ❌ Assuming this is preserved automatically in async callbacks 🔑 Key Takeaways ✔️ this depends on how a function is called ✔️ setTimeout callbacks lose object context ✔️ Use arrow functions or .bind() to fix this ✔️ This bug appears frequently in real projects #JavaScript #ThisKeyword #AsyncJavaScript #setTimeout #InterviewQuestions #FrontendDeveloper #MERNStack #ReactJS
To view or add a comment, sign in
-
-
The only JavaScript function that comes with a "Pause" button. ⏯️ In JavaScript, the golden rule of functions is usually "Run-to-Completion." Once a function starts, it doesn't stop until it returns or finishes. 𝐄𝐧𝐭𝐞𝐫 𝐭𝐡𝐞 𝐆𝐞𝐧𝐞𝐫𝐚𝐭𝐨𝐫 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧. 🤯 It completely breaks the rule. It is a special type of function that can be paused in the middle of execution and resumed later from exactly where it left off. 𝐓𝐡𝐞 𝐌𝐚𝐠𝐢𝐜 𝐒𝐲𝐧𝐭𝐚𝐱: 1️⃣ `function*`: The asterisk tells JS this isn't a normal function. 2️⃣ `yield`: This keyword acts like a pause button. It spits out a value and freezes the function's state. 3️⃣ `.next()`: This is the play button. Call it to resume the function until it hits the next `yield`. 𝐖𝐡𝐲 𝐢𝐬 𝐭𝐡𝐢𝐬 𝐮𝐬𝐞𝐟𝐮𝐥? (𝐋𝐚𝐳𝐲 𝐄𝐯𝐚𝐥𝐮𝐚𝐭𝐢𝐨𝐧) Generators allow for 𝐋𝐚𝐳𝐲 𝐄𝐯𝐚𝐥𝐮𝐚𝐭𝐢𝐨𝐧. You don't have to calculate a list of 1 million items at once (crashing your memory). You can generate them one by one, only when you actually need them. It’s perfect for infinite streams, ID generators, or defining complex state machines. Check out the syntax breakdown below! 👇 Have you used Generators in production (maybe with Redux Saga)? #JavaScript #WebDevelopment #CodingPatterns #AdvancedJS #SoftwareEngineering #Frontend
To view or add a comment, sign in
-
-
🧩 JavaScript Output-Based Question (`this` + setTimeout) ❓ What will be the output? 👉 Comment your answer below (Don’t run the code ❌) Output : undefined 🧠 Why this output comes? (Step-by-Step) 1️⃣ print() is called as a method obj.print(); So inside print, this correctly refers to obj. 2️⃣ But inside setTimeout… setTimeout(function () { console.log(this.name); }, 0); The callback is a regular function, not a method of obj. When it executes: • this does NOT refer to obj • In non-strict mode → this points to the global object • In strict mode → this is undefined Either way: this.name → undefined 3️⃣ The key mistake Assuming this is preserved automatically in async callbacks ❌ 🔑 Key Takeaways ✔️ this depends on how a function is called ✔️ setTimeout callbacks lose object context ✔️ Use arrow functions or bind to fix this ✔️ This bug appears frequently in real projects Async code doesn’t preserve this by default. How would you fix this so it prints "JS"? 👇 Drop your solution in comments #JavaScript #ThisKeyword #InterviewQuestions #FrontendDeveloper #MERNStack #WebDevelopment
To view or add a comment, sign in
-
-
🚀 5 Tricky JavaScript Output Questions (Closures & Scope) Let’s test your JS fundamentals 👇 Try to guess the output before checking answers. 1️⃣ for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } 2️⃣ let a = 10; (function () { console.log(a); let a = 20; })(); 3️⃣ function foo() { console.log(x); var x = 10; } foo(); 4️⃣ const obj = { a: 10, getA() { return this.a; } }; const fn = obj.getA; console.log(fn()); 5️⃣ console.log(typeof typeof 1); Answers below 👇 1️⃣ 3 3 3 (var is function-scoped, same reference) 2️⃣ ReferenceError (Temporal Dead Zone for `let`) 3️⃣ undefined (var hoisting without initialization) 4️⃣ undefined (`this` is lost when function is detached) 5️⃣ "string" (typeof 1 → "number", typeof "number" → "string") If you can explain *why*, you’re interview-ready 💯 #javascript #frontend #interviewprep #webdevelopment
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