Day 2/100 – Understanding Closures in JavaScript Today I explored Closures — one of the most important concepts in JavaScript that directly impacts how modern frameworks like React work internally. ✅ What is a Closure? A closure is created when a function retains access to variables from its lexical scope, even after the outer function has finished execution. In simple terms: A function remembers the environment in which it was created. ✅ Why is it important in real-world applications? Closures are widely used in: • React hooks • Event handlers • Data encapsulation • Memoization • Maintaining private variables • Custom hook patterns A solid understanding of closures makes debugging and optimizing React applications much easier. 💻 Example: function createCounter() { let count = 0; return function () { count++; console.log(count); }; } const counter = createCounter(); counter(); // 1 counter(); // 2 Even after createCounter() has executed, the inner function still has access to “count”. That’s the power of closures. 📌 Key Takeaway: Closures are not just an interview topic — they are fundamental to writing predictable and maintainable JavaScript in production applications. #100DaysOfCode #JavaScript #ReactJS #FrontendDevelopment
Understanding Closures in JavaScript: Key to React Frameworks
More Relevant Posts
-
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
-
-
Today I explored one of the most confusing but fascinating concepts in JavaScript — The Event Loop. JavaScript is single-threaded, but it still handles asynchronous tasks like API calls, timers, and promises smoothly. The magic behind this is the Event Loop. Here’s the simple flow: 1️⃣ Call Stack – Executes synchronous code 2️⃣ Web APIs – Handles async tasks (setTimeout, fetch, DOM events) 3️⃣ Callback Queue / Microtask Queue – Stores callbacks waiting to execute 4️⃣ Event Loop – Moves tasks to the call stack when it’s empty 💡 Example: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); 🧠 Output: Start End Promise Timeout Why? Because Promises go to the Microtask Queue which runs before the Callback Queue. ✨ Learning this helped me finally understand how JavaScript manages async behavior without multi-threading. Tomorrow I plan to explore another interesting JavaScript concept! Devendra Dhote Ritik Rajput #javascript #webdevelopment #frontenddeveloper #100DaysOfCode #learninginpublic #codingjourney #sheryianscodingschool
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
-
🚀 JavaScript is finally addressing a 30-year-old problem. For decades, JavaScript’s Date object has been one of its most confusing and error-prone features. I’ve personally faced these issues multiple times while working with dates in JS: 👉 Same date string behaving differently across browsers 👉 Timezone bugs that only show up in production 👉 Unexpected mutations breaking logic 👉 And yes… months starting from 0 😅 💡 Introducing: Temporal API JavaScript is moving towards a modern date/time system designed to solve these long-standing issues. ✨ What makes Temporal better? ✔️ Immutable by default (no more accidental changes) ✔️ Clear separation of concerns (Date, Time, Timezone handled properly) ✔️ Consistent parsing across environments ✔️ First-class timezone support 🌍 ✔️ Cleaner and more readable date operations Example: Instead of: new Date() (unpredictable, mutable) We now have: Temporal.PlainDate, Temporal.PlainTime, Temporal.ZonedDateTime, and more — each with a clear purpose. 📌 Why this matters: Date bugs are among the hardest to detect and debug in real-world applications. While this is already improving things in some cases, it’s still evolving and not fully resolved everywhere yet — hoping to see complete adoption soon. 💬 Have you encountered challenges while working with dates in JavaScript? #JavaScript #WebDevelopment #Frontend #Programming #SoftwareEngineering #TemporalAPI
To view or add a comment, sign in
-
Hoisting in JavaScript (and TypeScript) - Explained So You’ll Never Forget Ever saw this weird behavior? console.log(a); // undefined var a = 10; OR even worse: sayHello(); // Works! function sayHello() { console.log("Hello!"); } How is JavaScript using things before they are declared? 👉 That’s called Hoisting 🏠 Real-Life Example: Hotel Reception Imagine you walk into a hotel… "var" — Pre-registered Guest 📝 Your name is already in the system, but your room is not ready yet. 👉 You exist… but not fully ready 👉 So you get "undefined" "let" / "const" — Walk-in Guest 🚶♂️ You are NOT in the system yet. 👉 Try to access before check-in? ❌ “Sir, you are not registered!” (This is called Temporal Dead Zone) "function" — VIP Guest ⭐ Your room is already booked and ready! 👉 You can directly go in 👉 That’s why functions work before declaration Behind the scenes (Simple terms): JavaScript does 2 steps: 1️⃣ Memory Allocation Phase → Variables & functions are stored 2️⃣ Execution Phase → Code runs line by line Key Takeaways: ✔ "var" is hoisted (initialized as "undefined") ✔ "let" & "const" are hoisted but NOT initialized ✔ Functions are fully hoisted Pro Tip: Avoid confusion → Always declare variables at the top (or just use "let" / "const" properly) 💬 Have you ever faced a bug because of hoisting? #JavaScript #TypeScript #WebDevelopment #Frontend #Coding #LearnToCode
To view or add a comment, sign in
-
-
💡 Understanding Scope in JavaScript One of the most important concepts in JavaScript is Scope. Scope defines where variables can be accessed in your code. There are three main types of scope in JavaScript: 🔹 Global Scope Variables declared outside any function are accessible anywhere in the program. let name = "Muneeb"; function showName() { console.log(name); } showName(); // Accessible because it's global 🔹 Function Scope Variables declared inside a function can only be used inside that function. function greet() { let message = "Hello"; console.log(message); } greet(); // console.log(message); ❌ Error 🔹 Block Scope Variables declared with "let" and "const" inside "{ }" are only accessible within that block. if (true) { let age = 25; console.log(age); } // console.log(age); ❌ Error 📌 Understanding scope helps developers write cleaner code and avoid bugs related to variable access. Mastering these fundamentals makes JavaScript much easier to understand and improves problem-solving skills. #JavaScript #WebDevelopment #FrontendDeveloper #Coding #LearnToCode
To view or add a comment, sign in
-
JavaScript Closures — made simple 💡 Closures sound complex… but they’re actually simple once you get the idea. A closure is when a function remembers variables from its outer scope even after the outer function has finished executing. Think of it like this: An inner function carries a “backpack” of variables and never forgets them. How it works: 1. Outer function creates a variable 2. Inner function uses that variable 3. Outer function returns the inner function 4. Inner function still has access to that variable Why closures are powerful: • Data privacy (encapsulation) • Maintain state between function calls • Used in callbacks, event handlers, React hooks • Foundation for advanced JavaScript concepts Real-world uses: • Counters • Private variables • One-time execution functions • Custom hooks & memoization One-line takeaway: A closure = function with a memory of its lexical scope If you understand closures, you’re moving from basics to real JavaScript thinking. What concept in JavaScript took you the longest to understand? #JavaScript #Closures #WebDevelopment #Frontend #CodingConcepts #LearnJavaScript #Programming #DeveloperLife
To view or add a comment, sign in
-
-
JavaScript Closures — made simple 💡 Closures sound complex… but they’re actually simple once you get the idea. A closure is when a function remembers variables from its outer scope even after the outer function has finished executing. Think of it like this: An inner function carries a “backpack” of variables and never forgets them. How it works: 1. Outer function creates a variable 2. Inner function uses that variable 3. Outer function returns the inner function 4. Inner function still has access to that variable Why closures are powerful: • Data privacy (encapsulation) • Maintain state between function calls • Used in callbacks, event handlers, React hooks • Foundation for advanced JavaScript concepts Real-world uses: • Counters • Private variables • One-time execution functions • Custom hooks & memoization One-line takeaway: A closure = function with a memory of its lexical scope If you understand closures, you’re moving from basics to real JavaScript thinking. What concept in JavaScript took you the longest to understand? #JavaScript #Closures #WebDevelopment #Frontend #CodingConcepts #LearnJavaScript #Programming #DeveloperLife
To view or add a comment, sign in
-
-
5 JavaScript concepts that make everything else click. Learn these deeply and frameworks stop being magic. 1. Closures A function that remembers the scope it was created in. This is how callbacks, event listeners, and setTimeout actually work. Not understanding closures = constant bugs you can't explain. 2. The Event Loop JavaScript is single-threaded. The event loop is how async code doesn't block everything else. If you've ever wondered why setTimeout(fn, 0) still runs after synchronous code — this is why. 3. Prototypal Inheritance Every object in JS has a prototype chain. Classes are just syntax sugar over this. Knowing this means you understand how methods are shared and where "cannot read properties of undefined" is actually coming from. 4. this - and how it changes 'this' is not fixed. It depends on how a function is called, not where it's defined. Arrow functions inherit 'this' from their enclosing scope. Regular functions create their own. This one trips up everyone. 5. Promises and the microtask queue Promises don't just "make async code cleaner." They run in the microtask queue, which runs before the next macrotask (setTimeout). Understanding this makes async debugging dramatically easier. Which of these gave you the biggest headache? 👇 #webdeveloper #coding #javascript
To view or add a comment, sign in
-
-
Wrote a complete guide on JavaScript Array Methods 📊 The 6 methods every JavaScript developer reaches for daily — explained simply with real examples. Stop writing clunky for loops for everything. Here's what's covered: → push() & pop() — add and remove from the end → shift() & unshift() — add and remove from the front → map() — transform every item, get a new array back → filter() — keep only items that pass a test → reduce() — collapse an entire array to one value → forEach() — loop without needing a result Plus: ✔ Before/after array state for every method ✔ Flowcharts showing exactly how map() and filter() work ✔ for loop vs map/filter side-by-side comparison ✔ A complete shopping cart example using all of them together The one comparison that made it click for me: map() = transform every item filter() = keep some items reduce() = squash everything into one thing forEach() = just do something, don't need a result Link : https://lnkd.in/gs4NGWWj chechout the hashnode profile : https://lnkd.in/gAwxuryw #JavaScript #WebDevelopment #LearnToCode #Frontend #ArrayMethods #chaicode #hiteshchoudhary #piyushgargh
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
Nice explanation brother 👍