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 console.table to Display Arrays as Tables

- 07.06.26 - ErcanOPAK comment on JavaScript: Use console.table to Display Arrays as Tables

๐Ÿ“Š console.log() is Messy for Arrays Array of objects logs as expandable tree. console.table() displays as formatted table. Much easier to read. ๐Ÿ“ Basic Usage const users = [ { id: 1, name: ‘Alice’, email: ‘alice@example.com’ }, { id: 2, name: ‘Bob’, email: ‘bob@example.com’ }, { id: 3, name: ‘Charlie’, email: ‘charlie@example.com’ } ]; console.table(users); […]

Read More
JavaScript

JavaScript: Use ?? Instead of || for Default Values

- 07.06.26 - ErcanOPAK comment on JavaScript: Use ?? Instead of || for Default Values

|| treats 0, ”, false as falsy. ?? only checks null/undefined. Default values with || break when value is 0. Nullish coalescing (??) fixes this. Use ?? for default values. โŒ || (Bug with 0) const volume = userVolume || 50; // If userVolume = 0 โ†’ volume = 50 (WRONG!) const name = userName […]

Read More
JavaScript

JavaScript: Use Labeled Statements to Break Outer Loops

- 06.06.26 - ErcanOPAK comment on JavaScript: Use Labeled Statements to Break Outer Loops

