🚀 Day 3/100 — Closures in JavaScript (Used Everywhere in Production) Continuing my 100 Days of JavaScript & TypeScript challenge. Today I explored one of the most powerful (and often misunderstood) concepts in JavaScript: 👉 Closures ⸻ 📌 What is a Closure? A closure is created when a function remembers variables from its outer scope, even after that outer function has finished executing. In simple terms: A function + its lexical environment = Closure ⸻ 📌 Example function createCounter() { let count = 0; return function () { count++; return count; }; } const counter = createCounter(); console.log(counter()); // 1 console.log(counter()); // 2 Even though createCounter() has finished execution, the inner function still has access to count. That’s a closure in action. ⸻ 🧠 Why This Works Because JavaScript functions capture their surrounding scope at the time they are created. This is called the lexical scope. ⸻ 💡 Real-World Use Cases Closures are everywhere in production systems: • Data privacy (encapsulation without classes) • Creating reusable functions • Maintaining state in async operations • Event handlers • Memoization & caching ⸻ 💡 Engineering Insight Closures are the foundation behind: • React hooks • Middleware patterns • Function factories • Many JavaScript libraries But they can also cause issues: ⚠ Memory leaks if references are not handled properly ⚠ Unexpected values in loops (classic bug) Example issue: for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); } Output: 3 3 3 Fix using let (block scope): for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); } Output: 0 1 2 ⸻ ⏭ Tomorrow: Hoisting in JavaScript (var, let, const — what really happens?) #100DaysOfCode #JavaScript #TypeScript #WebDevelopment #SoftwareEngineering #Closures
Closures in JavaScript: Understanding Lexical Scope and Memory Leaks
More Relevant Posts
-
🚀 Day 2/100 — How the JavaScript Event Loop Actually Works Continuing my 100 Days of JavaScript & TypeScript challenge. Today I explored one of the most important concepts in JavaScript: The Event Loop. JavaScript is single-threaded, which means it can execute only one task at a time. But in real applications we handle: • API requests • timers • user interactions • file operations So how does JavaScript manage all of this without blocking the application? 👉 The answer: The Event Loop ⸻ 📌 Core Components JavaScript concurrency relies on three main parts: 1️⃣ Call Stack Where functions are executed. Example: function greet() { console.log("Hello"); } greet(); The function goes to the call stack, runs, and then exits. ⸻ 2️⃣ Web APIs Provided by the browser or runtime. Examples: • setTimeout • fetch • DOM events These operations run outside the call stack. ⸻ 3️⃣ Callback Queue Once an async task finishes, its callback is placed in the queue. Example: console.log("Start"); setTimeout(() => { console.log("Timeout finished"); }, 0); console.log("End"); Output: Start End Timeout finished Even with 0ms, the callback waits until the call stack is empty. ⸻ ⚙ Role of the Event Loop The event loop continuously checks: 1️⃣ Is the call stack empty? 2️⃣ If yes → move a task from the queue to the stack This mechanism allows JavaScript to handle asynchronous operations efficiently. ⸻ 💡 Engineering Insight Understanding the event loop is critical when working with: • async/await • Promises • performance optimization • avoiding UI blocking Many real-world bugs happen because developers misunderstand how async tasks are scheduled. ⸻ ⏭ Tomorrow: Microtasks vs Macrotasks (Why Promises run before setTimeout) #100DaysOfCode #JavaScript #TypeScript #WebDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
🚀 Understanding the JavaScript Event Loop (Clearly & Practically) | Post 2 JavaScript is single-threaded — yet it handles asynchronous tasks like a pro. The secret behind this is the Event Loop 🔁 --- 📌 What is the Event Loop? The Event Loop is a mechanism that continuously checks: 👉 “Is the Call Stack empty?” If yes, it pushes pending tasks into execution. --- 🧩 Core Components 🔹 Call Stack Executes synchronous code line by line. 🔹 Web APIs (Browser / Node.js) Handles async operations like: - setTimeout - API calls - File operations 🔹 Callback Queue Stores callbacks once async tasks are completed. 🔹 Event Loop Moves callbacks from the queue to the Call Stack when it's free. --- 🔁 How It Works 1. Execute synchronous code 2. Send async tasks to Web APIs 3. Once done → push to Callback Queue 4. Event Loop checks → moves to Call Stack --- 🧠 Example console.log("Start"); setTimeout(() => { console.log("Async Task"); }, 0); console.log("End"); 👉 Output: Start → End → Async Task Even with "0ms", async tasks wait until the stack is empty. --- ⚡ Important Concept 👉 Microtasks vs Macrotasks ✔️ Microtasks (High Priority) - Promise.then - async/await ✔️ Macrotasks - setTimeout - setInterval 📌 Microtasks always execute before macrotasks. --- 🎯 Why You Should Care Understanding the Event Loop helps you: ✅ Write non-blocking, efficient code ✅ Debug async behavior easily ✅ Build scalable applications ✅ Crack JavaScript interviews --- 💬 Mastering this concept is a game-changer for every JavaScript developer. #JavaScript #EventLoop #WebDevelopment #NodeJS #Frontend #Programming #SoftwareEngineering
To view or add a comment, sign in
-
-
Most developers use TypeScript to add types to JavaScript. Senior developers use TypeScript to make entire categories of bugs impossible. 5 advanced patterns that actually matter in production 👇 Instead of "any" → Use unknown + type guards any disables the type system entirely. unknown forces you to verify the type before using it. → function parse(data: unknown) { → if (typeof data === string) { return data.toUpperCase() } → throw new Error(Unexpected type) → } Instead of repeating similar types → Use Utility Types → Partial<T> — makes all properties optional → Required<T> — makes all properties required → Pick<T, K> — selects a subset of properties → Omit<T, K> — excludes specific properties → Record<K, V> — builds a typed key-value map Define once. Derive everywhere. One source of truth. Instead of hardcoding string literals → Use const assertions → const ROLES = [admin, editor, viewer] as const → type Role = typeof ROLES[number] Change the array — the type updates automatically. Zero drift. Instead of messy overloaded functions → Use discriminated unions → type Shape = → | { kind: circle; radius: number } → | { kind: rectangle; width: number; height: number } Add a new Shape and forget to handle it — TypeScript warns you. The compiler becomes your code reviewer. Instead of repeating validation logic → Use branded types → type UserId = string & { readonly brand: UserId } → type OrderId = string & { readonly brand: OrderId } → function getOrder(userId: UserId, orderId: OrderId) { ... } Passing an OrderId where a UserId is expected is now a compile error — not a runtime bug. TypeScript is not just about autocomplete. Used well, it makes illegal states unrepresentable. Which of these patterns are you already using in production? 👇 #TypeScript #SoftwareEngineering #FullStack #FrontendDevelopment #WebDevelopment #JavaScript
To view or add a comment, sign in
-
🚀 Mastering Closures in JavaScript – A Real-World Example One of the most powerful (and often misunderstood) concepts in JavaScript is the closure. Think of it as a backpack 🎒 that an inner function carries, filled with variables from its outer function—even after the outer function has finished running. Here’s a neat example: function logWithPrefix(prefix: string): (message: string) => void { // Inner function remembers 'prefix' return function (message: string) { log(`${prefix} | ${message}`); }; } // Create loggers with different "backpacks" const infoLogger = logWithPrefix('INFO'); const errorLogger = logWithPrefix('ERROR'); infoLogger('Hello World!'); // Output: "INFO | Hello World!" errorLogger('Something went wrong!'); // Output: "ERROR | Something went wrong!" function log(message: string): void { console.log(message); } 💡 What’s happening here? logWithPrefix creates a closure. The inner function remembers the prefix variable, even after logWithPrefix has returned. This allows us to build reusable, context-aware loggers (INFO, ERROR, etc.) without repeating code. 👉 Closures are everywhere: event handlers, callbacks, and even frameworks like React rely on them. Once you grasp this, you unlock a new level of JavaScript power. 🔑 Takeaway: Closures = memory + reusability + cleaner code. ✨ If you found this useful, imagine how closures can simplify your next project. Keep experimenting, and you’ll see them pop up more often than you think! #JavaScript #TypeScript #Closures #WebDevelopment #CleanCode #InterviewPrep #LearningEveryday #TechLeadership
To view or add a comment, sign in
-
-
Ever wondered what actually happens when you use new in JavaScript? 🤔 Today I learned: 👉 How objects are created behind the scenes 👉 How prototypes are linked 👉 How constructors build instances Documented everything in this article 👇 https://lnkd.in/gr2UykHg #JavaScript #100DaysOfCode #WebDev #chaicode Chai Code Hitesh ChoudharyPiyush Garg Akash Kadlag Suraj Kumar Jha
To view or add a comment, sign in
-
🚀 JavaScript Runtime Environment — What really runs your code? When we say “JavaScript runs in the browser” or “Node.js runs JavaScript,” we’re actually talking about the JavaScript Runtime Environment. But what exactly is it? 🤔 👉 A JavaScript Runtime Environment is where your JavaScript code gets executed. It provides everything your code needs beyond just the language itself. 💡 Key Components: 1️⃣ JavaScript Engine (e.g., V8) • Converts JS code into machine code • Handles memory and execution 2️⃣ Call Stack • Keeps track of function execution • Follows LIFO (Last In, First Out) 3️⃣ Web APIs / Node APIs • Provided by the environment (NOT JavaScript!) • Examples: setTimeout, DOM, Fetch API 4️⃣ Callback Queue • Stores async callbacks waiting to execute 5️⃣ Event Loop 🔁 • The real hero! • Moves tasks from queue → call stack when it’s empty 🎯 Interview Insight: 💡 1. What is a JavaScript Engine? 👉 A program that executes JavaScript code by converting it into machine code 👉 Example: V8 (used in Chrome & Node.js) 💡 2. What is the difference between a JavaScript Engine and Runtime Environment? 👉 Engine → Executes code 👉 Runtime → Engine + APIs + Event Loop 💡 3. What is V8 Engine? 👉 An open-source JavaScript engine developed by Google 👉 Written in C++ 👉 Used in Chrome and Node.js 💡 4. How does a JavaScript Engine execute code? 👉 Parsing → Compilation → Execution 💡 5. What is Parsing in JavaScript Engine? 👉 Converts code into an Abstract Syntax Tree (AST) 💡 6. What is AST (Abstract Syntax Tree)? 👉 A tree representation of JavaScript code structure 💡 7. What is Just-In-Time (JIT) Compilation? 👉 Combines interpretation + compilation 👉 Improves performance by compiling code during execution 💡 8. What is the difference between Interpreter and Compiler? 👉 Interpreter → Executes line by line 👉 Compiler → Converts entire code before execution 💡 9. Does JavaScript use Interpreter or Compiler? 👉 Both (via JIT compilation) 💡10. Is setTimeout part of JavaScript? ❌ No ✅ It’s provided by the runtime environment (Browser/Node) #JavaScript #WebDevelopment #Frontend #NodeJS #EventLoop #Programming #Developers
To view or add a comment, sign in
-
🧠 Day 13 — Class vs Prototype in JavaScript (Simplified) JavaScript has both Classes and Prototypes — but are they different? 🤔 --- 🔍 The Truth 👉 JavaScript is prototype-based 👉 class is just syntactic sugar over prototypes --- 📌 Using Class (Modern JS) class Person { constructor(name) { this.name = name; } greet() { console.log(`Hello ${this.name}`); } } const user = new Person("John"); user.greet(); // Hello John --- 📌 Using Prototype (Core JS) function Person(name) { this.name = name; } Person.prototype.greet = function () { console.log(`Hello ${this.name}`); }; const user = new Person("John"); user.greet(); // Hello John --- 🧠 What’s happening? 👉 Both approaches: Create objects Share methods via prototype Work almost the same under the hood --- ⚖️ Key Difference ✔ Class → Cleaner, easier syntax ✔ Prototype → Core JavaScript mechanism --- 🚀 Why it matters ✔ Helps you understand how JS works internally ✔ Useful in interviews ✔ Makes debugging easier --- 💡 One-line takeaway: 👉 “Classes are just a cleaner way to work with prototypes.” --- #JavaScript #Prototypes #Classes #WebDevelopment #Frontend #100DaysOfCode
To view or add a comment, sign in
-
💡 JavaScript Essentials: Closures & Hoisting Explained Simply If you're working with JavaScript, especially in frameworks like Angular or React, understanding closures and hoisting is a must. Here’s a quick breakdown 👇 🔹 Closures A closure is created when a function remembers its outer scope even after that outer function has finished execution. 👉 Why it matters? Helps in data encapsulation Used in callbacks, event handlers, and async code Powers concepts like private variables Example: function outer() { let count = 0; return function inner() { count++; console.log(count); } } const counter = outer(); counter(); // 1 counter(); // 2 🔹 Hoisting Hoisting is JavaScript’s behavior of moving declarations to the top of their scope before execution. 👉 Key points: var is hoisted and initialized with undefined let and const are hoisted but stay in the Temporal Dead Zone Function declarations are fully hoisted Example: console.log(a); // undefined var a = 10; console.log(b); // ReferenceError let b = 20; 🚀 Takeaway Closures help you retain state, while hoisting explains how JavaScript reads your code before execution. Mastering these will level up your debugging skills and help you write cleaner, predictable code. #JavaScript #WebDevelopment #Frontend #Angular #React #Coding #Developers
To view or add a comment, sign in
-
🚀 JavaScript String Interpolation: Small Feature, Big Impact Ever noticed how JavaScript automatically converts arrays into strings when used inside template literals? That’s interpolation behavior in action—and it can be both helpful and tricky. 💡 Implicit Behavior When you embed an array inside a template string: const items = ['React', 'Node', 'TypeScript']; console.log(`Stack: ${items}`); 👉 Output: Stack: React,Node,TypeScript JavaScript internally calls .toString() on the array, which joins elements with commas by default. ⚠️ The Catch This implicit behavior might not always give you the format you want. It works—but not always professionally or readably. ✅ Better Approach: Explicit Control const technologies = ['React', 'Node', 'TypeScript']; const sentence = `I work with ${technologies.join(', ')} daily.`; 👉 Output: I work with React, Node, TypeScript daily. 🔥 Why This Matters Improves readability of your output Gives you full control over formatting Avoids unexpected results in production code 🧠 Pro Tip Always prefer explicit .join() when formatting arrays in strings—clean code > clever shortcuts. #JavaScript #WebDevelopment #CleanCode #Frontend #reactjs #nodejs #ProgrammingTips
To view or add a comment, sign in
-
-
🚀 Understanding the JavaScript Event Loop (In Simple Terms) If you’ve ever wondered how JavaScript handles multiple tasks at once, the answer lies in the Event Loop. 👉 JavaScript is single-threaded, meaning it can execute one task at a time. 👉 But with the help of the Event Loop, it can handle asynchronous operations efficiently. 🔹 How it works: 1. Call Stack – Executes synchronous code (one task at a time) 2. Web APIs – Handles async operations like setTimeout, API calls, DOM events 3. Callback Queue – Stores callbacks from async tasks 4. Event Loop – Moves tasks from the queue to the call stack when it’s empty 🔹 Microtasks vs Macrotasks: - Microtasks (Promises, MutationObserver) → Executed first - Macrotasks (setTimeout, setInterval, I/O) → Executed later 💡 Execution Order Example: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); 👉 Output: Start End Promise Timeout 🔥 Key Takeaways: ✔ JavaScript doesn’t run tasks in parallel, but it handles async smartly ✔ Microtasks always run before macrotasks ✔ Event Loop ensures non-blocking behavior Understanding this concept is a game-changer for writing efficient and bug-free JavaScript code 💻 #JavaScript #FrontendDevelopment #WebDevelopment #ReactJS #Programming #EventLoop
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