Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

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

Tag: JavaScript Tips

Ajax

Ajax: Stop One Slow Endpoint From Blocking Every Other Request on the Page

- 31.08.26 | 31.08.26 - ErcanOPAK comment on Ajax: Stop One Slow Endpoint From Blocking Every Other Request on the Page

🔄 One Slow Call Is Freezing Your Whole Page A dashboard that loads three widgets, each with its own Ajax call, can end up waiting for the SLOWEST one before showing anything — if those calls are written sequentially with await one after another instead of running in parallel. 🐞 The Problem async function loadDashboard() […]

Read More
JavaScript

JavaScript: Why localStorage Silently Throws in Private Browsing Mode

- 31.08.26 | 31.08.26 - ErcanOPAK comment on JavaScript: Why localStorage Silently Throws in Private Browsing Mode

⚡ localStorage Isn’t Always There — Code Like It Might Not Be Code that calls localStorage.setItem() directly works perfectly in normal testing, then throws an uncaught exception and breaks the whole page for users in Safari’s Private Browsing mode, some locked-down corporate browsers, or with storage explicitly disabled. 🐞 The Problem function saveDraft(text) { localStorage.setItem(‘draft’, […]

Read More
JavaScript

JavaScript: Why Array.sort() Turns Your Numbers Into Strings and Wrecks the Order

- 30.08.26 | 31.08.26 - ErcanOPAK comment on JavaScript: Why Array.sort() Turns Your Numbers Into Strings and Wrecks the Order

⚡ sort() Isn’t Sorting Numbers the Way You Think Calling .sort() on an array of numbers with no arguments doesn’t sort numerically — it converts every number to a string first and compares them alphabetically, and nothing throws an error to warn you it happened. 🐞 The Problem const values = [10, 1, 2, 21, […]

Read More
Ajax

Ajax: Stop Race Conditions From Showing Stale Search Results With AbortController

- 30.08.26 | 31.08.26 - ErcanOPAK comment on Ajax: Stop Race Conditions From Showing Stale Search Results With AbortController

🔄 Fast Typing = Wrong Search Results A live search box that fires a request per keystroke can show results for an OLD query if that request happens to finish after the newest one — a network race condition, not a UI bug, and debouncing alone doesn’t fully fix it. 🐞 The Problem input.addEventListener(‘input’, async […]

Read More
JavaScript

JavaScript: Why a Forgotten clearInterval() Is Silently Draining Your Users’ Battery

- 30.08.26 | 31.08.26 - ErcanOPAK comment on JavaScript: Why a Forgotten clearInterval() Is Silently Draining Your Users’ Battery

⚡ Missing clearInterval = Battery Drain A setInterval started when a component/page section mounts and never explicitly stopped keeps running in the background forever — even after the UI it was updating is gone — quietly burning CPU and battery on every device that ever visited the page. 🐞 The Problem function startLiveClock() { setInterval(() […]

Read More
Ajax

Ajax: Stop Double Form Submissions From Firing Duplicate Requests — Debounce and AbortController Explained

- 30.08.26 - ErcanOPAK comment on Ajax: Stop Double Form Submissions From Firing Duplicate Requests — Debounce and AbortController Explained

🔄 One Disable = No Duplicate Orders A user double-clicks “Submit” or clicks fast on a slow connection, and your Ajax call fires twice — creating two orders, two payments, or two database rows. This is one of the most common (and expensive) bugs in web forms. 🐞 The Problem document.getElementById(“payBtn”).addEventListener(“click”, function () { $.ajax({ […]

Read More
JavaScript

JavaScript: Why == Silently Breaks Comparisons — And Why === Isn’t Even the Full Fix

- 30.08.26 - ErcanOPAK comment on JavaScript: Why == Silently Breaks Comparisons — And Why === Isn’t Even the Full Fix

⚡ == Lies, === Doesn’t An if-statement that should never pass, passes. A bug ships to production because 0 == “” is somehow true. JavaScript’s loose equality performs invisible type coercion, and most developers only half-understand the rule. 🐞 The Problem console.log(0 == “”); // true — string coerced to number console.log(0 == “0”); // […]

Read More
JavaScript

JavaScript Event Delegation: Master Efficient Event Handling

- 29.08.26 - ErcanOPAK comment on JavaScript Event Delegation: Master Efficient Event Handling

⚡ Key Insights: Event delegation attaches one listener to a parent element, handling events for all children. Saves memory and handles dynamic elements. Adding event listeners to every element is inefficient. Event Delegation is the solution. ❌ The Problem – Many Listeners // ❌ Adds listener to EVERY button document.querySelectorAll(‘button’).forEach(button => { button.addEventListener(‘click’, handleClick); }); […]

Read More
JavaScript

JavaScript Async/Await: Complete Guide to Clean Promise Chains

- 19.08.26 - ErcanOPAK comment on JavaScript Async/Await: Complete Guide to Clean Promise Chains

Stop the callback hell and promise pyramid! Async/await makes asynchronous JavaScript code look synchronous and maintainable. Step 1: The Problem – Promise Chains // ❌ Callback Hell getUser(1, (user) => { getOrders(user.id, (orders) => { getOrderDetails(orders[0].id, (details) => { processOrder(details, (result) => { console.log(‘Done!’, result); }); }); }); }); // ❌ Promise Pyramid getUser(1) .then(user […]

Read More
JavaScript

JavaScript: Use Destructuring to Extract Values Cleanly

- 30.03.26 - ErcanOPAK comment on JavaScript: Use Destructuring to Extract Values Cleanly

📦 Unpack Like Python Accessing nested properties? const x = obj.prop.nested? Verbose. Destructuring extracts values from objects and arrays elegantly. One line replaces five. Object Destructuring const user = { name: ‘Alice’, age: 30, email: ‘alice@example.com’, address: { city: ‘New York’, country: ‘USA’ } }; // ❌ Old way const name = user.name; const age […]

Read More
JavaScript

JavaScript: Use Destructuring to Extract Values Elegantly

- 22.03.26 - ErcanOPAK comment on JavaScript: Use Destructuring to Extract Values Elegantly

📦 Unpack Data Like a Pro Accessing nested properties? Writing obj.prop.subprop.value? Destructuring extracts values in one line. Object Destructuring // ❌ Old way: Repetitive const user = { name: ‘John’, age: 30, email: ‘john@example.com’ }; const name = user.name; const age = user.age; const email = user.email; // ✅ Destructuring: One line const { name, […]

Read More
JavaScript

JavaScript: Use Optional Chaining (?.) to Avoid Nested If Checks

- 19.03.26 - ErcanOPAK comment on JavaScript: Use Optional Chaining (?.) to Avoid Nested If Checks

🔗 Access Deep Properties Safely Tired of user && user.address && user.address.city? Optional chaining makes it user?.address?.city The Old Nightmare // ❌ Verbose null checking const city = user && user.address && user.address.city; // ❌ Even worse with functions const result = obj && obj.method && obj.method(); // ❌ Nested ternaries const name = data […]

Read More
JavaScript

JavaScript: Use structuredClone for Deep Object Copy

- 19.03.26 | 19.03.26 - ErcanOPAK comment on JavaScript: Use structuredClone for Deep Object Copy

Deep cloning objects? JSON.parse(JSON.stringify()) fails on dates, functions, undefined. // ❌ Old way (loses dates, functions) const copy = JSON.parse(JSON.stringify(original)); // ✅ New way (preserves everything) const copy = structuredClone(original); // Works with: // – Nested objects // – Arrays // – Dates // – Maps, Sets // – RegExp // – ArrayBuffer Performance: Faster […]

Read More
JavaScript

JavaScript: Use AbortController to Cancel Fetch Requests

- 19.03.26 | 19.03.26 - ErcanOPAK comment on JavaScript: Use AbortController to Cancel Fetch Requests

🛑 Cancel In-Flight Requests User navigates away mid-request. Old request completes, updates wrong page. Prevent this. const controller = new AbortController(); fetch(‘/api/data’, { signal: controller.signal }) .then(res => res.json()) .catch(err => { if (err.name === ‘AbortError’) { console.log(‘Request cancelled’); } }); // User navigates away controller.abort(); // Cancels request React Hook: Use in useEffect cleanup. […]

Read More
JavaScript

JavaScript: Use globalThis for Universal Global Object Access

- 22.02.26 - ErcanOPAK comment on JavaScript: Use globalThis for Universal Global Object Access

Accessing global object is different everywhere: window (browser), global (Node), self (workers). globalThis works everywhere. The Problem: // Browser window.myVar = ‘test’; // Works // Node.js global.myVar = ‘test’; // Works // Web Worker self.myVar = ‘test’; // Works Universal Solution: globalThis.myVar = ‘test’; // Works everywhere! Write once, run in browser, Node, workers, Deno […]

Read More
JavaScript

JavaScript: Use IntersectionObserver for Efficient Scroll-Based Animations

- 21.02.26 - ErcanOPAK comment on JavaScript: Use IntersectionObserver for Efficient Scroll-Based Animations

Checking scroll position with addEventListener(‘scroll’) causes performance issues. IntersectionObserver is efficient and built-in. Detect When Element Enters Viewport: const observer = new IntersectionObserver(entries => { entries.forEach(entry => { if (entry.isIntersecting) { entry.target.classList.add(‘animate-in’); observer.unobserve(entry.target); // Only animate once } }); }); // Observe all elements you want to animate document.querySelectorAll(‘.fade-in-on-scroll’).forEach(el => { observer.observe(el); }); With Threshold: […]

Read More
JavaScript

JavaScript: Use WeakMap for Private Class Data Without Symbols

- 17.02.26 - ErcanOPAK comment on JavaScript: Use WeakMap for Private Class Data Without Symbols

Private class fields with # work but WeakMap provides better encapsulation and no memory leaks. Private Fields Approach: class Counter { #count = 0; // Private increment() { this.#count++; } get value() { return this.#count; } } WeakMap Approach: const _private = new WeakMap(); class Counter { constructor() { _private.set(this, { count: 0, history: [] […]

Read More
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 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 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 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
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
November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

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

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit
  • SQL Server: Fix ROW_NUMBER Ties Reordering Between Identical Runs
  • C#: Fix an Enum HasFlag Returning True for the Zero Value
  • WordPress: Fix Featured Images Vanishing After a CDN Migration
  • Photoshop: Fix Content-Aware Fill Smearing a Repeating Pattern
  • Asp.Net Core: Fix Antiforgery Tokens Rejected Behind a Reverse Proxy

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (981)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit

Social

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