The JavaScript "this" Trap 🪤🔥 The Puzzle: What is the output? 🤔 const obj = { name: "JS", getName() { console.log(this.name); } }; const fn = obj.getName; fn(); Output: undefined Why? 🧠 In JavaScript, this depends on HOW a function is called, not where it is written. Lost Context: const fn = obj.getName only copies the function reference. Standalone Call: When you call fn(), there is no object (no dot) before the function. Global Context: It now runs in the Global Context (window object). Since window.name is not "JS", it returns undefined. How to Fix? 🛠️ ✅ Use .bind(): const fn = obj.getName.bind(obj); ✅ Use .call(): fn.call(obj); ✅ Use Arrow Functions: They inherit this from the surrounding scope. Interview Tip: 💡 Always check the "Call Site." No dot before the function call (like fn()) usually means this is lost! #JavaScript #CodingTips #365DaysOfCode #InterviewPrep #WebDev #FullStack #mern #react #node
JavaScript 'this' Context Lost in Function Call
More Relevant Posts
-
🚀 Day 23 - Poll answer & Explanation 💡 **JavaScript Event Loop Explained (Simple & Clear)** ```javascript console.log('S'); Promise.resolve().then(() => console.log('P1')); setTimeout(() => console.log('T1'), 0); Promise.resolve().then(() => console.log('P2')); setTimeout(() => console.log('T2'), 0); console.log('E'); Output: S E P1 P2 T1 T2 ``` 🔹 **Explanation:** * `S` and `E` run first → synchronous code (call stack) * `P1`, `P2` → microtasks (Promises) → run next * `T1`, `T2` → macrotasks (setTimeout) → run last 👉 Microtasks always execute before macrotasks in the event loop. #JavaScript #ReactJS #WebDevelopment #Coding #FrontendDeveloper #InterviewPrep
To view or add a comment, sign in
-
From basic tags to advanced frameworks, here is the breakdown: ✅ Days 1-20: The Foundations (HTML/CSS) ✅ Days 20-40: The Engine (JavaScript/React) ✅ Days 40-70: Real-world Application & Design ✅ Days 80-100: Optimization & Polish Which stage do you find the most challenging? For me, it was definitely mastering Advanced JS! #TechCommunity #CodeNewbie #FrontendDeveloper #Roadmap
To view or add a comment, sign in
-
-
💡React Tip💡 Whenever you want to store an object in a state, use null as the initial value like this: const [user, setUser] = useState(null); instead of an empty object like this: const [user, setUser] = useState({ }); So if you want to check if user exist or if there are any properties present inside it, you can just use simple if condition like this: if(user) { // user exists, do something } or use JSX expression like this: { user && <p>User found</p>} However, If you use an empty object as the initial value, then you need to check like this: if(Object.keys(user).length === 0) { // user exists, do something } or use JSX expression like this: { Object.keys(user).length === 0 && <p>User found</p>} So assigning an initial value of null will make your code simpler and easier to understand. 𝗙𝗼𝗿 𝗺𝗼𝗿𝗲 𝘀𝘂𝗰𝗵 𝘂𝘀𝗲𝗳𝘂𝗹 𝗰𝗼𝗻𝘁𝗲𝗻𝘁, 𝗱𝗼𝗻'𝘁 𝗳𝗼𝗿𝗴𝗲𝘁 𝘁𝗼 𝗳𝗼𝗹𝗹𝗼𝘄 𝗺𝗲. #javascript #reactjs #nextjs #webdevelopment
To view or add a comment, sign in
-
If JavaScript is single‑threaded, how does it still handle Promises, API calls, and Timers without blocking the application? The answer lies in the Event Loop. Let’s take a simple example: What would be the output of the below code? console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); Some may guess the output to be: Start End Timeout Promise But the actual output is: Start End Promise Timeout So what is happening behind the scenes? 🔵 Synchronous Code Being synchronous, console.log("Start") and console.log("End") run immediately in the Call Stack. 🔵 Promises Resolved promises go to the Microtask Queue which is executed next. 🔵 setTimeout Timer callbacks go to the Macrotask Queue, even if the delay is '0ms', which is executed last. ✅ Simple flow to remember Synchronous Code → Promises (Microtasks) → setTimeout (Macrotasks) So even with 0 delay, Promises will always execute before setTimeout. Understanding this small but important detail will help developers debug async behavior and write more predictable JavaScript applications. #javascript #webdevelopment #eventloop #asyncprogramming
To view or add a comment, sign in
-
Question: What is the difference between var, let, and const in JavaScript? 💡 Answer: 1️⃣ var Function scoped Can be re-declared and updated Gets hoisted and initialized with undefined var a = 10 var a = 20 // allowed console.log(a) // 20 2️⃣ let Block scoped Can be updated but not re-declared in the same scope Hoisted but in Temporal Dead Zone (TDZ) let a = 10 a = 20 // allowed // let a = 30 ❌ Error 3️⃣ const Block scoped Cannot be updated or re-declared Must be initialized at declaration const a = 10 // a = 20 ❌ Error ⚡ Quick Summary FeaturevarletconstScopeFunctionBlockBlockRe-declare✅❌❌Update✅✅❌HoistingYesYes (TDZ)Yes (TDZ) 🎯 Interview Tip: Use const by default, let when value changes, and avoid var in modern JavaScript. 💬 Follow this series for daily JavaScript interview questions. #javascript #webdevelopment #frontend #mernstack #reactjs #codinginterview #softwareengineering
To view or add a comment, sign in
-
Today I learned about one of the most important concepts in JavaScript: The Event Loop. JavaScript is single-threaded, which means it can run only one task at a time. But it can still handle asynchronous operations like timers, API calls, and user events. This is possible because of the Event Loop. 💡 How it works: 1️⃣ Call Stack – Executes JavaScript code 2️⃣ Web APIs – Handles async tasks like setTimeout, fetch, DOM events 3️⃣ Callback Queue – Stores completed async callbacks 4️⃣ Event Loop – Moves tasks from the queue to the stack when it’s empty Example: console.log("Start"); setTimeout(() => { console.log("Timer"); }, 2000); console.log("End"); Output: Start End Timer The timer runs later because it goes through the Event Loop system. Understanding the event loop helps in writing better async JavaScript and debugging complex behavior. Day 5 of my 21 Days JavaScript Concept Challenge 🚀 #JavaScript #WebDevelopment #FrontendDeveloper #AsyncJavaScript #LearningInPublic
To view or add a comment, sign in
-
-
Javascript: Undefined vs null Ever seen undefined and null in JavaScript and felt confused? 🤔 You’re not alone. Many beginners mix them up. But the difference is actually very simple. Here’s the easy way to understand it: • undefined → A variable is declared but no value is assigned yet let name; console.log(name); // undefined • null → A developer intentionally sets an empty value let user = null; • undefined is automatic – JavaScript gives it by default. • null is intentional – The developer sets it manually. • Both mean “no value”, but the reason is different. Simple rule to remember: 👉 undefined = not assigned yet 👉 null = intentionally empty Understanding this small concept can help you avoid many bugs in JavaScript. #JavaScript #WebDevelopment #FrontendDevelopment #ProgrammingTips #LearnJavaScript #CodingForBeginners #SoftwareEngineering #TechEducation #JavaScriptDeveloper #DevCommunity
To view or add a comment, sign in
-
-
⏳ “JavaScript is single-threaded.” I used to hear this everywhere. But then I had one question: If JavaScript is single-threaded… How does async code work? That’s when I learned about the Event Loop. Here’s the simple idea 👇 🧠 JavaScript has: • Call Stack • Web APIs • Callback Queue • Event Loop When async code runs (like setTimeout or fetch): 1️⃣ It moves to Web APIs 2️⃣ Once completed, it goes to the Callback Queue 3️⃣ The Event Loop checks if the call stack is empty 4️⃣ Then pushes it back to execute That’s why: console.log(1) setTimeout(() => console.log(2), 0) console.log(3) Output is: 1 3 2 Understanding this made debugging async bugs much easier. Frameworks don’t hide this. They rely on it. #JavaScript #EventLoop #WebDevelopment #FrontendDeveloper #NodeJS #SheryiansCodingSchool
To view or add a comment, sign in
-
-
You say you’re “comfortable with JavaScript”? Cool. Let’s test that. Answer these in the comments 👇 🧠 1. What will this output? Why? 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨([] + []); 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨([] + {}); 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨({} + []); Most developers get at least one wrong. ⚡ 2. Predict the output: 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘰𝘶𝘵𝘦𝘳() { 𝘭𝘦𝘵 𝘤𝘰𝘶𝘯𝘵 = 0; 𝘳𝘦𝘵𝘶𝘳𝘯 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘪𝘯𝘯𝘦𝘳() { 𝘤𝘰𝘶𝘯𝘵++; 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨(𝘤𝘰𝘶𝘯𝘵); }; } 𝘤𝘰𝘯𝘴𝘵 𝘧𝘯 = 𝘰𝘶𝘵𝘦𝘳(); 𝘧𝘯(); 𝘧𝘯(); 𝘧𝘯(); What concept is this testing? 🔥 3. What’s the difference between these two? 𝘖𝘣𝘫𝘦𝘤𝘵.𝘧𝘳𝘦𝘦𝘻𝘦(𝘰𝘣𝘫); 𝘖𝘣𝘫𝘦𝘤𝘵.𝘴𝘦𝘢𝘭(𝘰𝘣𝘫); When would you use one over the other in production? 🧩 4. True or False? 𝘵𝘺𝘱𝘦𝘰𝘧 𝘯𝘶𝘭𝘭 === "𝘰𝘣𝘫𝘦𝘤𝘵" 𝘐𝘧 𝘵𝘳𝘶𝘦 — 𝘦𝘹𝘱𝘭𝘢𝘪𝘯 𝘸𝘩𝘺. 𝘐𝘧 𝘧𝘢𝘭𝘴𝘦 — 𝘦𝘹𝘱𝘭𝘢𝘪𝘯 𝘸𝘩𝘺. 🚀 5. Async trap — what happens here? 𝘢𝘴𝘺𝘯𝘤 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘵𝘦𝘴𝘵() { 𝘳𝘦𝘵𝘶𝘳𝘯 42; } 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨(𝘵𝘦𝘴𝘵()); What exactly gets logged? If you can answer all 5 confidently, you’re not just “using” JavaScript. You understand it. Drop your answers below 👇 Let’s see who’s interview-ready. #javascript #frontenddeveloper #codinginterview #webdevelopment #softwareengineering #DAY73
To view or add a comment, sign in
-
🧠 JavaScript Concept: Hoisting Explained Hoisting is JavaScript's behavior of moving variable and function declarations to the top of their scope before execution. This is why we can sometimes use variables or functions before they are declared. Example: console.log(name); // undefined var name = "Arun"; Why undefined? Because JavaScript internally treats it like this: var name; console.log(name); name = "Arun"; 🔹 Important Points: • "var" is hoisted and initialized with "undefined" • Function declarations are fully hoisted • "let" and "const" are hoisted but stay in the Temporal Dead Zone (TDZ) ⚠️ Accessing "let" or "const" before declaration will throw an error. 📌 Best Practice: Avoid relying on hoisting — always declare variables at the top for better readability. #javascript #frontenddevelopment #reactjs #webdevelopment #coding
To view or add a comment, sign in
-
Explore related topics
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