🤔 Wait… shouldn’t variables be deleted? How is it possible that a function still remembers a variable…even after the function where it was created has already finished executing? 😳 👉 Sounds impossible, right? 🚀 JavaScript’s one of the most powerful concepts: Closures 🧠 What is a Closure? A closure is created when a function is defined inside another function, and the inner function can access variables from its parent scope — even after the parent function has finished execution. ⚡Shouldn’t variables be deleted? Normally, yes ✅ 👉 Once a function finishes, its local variables are removed from memory (thanks to garbage collection) But closures change the game 👇 👉 If an inner function is still using those variables, JavaScript keeps them alive in memory 🔍 What’s really happening? The inner function “closes over” its parent’s variables 💡 That’s why it’s called a closure Even though the outer function is done… the inner function still has access to its scope 😮 🔐 Why Closures Matter (Real Use Cases) Closures aren’t just theory — they’re used everywhere: 👉 Encapsulation (Private Variables) Keep data hidden from global scope 👉 Debouncing & Throttling Control function execution (very common in React apps) 👉 State management patterns Maintain data across function calls 💡 Real Developer Insight Closures are powerful… but can be tricky 👉They can also hold memory longer than expected 👉 Misuse can lead to memory leaks 🚀 Final Thought: Most developers use closures unknowingly… But great developers understand how and why they work. #JavaScript #FrontendDevelopment #WebDevelopment #Closures #CodingTips #LearnJavaScript #BuildInPublic #100DaysOfCode #LearnInPublic
JavaScript Closures Explained
More Relevant Posts
-
JavaScript is easy. Until it isn't. 😅 Every developer has been there. You're confident. Your code looks clean. You hit run. And then: " Cannot read properties of undefined (reading 'map') " The classic JavaScript wall. Here are 7 JavaScript mistakes I see developers make constantly and how to fix them: 1. Not understanding async/await ⚡ → Wrong: | const data = fetch('https://lnkd.in/dMDBzbsK'); console.log(data); // Promise {pending} | → Right: | const data = await fetch('https://lnkd.in/dMDBzbsK'); | 2. Using var instead of let/const → var is function scoped and causes weird bugs → Always use const by default. let when you need to reassign. Never var. 3. == instead of === → 0 == "0" is true in JavaScript 😱 → Always use === for comparisons. Always. 4. Mutating state directly in React → Wrong: user.name = "Shoaib" → Right: setUser({...user, name: "Shoaib"}) 5. Forgetting to handle errors in async functions → Always wrap await calls in try/catch → Silent failures are the hardest bugs to track down 6. Not cleaning up useEffect in React → Memory leaks are real → Always return a cleanup function when subscribing to events 7. Treating arrays and objects as primitives → [] === [] is false in JavaScript → Reference types don't compare like numbers — learn this early JavaScript rewards the developers who understand its quirks. 💡 Which of these caught YOU off guard when you first learned it? 👇 #JavaScript #WebDevelopment #Frontend #FullStackDeveloper #React #Programming #CodingTips #Developer #Tech #Pakistan #LearnToCode #JS #SoftwareEngineering #100DaysOfCode #PakistaniDeveloper
To view or add a comment, sign in
-
-
🧠 Day 26 — Rest vs Spread Operator in JavaScript (Simplified) Both use ... — but they do very different things 👀 --- 🔍 The Idea 👉 Spread → Expands values 👉 Rest → Collects values --- ⚡ 1. Spread Operator ... 👉 Expands elements const arr = [1, 2, 3]; const newArr = [...arr, 4]; console.log(newArr); // [1, 2, 3, 4] 👉 Also used in objects const user = { name: "John" }; const newUser = { ...user, age: 25 }; --- ⚡ 2. Rest Operator ... 👉 Collects remaining values function sum(...nums) { return nums.reduce((a, b) => a + b, 0); } sum(1, 2, 3); // 6 --- 🧠 Key Difference Spread → Expands data Rest → Gathers data --- ⚠️ Important Rule 👉 Rest must be last parameter function test(a, ...rest) {} // ✅ --- 🚀 Why it matters ✔ Cleaner code ✔ Flexible functions ✔ Used heavily in React & modern JS --- 💡 One-line takeaway: 👉 “Spread expands, Rest collects.” --- Once you understand this, working with arrays & functions becomes much easier. #JavaScript #ES6 #SpreadOperator #RestOperator #WebDevelopment #Frontend #100DaysOfCode 🚀
To view or add a comment, sign in
-
JavaScript isn’t asynchronous… the environment is. After diving deep into asynchronous JavaScript, I realized something that completely changed how I think about writing code: We don’t “wait” for data… we design what happens when it arrives. 💡 Most developers use fetch and Promises daily, but very few truly understand what happens under the hood. Here’s the real mental model: 🔹 JavaScript is single-threaded 🔹 Heavy operations (API calls, timers) are offloaded to Web APIs 🔹 fetch() returns a Promise immediately (not the data!) 🔹 .then() doesn’t execute your function… it registers it for later 🔥 The game changer? There are actually two queues, not one: Microtask Queue (Promises) → HIGH PRIORITY Callback Queue (setTimeout, etc.) And the Event Loop always prioritizes microtasks. 💥 Example: console.log("1"); setTimeout(() => console.log("2"), 0); Promise.resolve().then(() => console.log("3")); console.log("4"); 👉 Output: 1 . 4 . 3 . 2 🧠 Why this matters: Explains unexpected execution order Makes debugging async code 10x easier Helps avoid common interview pitfalls Builds a strong foundation for React & modern frontend ⚡ Key Insight: Promises are not about cleaner syntax… They are about controlling time and execution order in a non-blocking environment. 📌 Once you truly understand: Event Loop Microtask vs Callback Queue Promise lifecycle You stop guessing… and start predicting behavior. #JavaScript #Frontend #WebDevelopment #AsyncJS #Promises #EventLoop #React #Programming
To view or add a comment, sign in
-
-
Most JavaScript bugs aren’t caused by complex logic. They come from choosing the wrong array method. The difference between find() and filter(), map() and forEach(), or some() and every() looks small—until it reaches production. That’s where performance, readability, and hidden bugs start to matter. Examples: filter()[0] instead of find() → unnecessary full array scan Using forEach() when map() should return transformed data → broken data pipelines Calling sort() directly in React state → silent mutation bugs Using filter().length > 0 instead of some() → extra work for no reason Overusing reduce() for simple logic → clever code, poor readability Great developers don’t just know array methods. They know: ✔ When to use them ✔ When not to use them ✔ Their performance cost ✔ Their side effects ✔ Their production impact Simple rule: Code should not only work. It should be readable, predictable, and efficient. Because in real applications, small method choices create big system behavior. The engineers I respect most don’t use reduce() to look smart. They use find() instead of filter()[0]. They spread before sort(). They know forEach() returns nothing. That’s the difference between writing JavaScript and engineering with JavaScript. #JavaScript #FrontendDevelopment #WebDevelopment #ReactJS #SoftwareEngineering #Programming #CodeQuality #TechLeadership
To view or add a comment, sign in
-
-
How I Understood Memory Leak in JavaScript One day I wrote this small code: let user = { name: "Siddharth" }; let map = new Map(); map.set(user, "Developer"); user = null; console.log(map); And I thought: 👉 “I removed the user… so memory should be free now.” But I was wrong. 🧠 What actually happened? Even after: user = null; The object was still in memory. Why? Because Map was still holding a reference to it. 👉 JavaScript says: “As long as something is pointing to this object, I won’t delete it.” That’s called a memory leak. 💡 Human way to understand this Imagine: You throw something in the dustbin 🗑️ But someone secretly keeps a copy of it. So it’s not really gone. That’s exactly what Map does here. ⚠️ The problem If this keeps happening in a real app: • Memory keeps increasing 📈 • App becomes slow 🐢 • Eventually crashes 💥 ✅ The fix (cleanup) let user = { name: "Siddharth" }; let map = new Map(); map.set(user, "Developer"); user = null; // Cleanup map.clear(); console.log(map); // Map(0) {} Now: 👉 No reference → memory gets freed 🚀 The lesson I learned 📌 Memory leaks happen when references are not removed 📌 Map keeps strong references 📌 Always clean up unused data Now whenever I use Map, I ask: 👉 Am I removing things I no longer need? Still learning JavaScript the human way. 🚀 #JavaScript #MemoryLeak #WebDevelopment #LearningInPublic #CleanCode #ReactJS #FrontendDevelopment #DeveloperJourney #Performance
To view or add a comment, sign in
-
-
Why is my code running "out of order"? (Eager vs. Lazy Evaluation) Ever passed a function as an argument and wondered why it executed before the function it was passed into? Look at this common "gotcha": javascript const main = (fn) => { console.log("start"); fn(); console.log("end"); }; const createLogger = (msg) => { console.log("start logger"); return () => console.log(msg); }; // ❌ Unexpected Order: "start logger" -> "start" -> "success" -> "end" main(createLogger("success")); Use code with caution. What’s happening? This is Eager Evaluation. In JavaScript, arguments are evaluated immediately before the outer function runs. Because we used parentheses () on createLogger, JS executes it first to find out what value to give to main. It’s like cooking a 5-course meal before your guests even knock on the door! 🥘 The Fix: Lazy Evaluation 💤 If we want main to control the timing, we need to wrap our logic in a "thunk" (a wrapper function). This tells JS: "Don't run this yet; run it only when I call it." javascript // ✅ Correct Order: "start" -> "start logger" -> "success" -> "end" main(() => createLogger("success")()); Use code with caution. Why does this matter in Node.js? Understanding this distinction is huge for: ✅ Middleware: Deciding when a request starts/ends. ✅ Performance: Avoiding expensive calculations unless they are actually needed. ✅ Closures: Controlling scope and execution timing. Stop executing, start referencing! 🚀 #JavaScript #WebDevelopment #NodeJS #CodingTips #SoftwareEngineering
To view or add a comment, sign in
-
-
For years, sorting an array in JavaScript has been a source of subtle bugs. The `.sort()` method, while functional, mutates the original array in place. This often leads developers to create a copy first, usually with the spread operator `[...]`, before sorting. This "copy-then-sort" pattern is verbose and easily forgotten, especially in complex applications where arrays are passed around. If you forget the copy, you inadvertently modify data in other parts of your program, leading to hard-to-trace bugs and unexpected side effects that can really tank your productivity. Enter `Array.toSorted()`. This modern, immutable alternative returns a new sorted array without touching the original. It's cleaner, safer, and exactly what developers have needed for handling data integrity. It prevents accidental data corruption and makes your code much more predictable. Are you still writing it the old way? #javascript #webdevelopment #frontend #cleancode #js
To view or add a comment, sign in
-
-
🚨 JavaScript Gotcha: Objects as Keys?! Take a look at this 👇 const a = {}; const b = { key: 'b' }; const c = { key: 'c' }; a[b] = 123; a[c] = 456; console.log(a[b]); // ❓ 👉 What would you expect? 123 or 456? 💡 Actual Output: 456 🤯 Why does this happen? In JavaScript, object keys are always strings or symbols. So when you use an object as a key: a[b] → a["[object Object]"] a[c] → a["[object Object]"] Both b and c are converted into the same string: "[object Object]" ⚠️ That means: a[b] = 123 sets " [object Object] " → 123 a[c] = 456 overwrites it → 456 So finally: console.log(a[b]); // 456 🧠 Key Takeaways ✅ JavaScript implicitly stringifies object keys ✅ Different objects can collide into the same key ❌ Using objects as keys in plain objects is unsafe 🔥 Pro Tip If you want to use objects as keys, use a Map instead: const map = new Map(); map.set(b, 123); map.set(c, 456); console.log(map.get(b)); // 123 ✅ ✔️ Map preserves object identity ✔️ No unexpected overwrites 💬 Final Thought JavaScript often hides complexity behind simplicity. Understanding these small quirks is what separates a developer from an expert. #JavaScript #WebDevelopment #FrontendDevelopment #Programming #Coding #JavaScriptTips #JSConfusingParts #DevelopersLife #CodeNewbie #LearnToCode #SoftwareEngineering #TechTips #CodeQuality #CleanCode #100DaysOfCode #ProgrammingTips #DevCommunity #CodeChallenge #Debugging #JavaScriptDeveloper #MERNStack #FullStackDeveloper #ReactJS #NodeJS #WebDevTips #CodingLife
To view or add a comment, sign in
-
-
😵💫𝗢𝗻𝗲 𝗼𝗳 𝘁𝗵𝗲 𝗺𝗼𝘀𝘁 𝗰𝗼𝗻𝗳𝘂𝘀𝗶𝗻𝗴 𝘁𝗵𝗶𝗻𝗴𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: `...` At first glance, it looks simple. But depending on where you use it, it completely changes its role. Same syntax. Different behavior. That’s where most developers get tripped up. So I decided to break it down clearly: ✍️ New Blog Published: 𝗦𝗽𝗿𝗲𝗮𝗱 𝘃𝘀 𝗥𝗲𝘀𝘁 𝗢𝗽𝗲𝗿𝗮𝘁𝗼𝗿𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: 𝗘𝘅𝗽𝗮𝗻𝗱 𝗼𝗿 𝗖𝗼𝗹𝗹𝗲𝗰𝘁 𝗟𝗶𝗸𝗲 𝗮 𝗣𝗿𝗼 https://lnkd.in/gFPgrdEv 🔍 What you’ll learn: 🔹 When ... acts as a Spread Operator (expanding data) 🔹 When it becomes a Rest Operator (collecting data) 🔹 Real-world use cases to eliminate confusion Hitesh Choudhary Piyush Garg Chai Aur Code Anirudh J. Akash Kadlag Suraj Kumar Jha Nikhil Rathore Jay Kadlag DEV Community #JavaScript #WebDevelopment #TechnicalWriting #LearningInPublic #Chaicode #Cohort
To view or add a comment, sign in
-
🚀 𝐃𝐚𝐲 6 – 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐄𝐯𝐞𝐧𝐭 𝐋𝐨𝐨𝐩 (𝐒𝐢𝐦𝐩𝐥𝐞 & 𝐂𝐥𝐞𝐚𝐫) JavaScript is single-threaded… 👉 But then how does it handle things like `setTimeout`? 🤔 Let’s understand the real flow 👇 --- 💡 The Setup JavaScript uses: * Call Stack → runs code * Web APIs → handles async tasks * Callback Queue → waits for execution * Event Loop → manages everything --- 💡Example: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); console.log("End"); --- 💡 Output: Start End Timeout --- 💡 Why? (Step-by-step) * `Start` → runs immediately * `setTimeout` → sent to Web APIs * `End` → runs immediately * Timer completes → callback goes to Queue * Event Loop checks → Stack empty * Callback pushed to Stack → executes --- ⚡ Key Insight 👉 Even with `0ms`, it does NOT run immediately 👉 It waits until the Call Stack is empty --- 💡 Simple Mental Model 👉 “Async code runs after sync code finishes” --- 💡 Why this matters? Because it explains: * execution order * async behavior * common bugs --- 👨💻 Continuing my JavaScript fundamentals series 👉 Next: **Promises (Async Made Better)** 👀 #JavaScript #WebDevelopment #FrontendDevelopment #Coding #SoftwareEngineer #Tech
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