Skip to content

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Category: JavaScript

JavaScript

JavaScript: Use Proxy to Create Reactive Objects Without Framework

- 16.02.26 - ErcanOPAK comment on JavaScript: Use Proxy to Create Reactive Objects Without Framework

Frameworks like Vue use Proxy for reactivity. You can too – update UI automatically when data changes. Basic Reactive Object: const data = { count: 0, name: ‘John’ }; const reactive = new Proxy(data, { set(target, property, value) { target[property] = value; // Update UI automatically document.getElementById(property).textContent = value; console.log(`${property} changed to ${value}`); return true; […]

Read More
JavaScript

JavaScript: Use AbortController to Cancel Multiple Requests at Once

- 15.02.26 - ErcanOPAK comment on JavaScript: Use AbortController to Cancel Multiple Requests at Once

Canceling multiple fetch requests individually is messy. One AbortController can cancel them all. Single Controller for Multiple Requests: const controller = new AbortController(); const signal = controller.signal; // Multiple requests with same signal const userRequest = fetch(‘/api/user’, { signal }); const ordersRequest = fetch(‘/api/orders’, { signal }); const settingsRequest = fetch(‘/api/settings’, { signal }); // […]

Read More
JavaScript

JavaScript: Use Nullish Coalescing (??) to Handle Only Null/Undefined

- 15.02.26 - ErcanOPAK comment on JavaScript: Use Nullish Coalescing (??) to Handle Only Null/Undefined

|| operator treats 0 and ” as falsy. ?? only checks null/undefined. Problem with ||: const count = 0; const display = count || 10; // Returns 10 (wrong!) // 0 is falsy, so falls back to 10 Solution with ??: const count = 0; const display = count ?? 10; // Returns 0 (correct!) […]

Read More
JavaScript

JavaScript: Use replaceAll() Instead of regex.replace() for Simple Text Replacement

- 14.02.26 - ErcanOPAK comment on JavaScript: Use replaceAll() Instead of regex.replace() for Simple Text Replacement

Replacing all occurrences with regex is overkill. replaceAll() is simpler and more readable. Old Regex Way: const text = “Hello World, Hello Universe”; const result = text.replace(/Hello/g, “Hi”); // “Hi World, Hi Universe” // Easy to mess up – forget ‘g’ flag and only first is replaced! New replaceAll() Way: const text = “Hello World, […]

Read More
JavaScript

JavaScript: Use structuredClone() to Deep Copy Objects

- 13.02.26 - ErcanOPAK comment on JavaScript: Use structuredClone() to Deep Copy Objects

JSON.parse(JSON.stringify()) is clunky and breaks on Dates/Functions. Use structuredClone() instead. Old Unreliable Way: const original = { name: ‘John’, date: new Date() }; const copy = JSON.parse(JSON.stringify(original)); console.log(copy.date); // String, not Date! ❌ New Built-In Way: const original = { name: ‘John’, date: new Date(), nested: { deep: { value: 42 } } }; const […]

Read More
JavaScript

JavaScript: Use Array.at() to Access Array Elements from End

- 13.02.26 - ErcanOPAK comment on JavaScript: Use Array.at() to Access Array Elements from End

Getting last array element with arr[arr.length – 1] is verbose. Use .at() instead. Old Way: const arr = [10, 20, 30, 40, 50]; const last = arr[arr.length – 1]; // 50 const secondLast = arr[arr.length – 2]; // 40 New Way: const last = arr.at(-1); // 50 const secondLast = arr.at(-2); // 40 const first […]

Read More
JavaScript

JavaScript Fetch API Secret: How AbortController Stops Memory Leaks in Single Page Apps

- 05.02.26 - ErcanOPAK comment on JavaScript Fetch API Secret: How AbortController Stops Memory Leaks in Single Page Apps

Single Page Applications leaking memory from unfinished fetch requests? AbortController is your solution to clean up abandoned API calls. The Memory Leak Problem: // Common React/Vue pattern causing leaks async function fetchUserData(userId) { const response = await fetch(`/api/users/${userId}`); const data = await response.json(); setUserData(data); // State update } // User clicks between tabs quickly: // […]

Read More
JavaScript

JavaScript: Use Optional Chaining to Prevent ‘Cannot Read Property of Undefined’ Errors

- 03.02.26 - ErcanOPAK comment on JavaScript: Use Optional Chaining to Prevent ‘Cannot Read Property of Undefined’ Errors

Your app crashes with “Cannot read property ‘name’ of undefined”? Optional chaining (?.) safely accesses nested properties without try-catch blocks. The Error-Prone Old Way: const user = getUserData(); // Might return null // ❌ This crashes if user is null/undefined const name = user.profile.name; // TypeError: Cannot read property ‘profile’ of undefined // ❌ Traditional […]

Read More
Ajax / JavaScript

Handle AJAX Errors Properly: Retry Logic with Exponential Backoff

- 01.02.26 | 01.02.26 - ErcanOPAK comment on Handle AJAX Errors Properly: Retry Logic with Exponential Backoff

Your AJAX calls fail randomly due to network hiccups or server load? Implement smart retry logic that actually works. The Problem with Basic Retry: // Bad: Immediate retry can make things worse function badRetry(url, maxAttempts) { for (let i = 0; i < maxAttempts; i++) { try { return await fetch(url); } catch (error) { […]

Read More
JavaScript

Debounce vs Throttle in JavaScript: When to Use Which (With Real Examples)

- 01.02.26 | 01.02.26 - ErcanOPAK comment on Debounce vs Throttle in JavaScript: When to Use Which (With Real Examples)

Search inputs lagging? Scroll events killing performance? Understanding debounce vs throttle is critical for responsive UIs. Debounce – Wait Until User Stops: function debounce(func, delay) { let timeoutId; return function(…args) { clearTimeout(timeoutId); timeoutId = setTimeout(() => { func.apply(this, args); }, delay); }; } // Usage: Search input const searchInput = document.getElementById(‘search’); const performSearch = debounce((query) […]

Read More
JavaScript

Why forEach Can Be Slower Than for (And When It Matters)

- 31.01.26 - ErcanOPAK comment on Why forEach Can Be Slower Than for (And When It Matters)

This is NOT about micro-optimizations.It’s about callback overhead. Example items.forEach(item => process(item)); vs for (let i = 0; i < items.length; i++) { process(items[i]); } Why forEach creates a function call per iteration Harder for JS engines to optimize No early break support When it matters Large arrays Hot paths Real-time processing Rule Readability first.But […]

Read More
Ajax / JavaScript

Why AJAX Requests Randomly Fail Under Load

- 30.01.26 - ErcanOPAK comment on Why AJAX Requests Randomly Fail Under Load

Works locally. Fails in production. Hidden issue Browsers limit parallel connections per origin. Fix Batch requests Use request queues Prefer a single endpoint await Promise.allSettled(requests); Why Uncontrolled parallelism = dropped requests.

Read More
JavaScript

Why Array.forEach() Breaks Async Logic (Silently)

- 30.01.26 - ErcanOPAK comment on Why Array.forEach() Breaks Async Logic (Silently)

This bug survives code reviews way too often. Problem forEach does not await async callbacks. items.forEach(async item => { await save(item); }); This exits immediately. Errors may never surface. Correct for (const item of items) { await save(item); } Why it matters Async flow control must be explicit, not assumed.

Read More
Ajax / JavaScript

Why Fetch Requests “Randomly” Hang (But Server Is Fine)

- 29.01.26 - ErcanOPAK comment on Why Fetch Requests “Randomly” Hang (But Server Is Fine)

AJAX requests stall… server logs show nothing. Hidden reason Browsers limit parallel connections per origin (usually 6). When it happens Long-polling Hanging fetch calls Images + API calls from same domain Fix Abort unused requests Use AbortController const controller = new AbortController(); fetch(url, { signal: controller.signal }); // later controller.abort();  

Read More
JavaScript

Why setTimeout(fn, 0) Is NOT Immediate (And Breaks Logic)

- 29.01.26 - ErcanOPAK comment on Why setTimeout(fn, 0) Is NOT Immediate (And Breaks Logic)

Many developers assume setTimeout(fn, 0) runs instantly.It never does. Why JavaScript has a single-threaded event loop setTimeout callbacks go to the macrotask queue Rendering, promises, microtasks run first console.log(‘A’); setTimeout(() => console.log(‘B’), 0); Promise.resolve().then(() => console.log(‘C’)); console.log(‘D’); Output A D C B Impact Race conditions UI glitches Unexpected async order Fix Use microtasks when order […]

Read More
Ajax / JavaScript

Ajax — Always Set Timeouts

- 28.01.26 - ErcanOPAK comment on Ajax — Always Set Timeouts

$.ajax({ timeout: 5000 }); Why it mattersPrevents hanging UI states.

Read More
JavaScript

structuredClone() Beats JSON Hacks

- 28.01.26 - ErcanOPAK comment on structuredClone() Beats JSON Hacks

const copy = structuredClone(obj); Why it mattersHandles Dates, Maps, Sets safely.

Read More
Ajax / JavaScript

Throttle Requests to Save Backend

- 27.01.26 - ErcanOPAK comment on Throttle Requests to Save Backend

let timeout; input.oninput = () => { clearTimeout(timeout); timeout = setTimeout(sendRequest, 300); }; Why it mattersLess load, better UX.

Read More
JavaScript

Use AbortController to Cancel Requests

- 27.01.26 - ErcanOPAK comment on Use AbortController to Cancel Requests

const controller = new AbortController(); fetch(url, { signal: controller.signal }); controller.abort(); Why it mattersPrevents race conditions and wasted bandwidth.

Read More
Ajax / JavaScript

Send JSON the Right Way

- 26.01.26 - ErcanOPAK comment on Send JSON the Right Way

fetch(url, { method: “POST”, headers: { “Content-Type”: “application/json” }, body: JSON.stringify(data) }); Why it mattersAvoids silent model binding failures.

Read More
JavaScript

Use requestIdleCallback for Background Tasks

- 26.01.26 | 26.01.26 - ErcanOPAK comment on Use requestIdleCallback for Background Tasks

requestIdleCallback(() => heavyWork()); Why it mattersRuns tasks without blocking UI.

Read More
Ajax / JavaScript

Abort Fetch Requests to Prevent UI Race Conditions

- 25.01.26 | 25.01.26 - ErcanOPAK comment on Abort Fetch Requests to Prevent UI Race Conditions

Multiple rapid requests = stale UI updates. const controller = new AbortController(); fetch(url, { signal: controller.signal }); controller.abort(); Why this mattersPrevents outdated responses from overwriting newer state.  

Read More
JavaScript

Why structuredClone() Beats JSON Deep Copy

- 25.01.26 - ErcanOPAK comment on Why structuredClone() Beats JSON Deep Copy

Why structuredClone() Beats JSON Deep Copy const copy = structuredClone(original); Why this mattersstructuredClone preserves complex types and avoids silent data corruption.

Read More
Ajax / JavaScript

Stop Using JSON for Everything — Sometimes HTML Is Faster

- 24.01.26 - ErcanOPAK comment on Stop Using JSON for Everything — Sometimes HTML Is Faster

Returning pre-rendered HTML via Ajax can outperform JSON → DOM rebuild. fetch(‘/comments’) .then(r => r.text()) .then(html => container.innerHTML = html); Why this worksLess JS work, fewer reflows, simpler rendering.

Read More
JavaScript

The Real Difference Between debounce and throttle

- 24.01.26 - ErcanOPAK comment on The Real Difference Between debounce and throttle

Misusing these kills UX and performance. // Debounce: waits until user stops debounce(search, 300); // Throttle: runs at most once per interval throttle(scrollHandler, 200); Why it mattersSearch inputs want debounce. Scroll/resize want throttle.

Read More
JavaScript

Why forEach Breaks Async Logic (and How to Fix It)

- 24.01.26 - ErcanOPAK comment on Why forEach Breaks Async Logic (and How to Fix It)

Array.forEach() does not await async functions.This silently causes race conditions and partial execution. // ❌ This does NOT wait items.forEach(async item => { await process(item); }); // ✅ Correct for (const item of items) { await process(item); } Why this mattersforEach ignores promises. Errors get swallowed, execution order breaks.

Read More
Ajax / JavaScript

Ajax Requests Succeed but UI Never Updates

- 23.01.26 - ErcanOPAK comment on Ajax Requests Succeed but UI Never Updates

Network OK, UI frozen. Why it happensState updated outside render cycle. Why it mattersUsers see stale data. Vital fix Centralize state updates.

Read More
JavaScript

JavaScript Objects Grow Memory Over Time

- 23.01.26 - ErcanOPAK comment on JavaScript Objects Grow Memory Over Time

No leaks visible. Why it happensDetached DOM references. Why it mattersLong sessions slow down. Vital fix Null references explicitly.

Read More
JavaScript

JavaScript Timers Drift Over Time

- 22.01.26 - ErcanOPAK comment on JavaScript Timers Drift Over Time

Intervals lose accuracy. Why it happenssetInterval stacks delays. Why it mattersAnimations and polling drift. Smart fixUse recursive setTimeout.

Read More
JavaScript

JavaScript Memory Grows Without Errors

- 21.01.26 - ErcanOPAK comment on JavaScript Memory Grows Without Errors

No crash, slow death. Why it happensDetached DOM references. Why it mattersLong-running apps degrade silently. Smart fixClear references on element removal. element = null;  

Read More
Page 1 of 5
1 2 3 4 5 Next »

Posts navigation

Older posts
February 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
232425262728  
« Jan    

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (935)
  • How to add default value for Entity Framework migrations for DateTime and Bool (831)
  • Get the First and Last Word from a String or Sentence in SQL (825)
  • How to select distinct rows in a datatable in C# (799)
  • How to make theater mode the default for Youtube (713)
  • Add Constraint to SQL Table to ensure email contains @ (573)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (552)
  • Average of all values in a column that are not zero in SQL (519)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (474)
  • Find numbers with more than two decimal places in SQL (436)

Recent Posts

  • C#: Use ArgumentNullException.ThrowIfNull for Cleaner Validation
  • C#: Use Discard Pattern to Ignore Unwanted Values
  • C#: Use Deconstruction with Tuples for Cleaner Multiple Returns
  • C#: Use File-Scoped Types to Limit Class Visibility
  • SQL: Use PIVOT to Transform Rows into Columns
  • SQL: Use MERGE OUTPUT to Track What Changed During Upsert
  • .NET Core: Use Polly for Resilient HTTP Requests with Retry Logic
  • .NET Core: Use Dapper for Lightweight ORM Alternative to Entity Framework
  • Git: Use git sparse-checkout to Clone Only Specific Folders
  • Git: Use git switch and git restore Instead of Confusing git checkout

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (935)
  • How to add default value for Entity Framework migrations for DateTime and Bool (831)
  • Get the First and Last Word from a String or Sentence in SQL (825)
  • How to select distinct rows in a datatable in C# (799)
  • How to make theater mode the default for Youtube (713)

Recent Posts

  • C#: Use ArgumentNullException.ThrowIfNull for Cleaner Validation
  • C#: Use Discard Pattern to Ignore Unwanted Values
  • C#: Use Deconstruction with Tuples for Cleaner Multiple Returns
  • C#: Use File-Scoped Types to Limit Class Visibility
  • SQL: Use PIVOT to Transform Rows into Columns

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com