Follow-up to yesterday’s JavaScript `this` question 👇 Yesterday’s output was: 10 2 undefined undefined The issue was: • lost `this` context • accidental global variable usage So what if we want **ALL calls to always print 10**? Here’s a clean and correct solution 👇 Output: 10 10 10 10 🧠Why this works • We always access a through this.a • No accidental mutation of global variables • bind(obj) permanently fixes the context • call(obj) explicitly sets the correct context No matter how the function is invoked, this always points to obj. 🔑 Key Takeaway If a function depends on `this`, make the binding explicit. #JavaScript #ThisKeyword #CallBindApply #InterviewQuestions #FrontendDeveloper #MERNStack
JavaScript this Context Fix with Bind and Call
More Relevant Posts
-
JAVASCRIPT NOTES — PART 5 Some JavaScript bugs aren’t about logic — they’re about understanding how the language behaves internally. This post covers: • Stack vs Heap (how memory is handled) • Shallow vs Deep copy • The real behavior of the `this` keyword • Garbage collection basics • Debouncing & Throttling for UI performance These are the concepts that explain why code behaves the way it does. Once memory and execution flow are clear, JavaScript becomes far more predictable. #JavaScript #WebDevelopment #FrontendDeveloper #InterviewPrep #LearningInPublic #Debouncing #Prototypes #Consistency
To view or add a comment, sign in
-
🔄 Revising a Core JavaScript Concept: Type Coercion JavaScript has a unique behavior called type coercion — it automatically converts one data type into another during operations. Understanding this can save you from many hidden bugs. 👉 Quick examples: ✅ Number + String 1 + "2" → "12" (JavaScript converts the number to a string) ✅ String with math operator "5" - 2 → 3 (JavaScript converts the string to a number) ✅ Boolean conversion true + 1 → 2 false + 1 → 1 (true → 1, false → 0) ⚠ Equality surprise: 0 == false → true 0 === false → false 👉 “==” allows coercion 👉 “===” checks value + type (best practice) 💡 Pro tip: Prefer explicit conversion to avoid confusion: Number("5") → 5 String(10) → "10" Boolean(1) → true #JavaScript #TypeCoercion #WebDevelopment #Coding #Frontend #LearnToCode
To view or add a comment, sign in
-
🧠 𝐀 𝐎𝐧𝐞-𝐋𝐢𝐧𝐞 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐄𝐱𝐩𝐫𝐞𝐬𝐬𝐢𝐨𝐧 𝐓𝐡𝐚𝐭 𝐓𝐞𝐬𝐭𝐬 𝐘𝐨𝐮𝐫 𝐅𝐮𝐧𝐝𝐚𝐦𝐞𝐧𝐭𝐚𝐥𝐬 Take a look at the snippet in the image 👇 𝐖𝐡𝐚𝐭 𝐝𝐨 𝐲𝐨𝐮 𝐭𝐡𝐢𝐧𝐤 𝐭𝐡𝐞 𝐨𝐮𝐭𝐩𝐮𝐭 𝐢𝐬? A. true B. false C. TypeError D. JavaScript needs therapy 😆 Most people have an immediate answer in mind — and most of the time, it’s not correct. 👇 Drop your answer in the comment section Instead of dropping the explanation here, I’ve written a detailed article that breaks this down step by step: -> How JavaScript evaluates the expression -> How type coercion works under the hood -> How this relates to similar cases like [] + 1 and [] - 1 👉 If you’re curious about the why, check out the article here: https://lnkd.in/gTt-9Z6Y #javascript #javascriptfundamentals #webdev
To view or add a comment, sign in
-
-
🧩 JavaScript Output-Based Question (`this` + destructuring) ❓ What will be logged? 👉 Comment your answer below (Don’t run the code ❌) Correct Output : undefined 🧠 Why this output comes? (Step-by-Step) 1️⃣ Method works only when called on the object user.getName(); // "Jyoti" 2️⃣ Destructuring extracts the function, not the context const { getName } = user; Here, getName becomes a plain function reference. 3️⃣ Function is called without an object getName(); So: • this is lost • this → global object / undefined (strict mode) • this.name → undefined That’s why nothing is printed. 🔑 Key Takeaways ✔️ this depends on how a function is called ✔️ Destructuring methods breaks their context ✔️ Methods should be bound before destructuring if this is used Extracting a method ≠ calling it as a method #JavaScript #ThisKeyword #InterviewQuestions #FrontendDeveloper #MERNStack #WebDevelopment
To view or add a comment, sign in
-
-
JavaScript Output-Based Question What will be logged (line by line)? Comment your answer in order (Don’t run the code) Correct Output: 10 2 undefined undefined Why this output comes? (Step-by-Step) Global scope a = 5; Creates a global variable a.. obj.printA(); • Called as a method of obj • this → obj • this.a → 10 fn(); const fn = obj.printA; fn(); • Function is called without context • this → global object (non-strict mode) • a = 2 updates the global variable a • this.a → 2 obj.printA.call(this); • this explicitly set to global context • But this.a is not a property lookup here • Result → undefined obj.printA.bind(this)(); • bind permanently binds this to global • this.a still doesn’t exist as an object property • Result → undefined Key Takeaways ✔ this depends on how a function is called ✔ Variable assignment ≠ object property ✔ Extracting a method loses its context ✔ call sets this temporarily ✔ bind sets this permanently One wrong assumption about this can break production code. #JavaScript #ThisKeyword #CallBindApply #InterviewQuestions #FrontendDeveloper #MERNStack
To view or add a comment, sign in
-
-
Intercept, Control, Reflect: Power Tools Hidden in JavaScript 🪞 Learned about the Proxy pattern in JavaScript and how it works closely with the Reflect object. Explored how Proxies allow interception of operations like: -Property access -Assignment -Validation -Logging or access control And how Reflect provides a clean, predictable way to forward those operations while preserving default behavior. Key takeaway: Proxies are powerful but sharp tools. They enable elegant abstractions, yet can hurt readability and debugging if overused. Reflect helps keep proxy logic explicit and intention-revealing. Understanding these internals deepens how JS really works under the hood. #JavaScript #DesignPatterns #ProxyPattern #FrontendDevelopment #WebDevelopment #LearnInPublic
To view or add a comment, sign in
-
If 𝐡𝐨𝐢𝐬𝐭𝐢𝐧𝐠 still feels like “JavaScript moves code to the top,” your fundamentals need reinforcement. JavaScript never rearranges your code. What actually happens is simpler—and more powerful. Before execution, the engine creates memory. That’s where `var`, `let`, `const`, and function declarations are registered. Understanding this changes everything. During the **memory creation phase**: * `var` is hoisted and initialized with `undefined` * `let` and `const` are hoisted but placed in the **Temporal Dead Zone (TDZ)** * Function declarations are fully stored in memory Then comes the **execution phase**, where code runs line by line and values are assigned. That’s why this works: `console.log(a)` → `undefined` `var a = 10;` But this throws an error: `console.log(b)` → ReferenceError `let b = 10;` 𝐒𝐚𝐦𝐞 𝐡𝐨𝐢𝐬𝐭𝐢𝐧𝐠. 𝐃𝐢𝐟𝐟𝐞𝐫𝐞𝐧𝐭 𝐢𝐧𝐢𝐭𝐢𝐚𝐥𝐢𝐳𝐚𝐭𝐢𝐨𝐧 𝐫𝐮𝐥𝐞𝐬. In production, shallow understanding leads to undefined values, unpredictable refactors, and “JavaScript is weird” complaints. It’s not weird. It’s precise. Practical reminders: * Avoid `var` in modern codebases * Declare variables at the top of their scope intentionally * Understand TDZ before debugging scope-related errors Strong engineers don’t memorize slogans—they understand execution context. Can you clearly explain why `let` behaves differently from `var` without saying “it’s not hoisted”? #JavaScript #WebDevelopment #FrontendEngineering #CleanCode #ExecutionContext #SoftwareEngineering #ProgrammingFundamentals
To view or add a comment, sign in
-
-
🚨 JavaScript Truth Bomb: “Everything is an object”… so why does typeof fn say "function"? Quick reality check: functions are objects in JS. But typeof goes a step further. It checks if that object is callable. If yes, it returns "function" instead of "object". That’s not a bug, it’s intentional: 🔥 Early JS needed a simple way to detect callable values 🔥 So functions got a special typeof result 🔥 They still behave like objects with extra behavior 👉 Functions are objects with a [[Call]] method capability. What weird JavaScript behavior confused you the most? 👇 #JavaScript #Coding #DeveloperLife #WebDev
To view or add a comment, sign in
-
-
If you misunderstand `𝐯𝐚𝐫`, `𝐥𝐞𝐭`, 𝐚𝐧𝐝 `𝐜𝐨𝐧𝐬𝐭`, your bugs will multiply quietly. Master these three, and your JavaScript becomes predictable. I like to explain them with simple mental models. `𝐯𝐚𝐫` is like a basic box. You can put something in it, replace it, and even access it outside the block where it was created. It’s flexible—but that flexibility often creates confusion due to function scope and re-declarations. `𝐥𝐞𝐭` is a box with a protective boundary. You can change what’s inside, but only within its block scope. Step outside that boundary, and it no longer exists. This makes your code safer and more controlled. `𝐜𝐨𝐧𝐬𝐭` is a locked cage. You cannot reassign it to something else. However, if it holds an object or array, the contents can still change—because the reference is locked, not the internal data. Understanding this difference prevents scope leaks, accidental overwrites, and unpredictable behavior. Here’s a practical rule: * Use `𝐜𝐨𝐧𝐬𝐭` by default * Use `𝐥𝐞𝐭` when reassignment is necessary * Avoid `𝐯𝐚𝐫` in modern JavaScript Clean code starts with disciplined variable declarations. When reviewing your code, are you choosing the right “box” intentionally—or out of habit? #JavaScript #FrontendDevelopment #WebEngineering #CleanCode #ProgrammingFundamentals #SoftwareEngineering #CodeQuality
To view or add a comment, sign in
-
-
💡 Everything in JavaScript is an object (almost). ❓ Why is null also an object? When you check the type of null in JavaScript, you’ll see something strange: typeof null; // "object" 😵 But here’s the truth 👉 null is NOT actually an object. 🔹 So why does this happen? This is a historical bug from the early days of JavaScript. Internally, JavaScript used type tags to identify values, and null was given the same tag as objects. Once JavaScript became widely used, this mistake couldn’t be fixed—changing it would break millions of existing programs. 🔹 What is null really? null is a primitive value that means: “No value” “Intentionally empty” “Nothing here” It’s often used to reset variables or show that something is missing on purpose. ⚠️ Why this matters If you rely only on typeof, you can write buggy logic. if (typeof value === "object") { // This will also run for null ❌ } ✅ Best practice Always check for null explicitly: value === null; 💡 Takeaway null showing up as "object" is a JavaScript bug that became a feature. Knowing this helps you avoid confusing bugs and write safer code #learnwithisnaan #JavaScriptTips #ModernJavaScript #ES6 #DeveloperTips #CleanCode #JSDevelopers
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