🚀 JavaScript Event Loop “JavaScript is single-threaded…” 🧵 👉 Then how does it handle timers, API calls, promises, and user interactions so smoothly? What is the Event Loop? 👉 The Event Loop is a mechanism that continuously checks the call stack and task queues, and executes code in the correct order without blocking the main thread. 👉 It ensures JavaScript remains non-blocking and efficient. To Understand Event Loop, You Need 5 Core Pieces: 1️⃣ Call Stack 📚 The Call Stack is a data structure that keeps track of function execution in JavaScript. It follows the Last In, First Out (LIFO) principle. ⚙️ How It Works: >> When a function is called → it is pushed onto the stack >> When the function completes → it is popped off the stack >> The stack always runs one function at a time Example: function greet() { console.log("Hello"); } greet(); 👉 Goes into stack → executes → removed 2️⃣ Web APIs 🌐 👉 Provided by the browser (not JavaScript itself) Handles async operations like: setTimeout, fetch, DOM events.... 3️⃣ Callback Queue (Macrotask Queue) 📥: The Callback Queue (also called Task Queue) is a place where callback functions wait after completing asynchronous operations, until the Call Stack is ready to execute them. ⚙️ How It Works: >> Async function (like setTimeout) runs in background >> After completion → its callback goes to Callback Queue Event Loop checks: > If Call Stack is empty → moves callback to stack > If not → waits 👉 Any callback from async operations like timers, events, or I/O goes into the Callback Queue (except Promises, which go to Microtask Queue). 4️⃣ Microtask Queue ⚡: The Microtask Queue is a special queue in JavaScript that stores high-priority callbacks, which are executed before the Callback Queue. ⚙️How It Works: Execute all synchronous code (Call Stack) Check Microtask Queue Execute ALL microtasks Then move to Callback Queue 5️⃣ Event Loop 🔁 👉 Keeps checking: 👉 “Is the call stack empty?” If YES: >> Execute all microtasks >> Then execute macrotasks 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: >> JS executes synchronous code first >> Then Microtasks (Promises) completely >> Then Callback Queue (setTimeout, events) >> Event Loop keeps checking and moving tasks #JavaScript #EventLoop #AsyncJavaScript #WebDevelopment #Frontend #Coding #Developers #Programming #LearnJavaScript #100DaysOfCode
Understanding JavaScript Event Loop: Call Stack, Web APIs, Callback Queue, Microtask Queue
More Relevant Posts
-
🚀 Today we are going to analyse the JavaScript microtask queue, macrotask queue, and event loop. A junior developer once asked me during a code review: "Why does Node.js behave differently even when the code looks simple?" So I gave him a small JavaScript snippet and asked him to predict the output. console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); He answered confidently: Start Timeout Promise End But when we ran the code, the output was: Start End Promise Timeout He looked confused. That’s when we started analysing how JavaScript actually works internally. 🧠 Step 1: JavaScript is Single Threaded JavaScript runs on a single thread. It executes code line by line inside the call stack. So first it runs: console.log("Start") → Start console.log("End") → End Now the stack becomes empty. ⚙️ Step 2: Macrotask Queue setTimeout goes to the macrotask queue. Even though timeout is 0ms, it does not execute immediately. It waits in the macrotask queue. Examples of macrotasks: • setTimeout • setInterval • setImmediate • I/O operations • HTTP requests ⚡ Step 3: Microtask Queue Promise goes to the microtask queue. Examples of microtasks: • Promise.then() • Promise.catch() • Promise.finally() • process.nextTick (Node.js) • queueMicrotask() Microtasks always get higher priority. They execute before macrotasks. 🔁 Step 4: Event Loop Now the event loop starts working. The event loop checks: Is the call stack empty? Yes Check microtask queue Execute all microtasks Then execute macrotasks So execution becomes: Start End Promise Timeout Now everything makes sense. 🏗️ Real Production Example Imagine a Node.js API: app.get("/users", async (req, res) => { console.log("Request received"); setTimeout(() => console.log("Logging"), 0); await Promise.resolve(); console.log("Processing"); res.send("Done"); }); Execution order: Request received Processing Logging Why? Because Promise (microtask) runs before setTimeout (macrotask). This directly affects: • API response time • Logging • Background jobs • Queue processing • Performance optimization 🎯 Why Every Node.js / NestJS / Next.js Developer Should Know This Because internally: • Async/Await uses Promises • API calls use Event Loop • Background jobs use Macrotasks • Middleware uses Microtasks • Performance depends on queue execution Without understanding this, debugging production issues becomes very difficult. 💡 Final Thought JavaScript is not just a language. It is an event-driven execution engine. If you understand microtask queue, macrotask queue, and event loop, you don’t just write code — you understand how the runtime thinks. And once you understand the runtime, you start building faster and more scalable systems. #JavaScript #NodeJS #EventLoop #Microtasks #Macrotasks #NextJS #NestJS #SystemDesign #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 setTimeout() vs setInterval() in JavaScript 📘 Definition: setTimeout() is a built-in JavaScript function that executes a given function once after a specified delay (in milliseconds). 👉 Syntax: setTimeout(callbackFunction, delay); 👉 Example: setTimeout(() => { console.log("Runs after 2 seconds"); }, 2000); Key Points: ✔ Executes only once ✔ Delay is in milliseconds (1000ms = 1 second) ✔ Time is not exact, it's a minimum delay 📘 Definition: setInterval() is a built-in JavaScript function that repeatedly executes a function at fixed time intervals. 👉 Syntax: setInterval(callbackFunction, interval); 👉 Example: setInterval(() => { console.log("Runs every 2 seconds"); }, 2000); Key Points: ✔ Executes again and again ✔ Runs at a fixed interval ✔ Continues until manually stopped 🧠 How JavaScript Handles Them (Event Loop Concept) JavaScript is single-threaded, meaning it can execute one task at a time. So how does it handle timers? 👉 Flow: >>>setTimeout / setInterval are handled by Browser APIs >>>After delay, callbacks go to the Callback Queue >>>The Event Loop moves them to the Call Stack when it’s empty That’s why: 👉 Execution time is not guaranteed 👉 It depends on what’s already running ⚠️ Important Difference ✔ setTimeout → Executes once after delay ✔ setInterval → Executes repeatedly at intervals ⚠️ Common Issue with setInterval() If the function takes longer than the interval: >> Calls can overlap >> Performance issues may occur 💡 Better Alternative (Advanced Concept) Using recursive setTimeout() function runTask() { setTimeout(() => { console.log("Controlled execution"); runTask(); }, 2000); } runTask(); ✔ Ensures next execution starts after previous finishes ✔ Gives better control 🛑 Stopping Timers: const id = setInterval(() => { console.log("Running..."); }, 1000); clearInterval(id); Use: ✔ clearTimeout() to stop timeout ✔ clearInterval() to stop interval Real-World Use Cases 🔹 setTimeout(): Delayed popups, API retry logic , Debouncing inputs 🔹 setInterval(): Digital clocks , Live dashboards, Polling servers #JavaScript #AsyncJS #EventLoop #FrontendDevelopment #Coding #WebDevelopment
To view or add a comment, sign in
-
Understanding JavaScript Runtime: From Call Stack to Event Loop (Deep Dive) Most developers use JavaScript daily, but very few truly understand what happens under the hood when code executes. If you want to think like an engineer—not just a coder—you need clarity on the JavaScript runtime model. Let’s break it down. 🔹 JavaScript Engine vs Host Environment JavaScript itself is just a language specification. It does not include things like DOM, timers, or APIs. JavaScript Engine (e.g., V8) Handles: Execution of JS code Memory allocation (Heap) Execution context (Call Stack) Garbage collection Host Environment (Browser / Node.js) Provides: Web APIs (setTimeout, fetch, DOM, events) Event loop Callback queue 👉 Key Insight: JavaScript alone is synchronous. Asynchronous behavior comes from the host environment. 🔹 Memory Model (Heap vs Call Stack) 1. Heap (Memory Allocation) Stores objects, functions, arrays Dynamically allocated Managed by Garbage Collector 2. Call Stack (Execution Context) Executes functions in LIFO (Last In First Out) Each function call creates a stack frame Example: function a() { b(); } function b() { console.log("Hello"); } a(); Call Stack: a() → b() → console.log() 🔹 Web APIs & Async Behavior When you use: setTimeout(() => console.log("Done"), 1000); What actually happens? setTimeout is handed over to Web API Timer runs outside JS engine After 1 second → callback goes to Callback Queue 🔹 Event Loop (The Heart of Async JS) The Event Loop continuously checks: IF (Call Stack is empty) THEN move task from Callback Queue → Call Stack This is why JavaScript can handle async tasks despite being single-threaded. 🔹 Callback Queue Holds tasks like: setTimeout callbacks DOM events (click, load) async operations Example queue: [onClick, onLoad, setTimeout callback] 🔹 Full Flow (Putting It All Together) Code enters Call Stack Async operations move to Web APIs Results go to Callback Queue Event Loop pushes them back to Call Stack when it's empty 🔹 Why This Matters (Real Engineering Insight) Understanding this helps you: Avoid blocking the main thread Debug async bugs (race conditions, delays) Optimize performance (debouncing, throttling) Master promises, async/await, and concurrency patterns 🔹 Final Thought JavaScript is not “asynchronous by nature.” It’s the combination of the JS engine + host environment + event loop that creates the illusion of concurrency. Once you truly understand this model, you stop guessing—and start engineering. If you're serious about becoming a high-level developer, don’t just write code. Understand how it runs. #JavaScript #WebDevelopment #Frontend #Programming #SoftwareEngineering #V8 #EventLoop
To view or add a comment, sign in
-
-
🚀 JavaScript: The Art of Execution Context & Hoisting (Why it REALLY matters) If you’ve ever wondered why JavaScript behaves the way it does, the answer lies in two core concepts: 👉 Execution Context 👉 Hoisting These aren’t just theory—they define how your code actually runs under the hood. 🧠 1. Execution Context — The Engine Behind Every Line Every time JavaScript runs code, it creates an Execution Context. There are mainly two types: Global Execution Context (GEC) → created when your program starts Function Execution Context (FEC) → created every time a function is invoked 🔄 How it works: Each execution context is created in two phases: 1️⃣ Memory Creation Phase (Hoisting Phase) Variables → stored as undefined Functions → stored with full definition 2️⃣ Code Execution Phase Values are assigned Code runs line by line ⚡ 2. Hoisting — Not Magic, Just Memory Allocation Hoisting is often misunderstood. It doesn’t “move code up”— 👉 it simply means JavaScript allocates memory before execution begins 🔍 Example that explains EVERYTHING console.log(a); // ? console.log(b); // ? console.log(myFunc); // ? var a = 10; let b = 20; function myFunc() { console.log("Hello JS"); } 🧠 Memory Phase: a → undefined b → (in Temporal Dead Zone) myFunc → full function stored 🏃 Execution Phase: console.log(a); // undefined console.log(b); // ❌ ReferenceError console.log(myFunc); // function definition 💣 The TRICKY Part (Arrow Functions vs Normal Functions) console.log(add); const add = () => { return 2 + 3; }; ❓ Output? 👉 ReferenceError: Cannot access 'add' before initialization Why? Because: const variables are hoisted but not initialized They stay in the Temporal Dead Zone (TDZ) So unlike normal functions: console.log(sum); // works function sum() { return 5; } 👉 Function declarations are fully hoisted with definition 👉 But arrow functions behave like variables ❌ 🔥 Key Takeaways ✔ JavaScript creates a new execution context for every function ✔ Memory is allocated before execution starts ✔ var → hoisted as undefined ✔ let / const → hoisted but in TDZ ✔ Function declarations → fully hoisted ✔ Arrow functions → treated like variables 🎯 Why This Matters Understanding this helps you: Debug errors faster ⚡ Write predictable code 🧩 Master interviews 💼 Think like the JavaScript engine 🧠 💡 JavaScript is not weird—you just need to think in terms of execution context. #JavaScript #WebDevelopment #Frontend #Coding #100DaysOfCode #AkshaySaini #Hoisting #ExecutionContext
To view or add a comment, sign in
-
JSI (JavaScript Interface) — concise overview for React Native What JSI is - JSI is a lightweight C++ layer that exposes a host‑embedded JavaScript runtime (e.g., Hermes, V8, JavaScriptCore) to native code with a stable, low‑overhead API. It replaces the old async JSON‑serialized “bridge” with direct in‑process bindings between JS and native. Why JSI matters - Eliminates expensive serialization/IPC of the legacy bridge. - Enables synchronous, low‑latency calls from JS to native and vice versa. - Serves as the foundation for TurboModules and the Fabric renderer, unlocking better performance and finer control over native interactions. How it works (high level) - JSI exposes a C++ API that represents JS values, functions, objects, and the runtime host. - Native modules and objects can be registered as JSI objects/functions and accessed directly from JS as if they were plain JS objects. - Calls go through the JSI API into the embedded runtime (no automatic JSON stringify/parse), enabling zero-copy or minimal-copy interactions when implemented carefully. - JSI runs in the JS runtime thread context; native code can create bindings that execute synchronously on that thread. Key benefits - Performance: much lower overhead per call vs bridge; reduces CPU and latency for frequent/native-heavy interactions. - Flexibility: native code can expose arbitrary APIs that look/behave like JS objects, enabling richer integrations. - Concurrency & determinism: tighter control over when operations run; easier to integrate with concurrent rendering and Fabric’s commit model. - Better memory semantics: enables zero-copy patterns and improved lifetime management when designed correctly. Common uses in RN New Architecture - TurboModules: lightweight native modules implemented as JSI bindings for faster method calls and direct property access. - Fabric renderer: uses JSI to coordinate view updates and layout with fewer serialized payloads. - Native-hosted JS objects: exposing native data structures or functionality directly into JS space. Debugging & tooling - Use Hermes debugger and Flipper plugins to inspect JS runtime behavior. - Instrument native code and measure round‑trip times to ensure expected gains. - Unit/test JSI modules with engine embeddings where possible. When to adopt - Adopt JSI when you need low‑latency native interactions (animations, gesture handlers, high‑frequency telemetry, tight renderer integrations) or when migrating from the bridge to the New Architecture (Fabric/TurboModules). For simple, infrequent native calls, legacy native modules remain acceptable. Summary JSI is the technical foundation that enables React Native’s New Architecture to reduce bridge overhead and deliver faster, more synchronous-style integrations between JS and native. Properly used, it unlocks substantial performance and UX improvements — but it requires careful threading, memory, and API design. #ReactNative #Perfomance #Optimization
To view or add a comment, sign in
-
-
#js #10 **What is Execution Context, Call Stack and Call Back Queue in Javascript** 🧠 1. What is Execution Context? 👉 Execution Context = The environment where JavaScript code runs 📦 Types of Execution Context 1. Global Execution Context (GEC) Created when program starts Runs global code let a = 10; 👉 This runs inside Global Execution Context 2. Function Execution Context (FEC) Whenever a function is called: function greet() { console.log("Hello"); } greet(); 👉 A new execution context is created for greet() 🧩 What’s inside Execution Context? Each context has: Memory (Variables) Code (Execution) 🥞 2. What is Call Stack? 👉 Call Stack = A stack where execution contexts are stored and executed Think of it like plates stacked on top of each other 🔄 How Call Stack Works Example: function one() { two(); } function two() { console.log("Hello"); } one(); Step-by-step: Global Execution Context pushed one() called → pushed two() called → pushed console.log runs two() removed one() removed Stack flow: Call Stack: [ Global ] [ one() ] [ two() ] ← runs Then: [ Global ] 📥 3. What is Callback Queue? 👉 Callback Queue = A queue where async callbacks wait before execution Example: console.log("Start"); setTimeout(() => { console.log("Async"); }, 2000); console.log("End"); Flow: Start → runs setTimeout → goes to browser End → runs After 2 sec → callback goes to Callback Queue 🔄 How everything connects Now combine all three: 👉 Call Stack 👉 Callback Queue 👉 Event system → Event Loop 🔁 Final Flow Call Stack runs normal code Async task completes → goes to queue Event loop checks: If stack empty → move task from queue → stack 🧑🍳 Simple Analogy Execution Context = workspace 🧑💻 Call Stack = stack of tasks 📚 Callback Queue = waiting line 🚶 Event Loop = manager checking when to allow next 🎯 Quick Comparison Concept Meaning Execution Context Environment where code runs Call Stack Where functions execute Callback Queue Where async tasks wait 🧾 Final Summary Execution Context = where code runs Call Stack = manages execution order (LIFO) Callback Queue = stores async callbacks Event Loop connects everything 💡 One-line understanding 👉 JavaScript uses execution contexts inside a call stack, and async tasks wait in a callback queue until the event loop pushes them for execution. #Javascript #ObjectOrientedProgramming #SoftwareDevelopment
To view or add a comment, sign in
-
I used to manipulate objects directly in JavaScript. Until one day, it didn't work. And the errors were almost impossible to trace. Meanwhile JavaScript has built a clean, deliberate API specifically for the job I had been doing messily for a long time. What is Reflect? Reflect is a built-in JavaScript object that provides a set of methods for performing fundamental operations on objects. The same operations you've always done, but in a more controlled, predictable, and reliable way. Reading properties. Setting values. Checking existence. Deleting keys. Reflect does all of this in a clean way. The most important Reflect methods: -> Reflect.get() - reads a property from an object. const user = { name: "Markus" }; Reflect.get(user, "name"); -> "Markus" Same as user.name - but more explicit and safer in dynamic contexts. -> Reflect.set() - sets a property value and returns true or false. const user = { name: "Markus" }; Reflect.set(user, "name", "John"); -> true console.log(user.name); -> "John" Unlike direct assignment - it tells you whether it succeeded by returning true. -> Reflect.has() - checks if a property exists. Reflect.has(user, "name"); -> true Same as the in operator - but cleaner in functional and dynamic code. -> Reflect.deleteProperty() - deletes a property safely. Reflect.deleteProperty(user, "name"); -> true Same as the delete keyword - but returns a boolean instead of throwing silently. -> Reflect.ownKeys() - returns all keys of an object. const user = { name: "Markus", age: 25}; Reflect.ownKeys(user); -> ["name", "age"] Where Reflect truly shines - with Proxy. Reflect and Proxy are natural partners. Inside a Proxy trap, Reflect lets you perform the default operation in a clean way - without rewriting the behaviour from scratch. Example: const proxy = new Proxy(user, { get(target, key) { console.log(`Reading: ${key}`); return Reflect.get(target, key); -> clean default behaviour } }); Reflect doesn't replace what you already know. It refines it. It makes the operations you perform on objects more intentional, consistent, and significantly easier to debug when something goes wrong.
To view or add a comment, sign in
-
-
🚀 Deep JavaScript Concepts Most Developers Don’t Know (But Should!) If you’re already comfortable with closures, promises, and async/await… here are some next-level JavaScript concepts that separate good devs from great ones 👇 🧠 1. Hidden Classes & Shapes (V8 Internals) JavaScript objects are dynamic, but engines like V8 JavaScript engine optimize them using hidden classes. 👉 Objects with the same structure share the same internal layout 👉 Changing structure later (adding/removing props) can deoptimize performance 🔄 2. Event Loop Internals (Microtask vs Macrotask) Not just “event loop” — the priority system matters: 👉 Microtasks (Promises, queueMicrotask) 👉 Macrotasks (setTimeout, setInterval) setTimeout(() => console.log("Macrotask"), 0); Promise.resolve().then(() => console.log("Microtask")); Output: Microtask Macrotask 👉 Microtasks always run before the next macrotask 🧩 3. Deoptimization (Deopt) — Silent Performance Killer Modern engines optimize your code using JIT, but certain patterns force them to fall back: ❌ Changing object shapes ❌ Using "delete" on objects ❌ Accessing out-of-bounds arrays ❌ Mixing types (number + string) 👉 This is called deoptimization, and it can silently slow your app 🧬 4. Garbage Collection (GC) Mechanics JavaScript uses automatic memory management, but not all objects are equal: 👉 Young Generation (fast cleanup) 👉 Old Generation (slower, long-lived objects) Engines like V8 JavaScript engine use Mark-and-Sweep + Generational GC 💡 Memory leaks still happen if references are retained! 🧮 5. Tagged Integers (SMI Optimization) Small integers are stored differently than large numbers: 👉 Fast path for small integers (SMIs) 👉 Large numbers → heap allocation This impacts performance in tight loops ⚡ 🔍 7. Prototype Chain Lookup Optimization Property access doesn’t just check the object: 👉 It walks the prototype chain 👉 Engines cache these lookups too const obj = {}; obj.toString(); // comes from prototype ⚙️ 8. JIT Compilation (Just-In-Time) JavaScript is not just interpreted anymore: 👉 Parsed → Compiled → Optimized at runtime 👉 Engines like Node.js use JIT for speed 💡 Hot code paths get highly optimized 🧨 9. Closures & Memory Retention Closures are powerful but can cause hidden memory issues: function outer() { let bigData = new Array(1000000); return function inner() { console.log("Using closure"); }; } 👉 "bigData" stays in memory because of closure reference! 🔐 10. Temporal Dead Zone (TDZ) "let" and "const" behave differently than "var": console.log(a); // ReferenceError let a = 10; 👉 Variables exist but are not accessible before initialization 🔥 Final Thought Most developers write JavaScript… Few understand how it actually runs under the hood. That difference? 👉 Performance 👉 Scalability 👉 Senior-level thinking #JavaScript #V8 #NodeJS #WebPerformance #SoftwareEngineering #TechDeepDive
To view or add a comment, sign in
-
#js #19 **Optional Chaining in Javascript** Optional Chaining (?.) in JavaScript is used to safely access nested properties without causing errors if something is null or undefined. 🔹 Why We Need It Without optional chaining: const user = null; console.log(user.name); // ❌ Error: Cannot read property 'name' 👉 This crashes your code. ✅ With Optional Chaining const user = null; console.log(user?.name); // undefined ✅ (no error) 👉 If user is null or undefined, it stops and returns undefined 🔹 Syntax obj?.propertyobj?.[key]obj?.method() ✅ Examples 📌 1. Nested Objects const user = { profile: { name: "Navnath" }}; console.log(user?.profile?.name); // Navnath console.log(user?.address?.city); // undefined 📌 2. Function Calls const user = { greet() { return "Hello"; }}; console.log(user.greet?.()); // Hello console.log(user.sayHi?.()); // undefined (no error) 📌 3. Arrays const arr = [1, 2, 3]; console.log(arr?.[0]); // 1 console.log(arr?.[5]); // undefined 🔥 Real Use Case (Very Common) const response = { data: { user: { name: "Navnath" } }}; const name = response?.data?.user?.name; 👉 Avoids writing multiple checks like: if (response && response.data && response.data.user) ... ⚠️ Important Points ❌ Doesn’t Work on Undeclared Variables console.log(user?.name); // ❌ if user is not defined at all ⚠️ Stops Only on null / undefined const obj = { value: 0 }; console.log(obj?.value); // 0 ✅ (not skipped) 🔥 Combine with Nullish Coalescing (??) const user = {}; const name = user?.name ?? "Guest"; console.log(name); // Guest 🧠 Easy Memory Trick ?. → "If exists, then access" Otherwise → return undefined, don’t crash #Javascript #ObjectOrientedProgramming #SoftwareDevelopment
To view or add a comment, sign in
-
Small JavaScript bugs keep escaping to production and breaking critical user flows. Debugging inconsistent runtime behavior steals time from feature delivery. ────────────────────────────── Proxy and Reflect API Guide with Examples This tutorial provides an advanced understanding of the Proxy and Reflect APIs in JavaScript, including practical examples, common use cases, and architectural considerations for enterprise applications. hashtag#javascript hashtag#proxy hashtag#reflect hashtag#api hashtag#advanced hashtag#architecture ────────────────────────────── How to Use Proxy and Reflect API Quickly? The fastest way to utilize the Proxy and Reflect APIs is by creating a simple proxy object that wraps an existing object. You can easily intercept operations like property access, assignment, and function calls. Here's a quick example of using Proxy with a handler to log property accesses: const target = { message: 'Hello, World!' }; const handler = { get: function(obj, prop) { console.log(Property ${prop} was accessed.); return obj[prop]; } }; const proxy = new Proxy(target, handler); console.log(proxy.message); // Logs: Property message was accessed. How to Proxy and Reflect API in Detail? The Proxy object allows you to define custom behavior for fundamental operations (e.g., property lookup, assignment, enumeration, function invocation, etc.). It is basically a wrapper around another object (the target) and intercepts operations performed on that object. The Reflect API complements Proxy by providing methods to perform operations on objects. It simplifies the work of the Proxy by offering methods that mirror the default behavior of JavaScript operations. For example, Reflect.get() can be used to access a property while respecting the Proxy's traps. Let's examine a detailed example where we create a Proxy to track user activity in an application: const user = { name: 'John Doe', age: 30, }; const handler = { get(target, prop) { if (prop in target) { console.log(Getting ${prop}: ${target[prop]}); return Reflect.get(target, prop); } else { console.log(Property ${prop} does not exist.); return undefined; } }, set(target, prop, value) { console.log(Setting ${prop} to ${value}); return Reflect.set(target, prop, value); } }; const proxy = new Proxy(user, handler); proxy.name; // Logs: Getting name: John Doe proxy.age = 31; // Logs: Setting age to 31 proxy.gender; // Logs: Property gender does not exist. In this example, we see how the get and set traps are defined. Each time a property is accessed or modified, it logs the action. The use of Reflect ensures that the original target object's behavior is preserved. What is Proxy and Reflect API? The Proxy API was introduced in ECMAScript 2015 (ES6) to provide a powerful way to create flexible and dynamic objects. A Proxy can redefine fundamental operations—lik
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