๐Ÿท๏ธ break only breaks inner loop Need to exit nested loops? Labeled statements break or continue outer loops. Perfect for search in matrix. โŒ Without Label (Cannot break outer) for (let i = 0; i < 10; i++) { for (let j = 0; j < 10; j++) { if (found) { break; // Only […]

Read More
JavaScript

JavaScript: Use Object.groupBy to Group Arrays Without Lodash

- 06.06.26 - ErcanOPAK comment on JavaScript: Use Object.groupBy to Group Arrays Without Lodash

๐Ÿ“Š _.groupBy() is Finally Native Grouping arrays required Lodash or manual reduce. Object.groupBy() is native. No more dependencies. ๐Ÿ“ Basic GroupBy const users = [ { name: ‘Alice’, role: ‘admin’ }, { name: ‘Bob’, role: ‘user’ }, { name: ‘Charlie’, role: ‘admin’ } ]; const byRole = Object.groupBy(users, user => user.role); // { // admin: […]

Read More
JavaScript

JavaScript: Use Error Cause for Better Error Chains

- 06.06.26 - ErcanOPAK comment on JavaScript: Use Error Cause for Better Error Chains

๐Ÿ”— Don’t Lose the Original Error Throwing new Error() loses original stack. Error cause chains errors. See full context. ๐Ÿ“ Without Error Cause (Lost Context) try { await fetchUser(userId); } catch (err) { throw new Error(`Failed to get user ${userId}`); // Original error stack lost! } โœ… With Error Cause (Full Context) try { await […]

Read More
JavaScript

JavaScript: Use WeakRef and FinalizationRegistry to Prevent Memory Leaks

- 05.06.26 - ErcanOPAK comment on JavaScript: Use WeakRef and FinalizationRegistry to Prevent Memory Leaks

๐Ÿ—‘๏ธ Know When Objects Are Garbage Collected WeakMap is known. WeakRef and FinalizationRegistry give advanced memory management. Cache cleanup, resource release, memory leak detection. ๐Ÿ“ WeakRef Example let obj = { data: ‘important’ }; const weakRef = new WeakRef(obj); // Later, obj might be garbage collected obj = null; // Check if still alive const […]

Read More
JavaScript

JavaScript: Use import.meta to Get Module Information

- 05.06.26 - ErcanOPAK comment on JavaScript: Use import.meta to Get Module Information

โ„น๏ธ Know Your Module’s URL, Resolve Paths Need to load assets relative to current file? import.meta gives you module URL, hot reload status, and more. ๐Ÿ“ import.meta.url // main.js console.log(import.meta.url); // “file:///C:/project/src/main.js” (Node.js) // “https://example.com/js/main.js” (browser) // Get directory of current module const modulePath = new URL(‘.’, import.meta.url).pathname; // Load sibling file dynamically const data […]

Read More
JavaScript

JavaScript: Use Temporal API for Modern Date and Time Handling

- 31.05.26 - ErcanOPAK comment on JavaScript: Use Temporal API for Modern Date and Time Handling

๐Ÿ“… Finally, a Good Date API Date object is broken (months are 0-indexed, mutates, timezone issues). Temporal fixes everything. Immutable, timezone-aware, intuitive. ๐Ÿ“ Temporal Basics // Current date/time const now = Temporal.Now.zonedDateTimeISO(); // with timezone const today = Temporal.Now.plainDateISO(); // date only const time = Temporal.Now.plainTimeISO(); // time only // Create dates (months are 1-indexed!) […]

Read More
JavaScript

JavaScript: Use Atomics for Thread-Safe Shared Memory with Web Workers

- 31.05.26 - ErcanOPAK comment on JavaScript: Use Atomics for Thread-Safe Shared Memory with Web Workers

๐Ÿงต Multiple Threads, One Memory Web Workers communicate via message passing. SharedArrayBuffer + Atomics enables shared memory. No copying. True multithreading. ๐Ÿ“ Basic Shared Memory // Main thread const sharedBuffer = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * 2); const sharedArray = new Int32Array(sharedBuffer); sharedArray[0] = 0; // Counter const worker = new Worker(‘worker.js’); worker.postMessage(sharedBuffer); // Transfer, not copy! […]

Read More
JavaScript

JavaScript: Use Object.groupBy() to Group Arrays Without Lodash

- 30.05.26 - ErcanOPAK comment on JavaScript: Use Object.groupBy() to Group Arrays Without Lodash

๐Ÿ“Š Native GroupBy Finally Arrived _.groupBy() required Lodash. Object.groupBy() is now native. Group arrays by any criteria. No more manual reduce hacks. ๐Ÿ“ Basic Usage const users = [ { name: ‘Alice’, role: ‘admin’ }, { name: ‘Bob’, role: ‘user’ }, { name: ‘Charlie’, role: ‘admin’ }, { name: ‘Diana’, role: ‘user’ } ]; // […]

Read More
JavaScript

JavaScript: Use Intl API for Native Date, Number, and String Localization

- 30.05.26 - ErcanOPAK comment on JavaScript: Use Intl API for Native Date, Number, and String Localization

๐ŸŒ No More Moment.js Dates, numbers, currencies, plurals โ€” all have different formats per locale. Intl API is built-in. No libraries needed. ๐Ÿ“ Date Formatting const date = new Date(); // US English new Intl.DateTimeFormat(‘en-US’).format(date); // “12/31/2024” // UK English new Intl.DateTimeFormat(‘en-GB’).format(date); // “31/12/2024” // German new Intl.DateTimeFormat(‘de-DE’).format(date); // “31.12.2024” // Japanese new Intl.DateTimeFormat(‘ja-JP’).format(date); // […]

Read More
JavaScript

JavaScript: Use structuredClone() for True Deep Copy of Objects

- 29.05.26 - ErcanOPAK comment on JavaScript: Use structuredClone() for True Deep Copy of Objects

๐Ÿ“ฆ Finally, True Deep Copy Without Libraries JSON.parse(JSON.stringify()) fails with dates, undefined, functions. structuredClone() handles dates, maps, sets, arrays, nested objects โ€” everything. โŒ JSON Hack (Broken) const obj = { date: new Date(), fn: () => {}, undef: undefined }; const copy = JSON.parse(JSON.stringify(obj)); // date becomes string! // fn and undef are gone! […]

Read More
JavaScript

JavaScript: Use Top-Level Await in Modules for Cleaner Async Code

- 28.05.26 | 28.05.26 - ErcanOPAK comment on JavaScript: Use Top-Level Await in Modules for Cleaner Async Code

โฐ Async Without Async Function Wrapper Need await at top level? Used to need IIFE. Top-level await works directly in ES modules. Cleaner initialization code. โŒ Old Way (IIFE) (async () => { const data = await fetch(‘/api/config’); const config = await data.json(); startApp(config); })(); โœ… Top-Level Await // In .mjs or type=”module” script const […]

Read More
JavaScript

JavaScript: Use Nullish Coalescing (??) Instead of || for Default Values

- 27.05.26 - ErcanOPAK comment on JavaScript: Use Nullish Coalescing (??) Instead of || for Default Values

?? vs || โ€” The Important Difference `||` treats 0, ”, false as falsy. `??` only checks `null` and `undefined`. Use ?? for default values. โŒ Logical OR (||) Trap const count = userInput || 10; // If userInput = 0 โ†’ count = 10 (WRONG!) const name = userName || ‘Guest’; // If userName […]

Read More
JavaScript

JavaScript: Use Optional Chaining (?.) to Avoid Cannot Read Property of Undefined

- 26.05.26 - ErcanOPAK comment on JavaScript: Use Optional Chaining (?.) to Avoid Cannot Read Property of Undefined

๐Ÿ”— Stop the Cannot Read Property Error Optional chaining (?.) safely accesses nested properties. No more Cannot read property ‘x’ of undefined. โŒ Old Way (Crash-prone) // ๐Ÿ’ฅ CRASH if user or address is undefined const city = user.address.city; // Verbose fix let city = ‘Unknown’; if (user && user.address) { city = user.address.city; } […]

Read More
JavaScript

JavaScript: Use Destructuring to Extract Values Cleanly

- 26.05.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. โŒ Old Way const name = user.name; const age = user.age; const email = user.email; โœ… Destructuring const { name, age, email } = user; ๐ŸŽฏ Advanced Patterns // Rename variables […]

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: Mastering Array.from() for Functional UI

- 01.03.26 - ErcanOPAK comment on JavaScript: Mastering Array.from() for Functional UI

Converting a NodeList or a set of data into a UI list? Stop using forEach and start using the mapping feature of Array.from. const listItems = Array.from({ length: 5 }, (v, i) => `Item ${i + 1}`); // Output: [‘Item 1’, ‘Item 2’, ‘Item 3’, ‘Item 4’, ‘Item 5’] This allows you to generate data […]

Read More
JavaScript

JavaScript: Advanced Memory Cleanup with WeakRef

- 01.03.26 - ErcanOPAK comment on JavaScript: Advanced Memory Cleanup with WeakRef

In complex SPAs, caching large objects can lead to ‘Slow Leaks’. WeakRef allows you to hold a reference to an object without preventing it from being Garbage Collected. let cache = new WeakRef(largeObject); // Later… const obj = cache.deref(); if (obj) { /* Use object */ } else { /* Re-fetch, it was cleaned up […]

Read More
JavaScript

JavaScript: Building Reactive Systems with Proxy Objects

- 01.03.26 - ErcanOPAK comment on JavaScript: Building Reactive Systems with Proxy Objects

How do frameworks like Vue.js know when a variable changes? They use Proxies to intercept object operations. const data = { price: 100 }; const observer = new Proxy(data, { set(target, key, value) { console.log(`${key} changed to ${value}! Update UI…`); target[key] = value; return true; } }); observer.price = 150; // Triggers the log automatically

Read More
JavaScript

JavaScript: Preventing Memory Leaks with WeakMap and WeakSet

- 28.02.26 - ErcanOPAK comment on JavaScript: Preventing Memory Leaks with WeakMap and WeakSet

Standard Maps keep a ‘strong’ reference to keys, preventing Garbage Collection even if the object is no longer used. This causes memory leaks in long-running SPAs. // The Safe Way let userMetadata = new WeakMap(); let user = { id: 1 }; userMetadata.set(user, { lastLogin: Date.now() }); user = null; // The metadata is now […]

Read More
JavaScript

JavaScript: Eliminating ‘Cannot read property of undefined’ Errors

- 28.02.26 - ErcanOPAK comment on JavaScript: Eliminating ‘Cannot read property of undefined’ Errors

Deeply nested API responses are dangerous. One missing key crashes your app. Use Optional Chaining. // Old Way const city = user && user.address && user.address.city; // The Pro Way (ES2020) const city = user?.address?.city ?? ‘Unknown’; Why? It’s cleaner, safer, and allows you to provide a default value (Nullish Coalescing) in a single line.

Read More
JavaScript

JavaScript: Cleaner API Consumption with Object Destructuring

- 28.02.26 - ErcanOPAK comment on JavaScript: Cleaner API Consumption with Object Destructuring

Stop checking for null or undefined manually when receiving data from an API. // The Pro Way const { name, role = ‘User’, status = ‘Active’ } = apiResponse; console.log(`${name} is a ${role}`); Why? It makes your code more resilient and readable by providing fallback values directly in the declaration.

Read More
JavaScript

JavaScript Performance: The One Weird Trick That Made Our App 10x Faster

- 23.02.26 | 23.02.26 - ErcanOPAK comment on JavaScript Performance: The One Weird Trick That Made Our App 10x Faster

โšก Performance.now() = Before: 8.5s | After: 0.8s PROBLEM: Rendering 10,000 items BOTTLENECK: DOM manipulation SOLUTION: Virtual scrolling / windowing RESULT: 10x faster, 90% less memory The Problem: You’re Rendering What Users Can’t See โŒ The Slow Way // Render ALL 10,000 items const list = document.getElementById(‘list’); items.forEach(item => { const div = document.createElement(‘div’); div.textContent […]

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: Demystifying the Event Loop and Microtask Queue

- 21.02.26 - ErcanOPAK comment on JavaScript: Demystifying the Event Loop and Microtask Queue

Understanding the difference between setTimeout (Macrotask) and Promise.then (Microtask) is what separates junior and senior JS developers. Execution Order: 1. Synchronous Code 2. All Microtasks (Promises) 3. Render UI 4. Macrotasks (Timers)

Read More
Page 1 of 6
1 2 3 4 5 6 Next ยป

Posts pagination

1 2 3 … 6 Next »
June 2026
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
2930  
« May    

Most Viewed Posts

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

Recent Posts

  • C#: Use String Interpolation Instead of Concatenation
  • C#: Use Tuples to Return Multiple Values from Methods
  • SQL: Use ISNULL and NULLIF for Smart NULL Handling
  • .NET Core: Use Data Annotations for Model Validation
  • Git: Use Git Clean to Remove Untracked Files
  • Ajax: Add Custom Headers to Fetch Requests
  • JavaScript: Use console.table to Display Arrays as Tables
  • HTML: Use Spellcheck Attribute to Enable Browser Spell Check
  • CSS: Use user-select to Prevent Text Selection
  • Windows 11: Use Snipping Tool for Instant Screenshots

Most Viewed Posts

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

Recent Posts

  • C#: Use String Interpolation Instead of Concatenation
  • C#: Use Tuples to Return Multiple Values from Methods
  • SQL: Use ISNULL and NULLIF for Smart NULL Handling
  • .NET Core: Use Data Annotations for Model Validation
  • Git: Use Git Clean to Remove Untracked Files

Social

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