🧠 The "Tricky Question" We All Fall For: A Deeper Look at JS Closures Have you ever faced THAT question in a technical interview? 👨💻 You know the one—the loop, the var, and the setTimeout that just refuses to print what you expect. It feels like a rite of passage for every JavaScript developer. But here’s the real kicker: Why do we keep falling for it, even when we know the answer? 🧐 The Core of the Mystery 🔍 This simple loop cuts to the heart of several advanced JavaScript concepts that even senior devs debate: 1️⃣ Function Scope vs. Block Scope: We know var is function-scoped and let is block-scoped. But visualizing that distinction while a loop is racing through your mind is tough! Our brains want each iteration to have its own "memory" 🧠, but var just doesn't work that way. 2️⃣ The Power of Closures: This is the real star. The function inside setTimeout creates a closure over the variable i. It remembers i... but it remembers the one, final value because that’s where the var reference leads. 🔗 3️⃣ The Event Loop (Concurrency): Our intuition says the timer should log "right now." But the Event Loop dictates that the logs can only happen after the loop is completely finished. By then, i has already hit its final form: 3. 🛑 Why It’s Still Tricky (Even for Pros) 💡 Even after fixing it with let, the cognitive dissonance remains. Our brains prefer linear execution, but JavaScript’s model is more of a synchronized dance. 💃 The Challenge: Next time you see this, don’t just "fix" it. Reflect on why your initial instinct was wrong. It’s the best exercise for mastering closures and scoping. What is the classic JS question YOU still have to think twice about? Let’s unpack them in the comments! 👇 #JavaScript #WebDevelopment #CodingLife #SoftwareEngineering #FrontendDeveloper #ProgrammingTips #TechInterview #JSClosures #CodeNewbie #WebDevTips
JS Closures: Understanding Function Scope vs Block Scope
More Relevant Posts
-
Check out https://lnkd.in/duaEW9S8 — building a "simple" rectangle tool taught me that math edge cases are a total nightmare. As a Frontend Engineer working with TypeScript and React 19, I’ve learned that the simplest UI often hides the most complex logic. I used to think a rectangle was just length x width. Simple, right? 📐 Then I tried to allow users to calculate dimensions based on the diagonal and perimeter. Suddenly, I was deep in Pythagorean theorem edge cases and floating-point rounding errors. 💻 I actually tried using Cursor to generate the initial math functions for the diagonal logic. 🤖 It looked perfect until I realized it didn't handle the "impossible" input where the diagonal is shorter than a side. To fix this, I leaned heavily on Vitest to catch those sneaky mathematical impossibilities before they hit production. ✅ I built the interface with Tailwind CSS and Vite to keep the DX fast while managing state with clean TypeScript interfaces. 🛠️ It’s a reminder that even "basic" tools require a high bar for reliability when you're building for a global audience. 🚀 What's the most "basic" feature you've built that turned out to be surprisingly complex? 🧠 #RectangleCalculator #FrontendEngineer #TypeScript #ReactJS #Vite #Vitest #TailwindCSS #WebDev #CodingLife #SoftwareEngineering #CalculatorAll #MathTools #Geometry #TypeScriptDeveloper #FrontendDevelopment
To view or add a comment, sign in
-
-
🚨 JavaScript Brain Teasers That Will Mess With Your Mind. ❓ console.log(["A"] + ["B"]) 👉 Output: "AB" ❓ let arr1 = [1,2,3] let arr2 = [4,5,6] console.log(arr1 + arr2) 👉 Output: "1,2,34,5,6" ❓ console.log(+null) 👉 Output: 0 ❓ console.log(+"hello") 👉 Output: NaN ❓ let arr = [1,2,3] let str = "1,2,3" console.log(arr == str) 👉 Output: true ❓ console.log(10 == [10]) 👉 Output: true ❓ console.log(10 == [[[[10]]]]) 👉 Output: true ❓ var fruits = ["orange", "mango", "banana"] var fruitObj = { ...fruits } console.log(fruitObj) 👉 Output: {0: "orange", 1: "mango", 2: "banana"} ❓ console.log(null ?? true) 👉 Output: true ❓ console.log(undefined ?? true) 👉 Output: true 🔥 Takeaway: Most of this comes down to type coercion and how JS internally converts values. #JavaScript #WebDevelopment #Coding #Frontend #Programming #JavaScriptTips #JavaScriptTricks #JSConcepts #LearnJavaScript #FrontendDevelopment #FrontendDeveloper #WebDevCommunity #CodingTips #CodeNewbie #ProgrammingLife #DeveloperCommunity #DevLife #CodeChallenge #DailyCoding #CodeWithMe #TechContent #SoftwareDevelopment #FullStackDeveloper #JSDevelopers #ProgrammingTips #CodeDaily #DevTips
To view or add a comment, sign in
-
🚀 Day 2 / 21 — Frontend Challenge Today I built: 👉 Theme Toggle 🌙☀️ 🧠 Flow I designed before coding: Create basic UI with toggle button Add event listener on toggle click Switch between dark and light theme using class Change background and text color dynamically 🛠 Tech Used: HTML | CSS | JavaScript ✨ Features: Dark/Light mode toggle Background + text color both change dynamically 💡 Key Learning: Planning before coding makes development faster & cleaner. 🙏 Guidance by: @Keyur Gohil 🏫 Learning at: @Red & White Skill Education Official 📂 GitHub Repo: https://lnkd.in/gV5_mW2q #21DaysJSWithKeyur #RedandWhite #Skill #JavaScript #FrontendDevelopment #BuildInPublic #WebDevelopment
To view or add a comment, sign in
-
Day 2: The Secret Life of a Function Call — Global vs. Local Execution Context 🚀 Today, I went deeper into the "Big Box" of JavaScript to understand exactly what happens when we call a function. Using this simple square function as an example, here is the line-by-line magic: 🎭 The Two-Phase Performance Phase 1: Memory Allocation Before a single line of code runs, JavaScript scans everything. n, square2, and square4 are allocated memory and set to undefined. The square function gets its own memory space with the entire function code stored inside. Phase 2: Code Execution Line 1: n is assigned the value 2. Line 6: This is where it gets interesting! A Function Invocation happens. 📦 The "Mini Box": Functional Execution Context When square(n) is called, a New Execution Context is created inside the Global one! Memory Phase: A local variable ans is created (undefined). Code Phase: num becomes 2, ans becomes 4. The Return Statement: This is the exit signal. It returns the value 4 to square2 and destroys the local execution context immediately. 📚 The Call Stack: The Manager of it All How does JS keep track of these nested boxes? The Call Stack. It's a stack (LIFO - Last In, First Out). Bottom of stack: Global Execution Context (GEC). When a function is called, it's pushed onto the stack. When it returns, it's popped off. 💡 Interview Tip: Did you know the Call Stack has many names? It’s also called the Execution Context Stack, Program Stack, Control Stack, Runtime Stack, or Machine Stack. Understanding how the stack grows and shrinks is the key to mastering Recursion and avoiding the dreaded "Stack Overflow"! Drop a "🚀" if you’re also following the Namaste JavaScript series! #JavaScript #WebDevelopment #CallStack #ExecutionContext #ProgrammingLogic #FrontendEngineer #CodingCommunity #JSFundamentals
To view or add a comment, sign in
-
-
I did a deep dive 🔍 into JavaScript fundamentals and it reminded me why mastering the basics is non-negotiable in engineering. Here's what I explored: ▸ Variables & Hoisting — why let and const replaced var, and what the Temporal Dead Zone actually means ▸ Control Flow — from ternary operators to early return patterns that keep code clean ▸ Functions — closures, higher-order functions, and why JS treats functions as first-class citizens ▸ Arrays & Objects — the iteration methods (map, filter, reduce) every developer needs in their toolkit The more I revisit fundamentals, the more I realize how much of modern JavaScript is built on these exact concepts. Frameworks come and go — but a solid grasp of closures, scope, and data structures never goes out of style. Don't rush past the basics. They're the foundation everything else is built on. What JS concept took you the longest to truly "get"? Drop it in the comments 👇 #JavaScript #WebDevelopment #SoftwareEngineering #LearningInPublic #TechCareers
To view or add a comment, sign in
-
🔁 Understanding the forEach() loop in JavaScript The forEach() method is a simple way to iterate over arrays and perform an action for each element. 👉 Syntax: array.forEach((item, index) => { // logic here }); 👉 Example: const numbers = [1, 2, 3, 4]; numbers.forEach((num, index) => { console.log(`Index: ${index}, Value: ${num}`); }); 💡 Key Points: ✔️ Executes a function for each array element ✔️ Does not return a new array ✔️ Cannot break or use return to stop the loop If you need a return value, consider using map() instead. Small concepts like this build a strong JavaScript foundation 🚀 #JavaScript #WebDevelopment #Frontend #Coding #LearnToCode
To view or add a comment, sign in
-
🚀 Dynamic Currying in JavaScript — Why it actually matters At first, currying feels like a trick: sum(1)(2)(3) But the real power isn’t syntax — it’s reusability. 💡 The idea 👉 Fix some arguments now 👉 Reuse the function later 🔧 Example const filter = fn => arr => arr.filter(fn); const filterEven = filter(x => x % 2 === 0); filterEven([1,2,3,4]); // [2,4] Instead of repeating logic everywhere, you create reusable building blocks. ⚡ Real-world uses API helpers → request(baseUrl)(endpoint) Logging → logger("ERROR")(msg) Event handlers → handleClick(id)(event) Validation → minLength(8)(value) 🧠 Key takeaway Currying isn’t about fancy functions. It’s about writing code that is: ✔ Reusable ✔ Composable ✔ Cleaner Libraries like Lodash and Ramda use this pattern heavily. Once this clicks, your approach to writing functions changes completely. #JavaScript #WebDevelopment #FunctionalProgramming #Currying #CleanCode #Frontend #Coding #100DaysOfCode #DeveloperJourney #TechCommunity
To view or add a comment, sign in
-
-
🚀 JavaScript Last-Minute Cheat Sheet — Perfect Before Interviews & Coding Rounds 🔥 Variables & Scope • "let" & "const" over "var" • Block scope matters • Avoid global variables ⚡ Functions • Arrow functions → shorter syntax • Default parameters save time • Closures = function + lexical scope 🧠 Async JavaScript • Callbacks → Promises → "async/await" • Use "try...catch" for error handling • "Promise.all()" for parallel execution 📦 Arrays & Objects • "map()", "filter()", "reduce()" = must know • Spread "..." & Destructuring simplify code • Optional chaining "?." prevents crashes 🎯 DOM & Events • "querySelector()" is your best friend • Event delegation improves performance • Debounce & throttle for optimization 💡 Pro Tip Understand concepts, not just syntax. Clean code + problem-solving mindset = real JavaScript mastery. Learn more From w3schools.com ✨ #JavaScript #WebDevelopment #FrontendDeveloper #CodingInterview #100DaysOfCode
To view or add a comment, sign in
-
JavaScript: forEach() vs map() 🚀 A lot of developers confuse forEach() and map(), but they are not the same. Here’s the easy way to remember it: ✅ Use forEach() when you want to do something with each item • Logging data • Updating the UI • Calling an API • Running side effects It does not return a new array. ✅ Use map() when you want to transform each item • Changing values • Creating a new list • Rendering data in React It returns a new array. Simple rule: If you need a new array → use map() If you just need to loop through items → use forEach() Small choice, big impact on code clarity 💡 What do you use more often in your projects — forEach() or map()? 👇 #JavaScript #FrontendDevelopment #WebDevelopment #ReactJS #CodingTips #Programming #LearnJavaScript #100DaysOfCode #DevCommunity #SoftwareDevelopment #CodingLife #ReactDeveloper
To view or add a comment, sign in
-
-
🚨 𝗠𝗼𝘀𝘁 𝗱𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀 𝗴𝗲𝘁 𝘁𝗵𝗶𝘀 𝘄𝗿𝗼𝗻𝗴 👇 JavaScript variables look simple… Until they silently break your logic 😵 🧠 𝗧𝗿𝘆 𝘁𝗵𝗶𝘀: 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔(𝑎); 𝑣𝑎𝑟 𝑎 = 10; 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔(𝑏); 𝑙𝑒𝑡 𝑏 = 20; 𝗪𝗵𝗮𝘁 𝘄𝗶𝗹𝗹 𝗯𝗲 𝘁𝗵𝗲 𝗼𝘂𝘁𝗽𝘂𝘁? Take a guess before scrolling… 👇 . . . . . . ✅ 𝗔𝗻𝘀𝘄𝗲𝗿: undefined ReferenceError: Cannot access 'b' before initialization 💡 𝗦𝗶𝗺𝗽𝗹𝗲 𝗘𝘅𝗽𝗹𝗮𝗻𝗮𝘁𝗶𝗼𝗻 JavaScript behaves differently for var and let: 👉 var is hoisted and initialized with undefined 👉 let is also hoisted, BUT it stays in a “𝗧𝗲𝗺𝗽𝗼𝗿𝗮𝗹 𝗗𝗲𝗮𝗱 𝗭𝗼𝗻𝗲” until the line where it’s defined So: • a exists → prints undefined • b exists but is 𝗻𝗼𝘁 𝗮𝗰𝗰𝗲𝘀𝘀𝗶𝗯𝗹𝗲 𝘆𝗲𝘁 → throws error 🎯 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆𝘀 • var → function scoped + can lead to unexpected bugs • let → block scoped + safer to use • Always prefer let & const in modern JavaScript 🔥 𝗗𝗶𝗱 𝘆𝗼𝘂 𝗴𝗲𝘁 𝗶𝘁 𝗿𝗶𝗴𝗵𝘁? Be honest 😄 💬 Comment your answer before you saw the solution 🔖 Save this for interview prep 💡 Part of my #FrontendRevisionMarathon — breaking down Frontend concepts daily 🚀 🚀 Follow Shubham Kumar Raj for more such content. #javascript #frontenddeveloper #codinginterview #webdevelopment #learnjavascript #100daysofcode #programming #interviewprep #CareerGrowth #SowftwareEngineering
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