JSInterop in Blazor: Is your C#-to-JS bridge suffocating your app? How I vet my JavaScript integrations: ❌ Junior You: The "Chatty Bridge" Trap Request: "We need to render 5,000 coordinates on a JavaScript map interface." Action: Loop through the C# list and send them to JS one by one. #csharp foreach (var coordinate in treeCoordinates) { await JS.InvokeVoidAsync("map.addMarker", coordinate); } The Cost: The C#-to-JS boundary is crossed 5,000 individual times. On Blazor Server, each call is a SignalR round trip. On WASM, each call is a shared memory boundary crossing. The cumulative synchronization overhead freezes the UI thread. The browser gasps for air. You Now: The "Batched Payload" Fix Request: "We need to render 5,000 coordinates on a JavaScript map interface." Action: "Can we package this and cross the bridge exactly once?" #csharp // Cross the boundary once with the entire payload await JS.InvokeVoidAsync("map.addMarkersBatched", treeCoordinatesArray); #javascript // The JS side must handle bulk insertion efficiently too window.map = { addMarkersBatched: function (coordinates) { // Batch DOM operations in one pass; don't loop and mutate individually const markers = coordinates.map(c => createMarker(c.lat, c.lng)); markerLayer.addLayers(markers); } } Important: Batching on the C# side moves the bottleneck, it doesn't eliminate it. If your JS function loops through 5,000 coordinates and mutates the DOM individually, you've just shifted the freeze from the bridge to the browser's render thread. The JS side needs to handle bulk insertion in a single pass. What you gain: →Responsive UI: The boundary crossing overhead drops from 5,000 hits to one; the UI thread stays free. →Server-friendly: On Blazor Server, you go from 5,000 SignalR round trips to one. Your infrastructure will thank you. →Scalable pattern: The same approach applies to any bulk operation across the interop boundary; chart data, table rows, canvas drawing instructions. Treat the Blazor-to-JS bridge like a toll road. Don't pay the toll for every single passenger; put them all in a bus. 💾 Save this for your next map, chart, or data-heavy JS integration. Have you ever frozen a browser tab pushing data to a JS library one record at a time? #Blazor #DotNet #JSInterop #WebPerformance #CleanCode
Optimize Blazor C#-to-JS Bridge with Batched Payloads
More Relevant Posts
-
🛠️ Phase 4 Complete: The "Input" Component in Pure JS Moving one step closer to a full design system! Today, I successfully implemented a versatile Input Component using only Vanilla JavaScript and CSS. Since I’m building this entire system from scratch before migrating to React, focusing on the core DOM logic for forms has been an invaluable deep dive. Key features of today’s build: 📝 State Handling: Integrated support for default, focus, error, and disabled states. 💡 Helper & Error Text: Built-in logic to toggle between validation messages and helpful hints. ⌨️ Event Integration: Added a onInput callback to handle live data binding without a framework. 🎨 Clean Architecture: Used a modular structure with input.js for logic and input.css for the design tokens. function createInput({ label = "", placeholder = "", value = "", error = "", helperText = "", disabled = false, onInput = null }) { const wrapper = document.createElement("div"); wrapper.classList.add("input-group"); // Label if (label) { const labelEl = document.createElement("label"); labelEl.classList.add("input-label"); labelEl.innerText = label; wrapper.appendChild(labelEl); } // Input const input = document.createElement("input"); input.classList.add("input-field"); input.placeholder = placeholder; input.value = value; input.disabled = disabled; // Error style if (error) { input.classList.add("input-error"); } // Event if (onInput && !disabled) { input.addEventListener("input", (e) => { onInput(e.target.value); }); } wrapper.appendChild(input); // Helper text if (helperText && !error) { const helper = document.createElement("div"); helper.classList.add("input-helper"); helper.innerText = helperText; wrapper.appendChild(helper); } // Error text if (error) { const errorText = document.createElement("div"); errorText.classList.add("input-error-text"); errorText.innerText = error; wrapper.appendChild(errorText); } return wrapper; } function renderInputPage(container) { container.innerHTML = "<h2>Inputs</h2>"; // Normal container.appendChild( createInput({ label: "Username", placeholder: "Enter username", helperText: "This will be visible publicly" }) ); // With value container.appendChild( createInput({ label: "Email", value: "test@mail.com" }) ); // Error container.appendChild( createInput({ label: "Password", placeholder: "Enter password", error: "Password must be at least 6 characters" }) ); ); } The image shows the different variants in action—from standard text fields to validation errors and disabled states. Up next: Modals and Accordions! #JavaScript #WebDevelopment #Frontend #DesignSystems #CodingJourney #VanillaJS #CSS3 #SoftwareEngineering
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
-
-
𝗧𝗼𝗽𝗶𝗰 𝟭𝟮: 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽 (𝗠𝗮𝗰𝗿𝗼 𝘃𝘀 𝗠𝗶𝗰𝗿𝗼𝘁𝗮𝘀𝗸𝘀) JavaScript is single-threaded, yet it handles thousands of concurrent operations without breaking a sweat. The secret isn't raw speed; it's an incredibly strict, ruthless prioritization engine. If you don't understand the difference between a macro and a microtask, your "asynchronous" code is a ticking time bomb for UI freezes. Summary: The Event Loop is the conductor of JavaScript's concurrency model. It continuously monitors the Call Stack and the Task Queues. To manage asynchronous work, it uses two distinct queues with vastly different priorities: Macrotasks (like setTimeout, setInterval, network events) and Microtasks (like Promises and MutationObserver). Crux: The VIP Queue: Microtasks have absolute priority. The engine will not move to the next Macrotask, nor will it allow the browser to re-render the screen, until the entire Microtask queue is completely empty. The Normal Queue: Macrotasks execute one by one. After a single Macrotask finishes, the Event Loop checks the Microtask queue again. The Starvation Risk: Because Microtasks can spawn other Microtasks, a recursive Promise chain can hold the main thread hostage, permanently blocking the UI from updating. The Deep Insight (Architect's Perspective): Traffic Control and Yielding: As architects, we must visualize the Event Loop as a traffic control system where Microtasks are emergency vehicles. When you resolve a massive chain of Promises or heavy async/await logic, you are flooding the intersection with ambulances. The browser's rendering engine—the normal traffic—is forced to sit at a red light until every single emergency vehicle has cleared. We don't just use async patterns for code readability; we must actively manage thread occupancy. For heavy client-side computations, we must intentionally interleave Macrotasks (like setTimeout(..., 0)) to force our code to yield control back to the Event Loop, allowing the browser to paint frames and keeping the UI responsive. Tip: If you have to process a massive dataset on the frontend (e.g., parsing a huge JSON file or formatting thousands of rows), do not use Promise.all on the entire set at once. That floods the Microtask queue and locks the UI. Instead, "chunk" the array and process each chunk using setTimeout or requestAnimationFrame. This gives the Event Loop room to breathe and the browser a chance to render 60 frames per second between your computation chunks. Tags: #SoftwareArchitecture #JavaScript #WebPerformance #EventLoop #FrontendEngineering #CleanCode
To view or add a comment, sign in
-
-
POST 1 — The JavaScript Event Loop Is Not What You Think ⚙️ Every JavaScript developer says they understand the event loop. Most of them don't. And that gap is exactly why async bugs are so hard to find and fix. Here's what's actually happening 👇 ───────────────────────── First — JavaScript is single-threaded. Always. One thread. One call stack. One thing running at a time. So how does it handle timers, fetch calls, and user events without freezing? It doesn't. The BROWSER does. And then it reports back. ───────────────────────── The pieces most developers mix up: The Call Stack → where your code actually runs. Functions get pushed in, executed, and popped out. This is the only place code runs. Web APIs → setTimeout, fetch, DOM events. These live OUTSIDE the JS engine — in the browser or Node runtime. They run in separate threads you never manage. The Task Queue (Macrotask Queue) → where callbacks from Web APIs wait to be picked up. setTimeout callbacks land here. The Microtask Queue → where Promise callbacks and queueMicrotask calls wait. This queue has HIGHER priority than the task queue. ───────────────────────── The loop itself: 1. Run everything currently on the call stack until it's empty 2. Drain the ENTIRE microtask queue — every single item, including new ones added during draining 3. Pick ONE task from the task queue 4. Go back to step 1 ───────────────────────── Why this produces bugs nobody expects: Promise.resolve().then() runs before setTimeout(() => {}, 0) — always. Microtasks can starve the task queue if you keep adding new ones during draining. Long synchronous code blocks EVERYTHING — no timers fire, no events respond, no UI updates. ───────────────────────── The practical rule: Never put heavy computation directly on the call stack. Break it up. Use setTimeout to yield back to the event loop. Keep microtask chains short and predictable. ───────────────────────── Did the microtask vs task queue distinction surprise you? Drop a comment below 👇 #JavaScript #WebDevelopment #FrontendDevelopment #Programming #WebPerformance
To view or add a comment, sign in
-
𝗥𝗲𝗮𝗰𝘁 𝘃𝘀 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: 𝗪𝗵𝘆 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀 𝗣𝗿𝗲𝗳𝗲𝗿 𝗥𝗲𝗮𝗰𝘁 𝗳𝗼𝗿 𝗨𝗜 𝗣𝗿𝗼𝗷𝗲𝗰𝘁𝘀 You built a calculator or to-do app. It felt harder in plain JavaScript. It felt easier in React. This confuses many developers. React is built on JavaScript. So how can it be easier? Here is the simple truth. JavaScript means you control everything. You select each button. You add event listeners. You store values. You update the display. You handle all edge cases. You do two jobs. You handle calculations. You handle the user interface. This makes it complex. React changes the approach. You describe what you want. React handles the rest. For a calculator: You create components. You store values in state. You update state on click. React updates the user interface. You focus on your data. React does the rest. Why React feels easier? - Components organize your code. You break the app into parts. Display, buttons, logic. Each part has one job. In JavaScript, code mixes together. - State manages your data. State holds changing values. Current number, operator, result. When state changes, UI updates. You do not update the UI yourself. - No manual DOM work. JavaScript: document.getElementById('display') React: update state only. React updates the UI. This saves time. - Reuse components easily. Write a button once. Use it everywhere. <Button value="1" /> <Button value="2" /> Same component, different values. - React scales for big apps. Small apps work with plain JavaScript. Large apps need structure. E-commerce, dashboards, chat apps. React keeps code organized. For tiny projects, plain JavaScript is fine. For larger user interface projects, React helps. It reduces your manual work. It prevents common errors. It grows with your project. Source: https://lnkd.in/gqedqJpf
To view or add a comment, sign in
-
𝗧𝗵𝗶𝘀 𝗾𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝗿𝗲𝘃𝗲𝗮𝗹𝘀 𝗶𝗳 𝘆𝗼𝘂 𝘂𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱 𝗮𝘀𝘆𝗻𝗰 𝗽𝗮𝘁𝘁𝗲𝗿𝗻𝘀 𝗱𝗲𝗲𝗽𝗹𝘆 𝗹𝗶𝗸𝗲 𝗮 𝘀𝗲𝗻𝗶𝗼𝗿 𝗱𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿... ASKED : 𝗗𝗲𝘀𝗶𝗴𝗻 𝗮 𝗿𝗮𝘁𝗲 𝗹𝗶𝗺𝗶𝘁𝗲𝗿 𝗶𝗻 𝘁𝗵𝗲 𝗳𝗿𝗼𝗻𝘁𝗲𝗻𝗱. The candidate was confident. Strong JavaScript knowledge. Years of React experience. They started typing immediately. Created a counter. Checked if counter was below 5. Made the API call. Reset counter every second. Shipped it to production in their mind. Then I asked: "𝗪𝗵𝗮𝘁 𝗵𝗮𝗽𝗽𝗲𝗻𝘀 𝗶𝗳 𝟭𝟬 𝗿𝗲𝗾𝘂𝗲𝘀𝘁𝘀 𝗰𝗼𝗺𝗲 𝗶𝗻 𝗮𝘁 𝗲𝘅𝗮𝗰𝘁𝗹𝘆 𝘁𝗵𝗲 𝘀𝗮𝗺𝗲 𝗺𝗶𝗹𝗹𝗶𝘀𝗲𝗰𝗼𝗻𝗱?" Complete Silence!!! 𝗟𝗲𝘁𝘀 𝘀𝗲𝗲 𝘁𝗵𝗲 𝗻𝗮𝗶𝘃𝗲 𝗮𝗽𝗽𝗿𝗼𝗮𝗰𝗵 𝗲𝘃𝗲𝗿𝘆𝗼𝗻𝗲 𝘁𝗿𝗶𝗲𝘀 𝗳𝗶𝗿𝘀𝘁: Track requests, allow if under limit, reset counter every second. Sounds fine. It’s not. 𝗪𝗵𝗮𝘁 𝗯𝗿𝗲𝗮𝗸𝘀: • Multiple requests in the same tick bypass the check • Boundary issue → 10 requests in milliseconds • No queue → dropped requests, bad UX 𝗧𝗵𝗲 𝗮𝗽𝗽𝗿𝗼𝗮𝗰𝗵𝗲𝘀 𝘁𝗵𝗮𝘁 𝘀𝗵𝗼𝘄 𝘂𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴: Token Bucket Algorithm: Start with 5 tokens. Each request consumes a token. Tokens refill at a steady rate. Allows bursts while maintaining average rate. Handles timing edge cases gracefully. 𝟭 - 𝗦𝗹𝗶𝗱𝗶𝗻𝗴 𝗪𝗶𝗻𝗱𝗼𝘄: Track timestamps of last N requests. New request checks if oldest request was within the window. Slide the window forward. More precise than fixed windows but requires storing request history. 𝟮 - 𝗤𝘂𝗲𝘂𝗲-𝗯𝗮𝘀𝗲𝗱 𝗮𝗽𝗽𝗿𝗼𝗮𝗰𝗵: Requests go into a queue. Process queue with delays between items to maintain rate. Ensures no requests are lost, provides feedback on position, handles backpressure. 𝗪𝗵𝗮𝘁 𝘆𝗼𝘂 𝘀𝗵𝗼𝘂𝗹𝗱 𝗮𝘀𝗸 𝗶𝗻𝘀𝘁𝗲𝗮𝗱 : "I need to clarify requirements first. What happens to requests exceeding the limit - do we queue, reject, or retry? Do we need user feedback? Is this per-API-endpoint or global? Then I'd implement a token bucket for smooth rate control with a queue for overflow requests, providing clear feedback to users about rate limit status." 𝗣𝗿𝗼𝗱𝘂𝗰𝘁𝗶𝗼𝗻 𝗰𝗼𝗻𝘀𝗶𝗱𝗲𝗿𝗮𝘁𝗶𝗼𝗻𝘀: • Background tabs → timers get throttled • Multiple tabs → per-tab or per-user? (sync needed) • User feedback → show quota, wait time, or disable actions • Retries → avoid retry storms after reset 𝗥𝗲𝗮𝗹-𝘄𝗼𝗿𝗹𝗱 𝘂𝘀𝗲 𝗰𝗮𝘀𝗲𝘀: • Search autocomplete → prevent API overload • File uploads → avoid browser/server stress • Real-time data → control request spikes • Shared API client → centralized rate limiting Rate limiting, async patterns, race conditions, queue management, the JavaScript execution model, these aren’t just interview topics.
To view or add a comment, sign in
-
-
𝗥𝗲𝗮𝗰𝘁 𝘃𝘀 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: 𝗪𝗵𝘆 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀 𝗣𝗿𝗲𝗳𝗲𝗿 𝗥𝗲𝗮𝗰𝘁 𝗳𝗼𝗿 𝗨𝗜 𝗣𝗿𝗼𝗷𝗲𝗰𝘁𝘀 Have you built a small app? Maybe a calculator or to-do list. You might see it feels harder in plain JavaScript. But in React, it feels easier. Why? React uses JavaScript. So how is it easier? Let me explain simply. In JavaScript, you control everything. In React, you describe what you want. React handles the rest. Think about building a calculator. With JavaScript, you: - Select buttons with getElementById. - Add event listeners to each button. - Store values like current number and operator. - Update the display yourself. - Handle edge cases like clear and delete. You do two jobs. You handle calculations. You update the screen. This is why it feels complex. With React, you: - Create components like Button and Display. - Store values in state. - Update state on click. - React updates the UI automatically. You only focus on your data. React does the rest. Why does React feel easier? Components give clean structure. In React, Display and Buttons are separate parts. In JavaScript, everything mixes together. State makes data management easy. React uses state for changing values. When state changes, the UI updates. In JavaScript, you update variables and the UI separately. No manual DOM work. In JavaScript, you use document.getElementById. In React, you update state. React updates the UI. This saves effort. Reusability is easy. You can use a Button component many times with different values. For bigger projects, React helps. Small apps are fine with JavaScript. But for e-commerce, dashboards, or chat apps, React keeps things organized. So, for UI projects, many developers prefer React. It simplifies the work. Source: https://lnkd.in/gqedqJpf
To view or add a comment, sign in
-
#js #8 **Why JavaScript Is Single Threaded Synchronous Language** 🧠 Statement: 👉 “JavaScript is single-threaded and synchronous” We’ll break this into parts so it’s easy to understand. 🧵 1. What is Single-Threaded? 👉 JavaScript has only ONE main thread That means: One call stack One task at a time Example: console.log("A"); console.log("B"); console.log("C"); 👉 Output: A B C ✔ It runs one by one, not in parallel. ⚙️ Why JavaScript is single-threaded? Originally designed for browsers. Browsers (like Google Chrome) need to: Update UI Handle clicks 👉 If multiple threads changed UI at same time: UI would break Data would be inconsistent ✔ So JavaScript uses one thread → safe & predictable ⏱️ 2. What is Synchronous? 👉 Synchronous means: Code runs line by line, and each line waits for previous one to finish Example: console.log("Start"); function slowTask() { for (let i = 0; i < 1; i++) {} } slowTask(); console.log("End"); 👉 Output: Start End (after delay) ✔ End waits until slowTask finishes 🔴 Problem with synchronous nature If something takes time: Everything stops ⛔ UI freezes 👉 Bad user experience 🔄 3. Then how does JavaScript handle async? Here’s the important twist 👇 👉 JavaScript is: ✔ Single-threaded ✔ Synchronous (by default) ❗ BUT supports async using system outside JS 🌐 Behind the scenes JavaScript uses: Browser APIs Event system → Event Loop 📦 Example console.log("Start"); setTimeout(() => { console.log("Async"); }, 2000); console.log("End"); 🔄 Execution flow Start → runs setTimeout → sent to browser End → runs immediately After 2 sec → callback comes back Event loop executes it Output: Start End Async 👉 So JS looks async, but actually: It delegates work Still runs one task at a time 🧑🍳 Simple analogy You (JS) 👨🍳: Cook one dish at a time (single-threaded) Follow order (synchronous) Ask assistant to do waiting tasks (async) 👉 JavaScript is: ✔ Single-threaded One task at a time ✔ Synchronous (by default) Executes line by line ✔ Non-blocking (with help) Uses event loop + browser APIs 👉 JavaScript is single-threaded and synchronous, but uses the event loop to handle asynchronous operations without blocking execution. #Javascript #ObjectOrientedProgramming #SoftwareDevelopment
To view or add a comment, sign in
-
#js #18 **Spread and Rest Operator** Spread (...) and Rest (...) look the same in JavaScript, but they do opposite jobs depending on where you use them. 🔹 1. Spread Operator (...) 👉 Expands (unpacks) elements Used when you want to take values out of an array/object ✅ Examples 📌 Array Spread const arr1 = [1, 2, 3];const arr2 = [...arr1, 4, 5];console.log(arr2); // [1, 2, 3, 4, 5] 📌 Copy Array (Important ⚠️) const original = [1, 2, 3]; const copy = [...original]; copy.push(4); console.log(original); // [1, 2, 3] console.log(copy); // [1, 2, 3, 4] 👉 Avoids reference issues (unlike direct assignment) 📌 Merge Arrays const a = [1, 2]; const b = [3, 4]; const merged = [...a, ...b]; 📌 Object Spread const user = { name: "Navnath", age: 28 }; const updated = { ...user, city: "Nagpur" }; 📌 Function Arguments const nums = [1, 2, 3]; function sum(a, b, c) { return a + b + c;} sum(...nums); // 6 🔹 2. Rest Operator (...) 👉 Collects (packs) elements into one Used when you want to gather multiple values into a single variable ✅ Examples 📌 Function Parameters function sum(...numbers) { return numbers.reduce((acc, curr) => acc + curr, 0);} sum(1, 2, 3, 4); // 10 👉 numbers becomes an array 📌 Array Destructuring const arr = [1, 2, 3, 4]; const [first, ...rest] = arr; console.log(first); // 1 console.log(rest); // [2, 3, 4] 📌 Object Destructuring const user = { name: "Navnath", age: 28, city: "Nagpur"}; const { name, ...others } = user; console.log(name); // Navnath console.log(others); // { age: 28, city: "Nagpur" } key difference: | Feature | Spread (`...`) | Rest (`...`) | | ---------- | ---------------- | --------------- | | Purpose | Expand values | Collect values | | Usage side | Right side (RHS) | Left side (LHS) | | Example | `[...arr]` | `[a, ...rest]` | 🧠 Easy Way to Remember Spread → “Break it” (expand) Rest → “Collect it” (gather) ⚠️ Common Mistake const obj = { a: 1, b: 2 }; const newObj = { ...obj, a: 10 }; 👉 Output: { a: 10, b: 2 } ✔️ Last value overrides previous ones #Javascript #ObjectOrientedProgramming #SoftwareDevelopment
To view or add a comment, sign in
-
#js #15 **This Keyword** In JavaScript, the this keyword refers to the context in which a function is executed—basically, “who is calling this function.” But unlike many other languages, this in JavaScript is dynamic (it changes depending on how the function is called, not where it’s written). 🔹 1. Global Context In the global scope: console.log(this); In browsers → window In Node.js → global (or {} in strict modules) 🔹 2. Inside an Object Method When used inside an object: const person = { name: "Alice", greet() { console.log(this.name); } }; person.greet(); // Alice 👉 this refers to the object calling the method (person). 🔹 3. Inside a Regular Function function show() { console.log(this); } show(); Non-strict mode → window Strict mode → undefined 🔹 4. Arrow Functions (Important ⚠️) Arrow functions do NOT have their own this. They inherit it from the surrounding (lexical) scope. const obj = { name: "Bob", greet: () => { console.log(this.name); } }; obj.greet(); // undefined 👉 Here, this is NOT obj, it’s from the outer scope. 🔹 5. Event Handlers button.addEventListener("click", function () { console.log(this); // the button }); 👉 this refers to the element that triggered the event 🔹 6. Constructor Functions / Classes function Person(name) { this.name = name; } const p = new Person("John"); console.log(p.name); // John 👉 this refers to the newly created object 🔹 7. Explicit Binding (call, apply, bind) You can manually set this: function greet() { console.log(this.name); } const user = { name: "Emma" }; greet.call(user); // Emma Summary: | Situation | `this` refers to | | ------------------- | --------------------------- | | Global scope | Global object | | Object method | The object | | Regular function | Global / undefined (strict) | | Arrow function | Lexical (outer) `this` | | Constructor (`new`) | New instance | | Event handler | Element triggering event | | `call/apply/bind` | Explicitly set value | #Javascript #ObjectOrientedProgramming #SoftwareDevelopment
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