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

Category: JavaScript

JavaScript

JavaScript: Use Callback Functions for Async Programming

- 21.06.26 - ErcanOPAK comment on JavaScript: Use Callback Functions for Async Programming

πŸ“ž Functions That Call Other Functions JavaScript runs sequentially. Callbacks run after async operations. Event handlers, API calls, timers β€” all use callbacks. πŸ“ Basic Callback // Function that takes a callback function fetchData(callback) { setTimeout(() => { callback(‘Data loaded’); }, 1000); } // Using the callback fetchData((data) => { console.log(data); // ‘Data loaded’ (after […]

Read More
JavaScript

JavaScript: Understand Closures for Powerful Functions

- 20.06.26 - ErcanOPAK comment on JavaScript: Understand Closures for Powerful Functions

πŸ”’ Function + Its Environment = Closure Inner functions remember outer variables. Closures enable private variables, function factories, event handlers. πŸ“ Basic Closure function outer() { const message = ‘Hello’; function inner() { console.log(message); // Accesses outer variable } return inner; } const myFunc = outer(); myFunc(); // ‘Hello’ (message is remembered!) 🎯 Practical Closure […]

Read More
JavaScript

JavaScript: Use Async/Await for Clean Async Code

- 20.06.26 - ErcanOPAK comment on JavaScript: Use Async/Await for Clean Async Code

⏳ async/await = Sync-Looking Async Code Promise chains are better than callbacks. Async/await is even better. Write async code like synchronous. Clean, readable, maintainable. ❌ Promise Chain getUser(id) .then(user => getOrders(user.id)) .then(orders => getProducts(orders)) .then(products => console.log(products)) .catch(err => console.error(err)); βœ… Async/Await try { const user = await getUser(id); const orders = await getOrders(user.id); const […]

Read More
JavaScript

JavaScript: Use Event Delegation for Better Event Handling

- 20.06.26 - ErcanOPAK comment on JavaScript: Use Event Delegation for Better Event Handling

🎯 One Event Listener for Multiple Elements Attaching listeners to 100 buttons is wasteful. Event delegation attaches one listener to parent. Handles all children, including dynamically added. ❌ Many Listeners document.querySelectorAll(‘button’).forEach(btn => { btn.addEventListener(‘click’, handleClick); }); // 100 buttons = 100 listeners βœ… Event Delegation document.addEventListener(‘click’, (e) => { if (e.target.matches(‘button’)) { handleClick(e); } }); […]

Read More
JavaScript

JavaScript: Use Promises to Handle Asynchronous Operations

- 14.06.26 - ErcanOPAK comment on JavaScript: Use Promises to Handle Asynchronous Operations

⏳ Callback Hell is Dead. Long Live Promises. Callbacks nested inside callbacks = callback hell. Promises chain async operations. .then() and .catch() are readable, composable. ❌ Callback Hell getUser(id, (user) => { getOrders(user.id, (orders) => { getProducts(orders, (products) => { console.log(products); }); }); }); βœ… Promises getUser(id) .then(user => getOrders(user.id)) .then(orders => getProducts(orders)) .then(products => […]

Read More
JavaScript

JavaScript: Use Template Literals for Multi-line Strings and Interpolation

- 14.06.26 - ErcanOPAK comment on JavaScript: Use Template Literals for Multi-line Strings and Interpolation

“ Backticks > ” Quotes Quotes need escaping and concatenation. Template literals support multi-line and interpolation. Cleaner, more readable. ❌ Old Way const message = ‘Hello, ‘ + name + ‘!\n’ + ‘You are ‘ + age + ‘ years old.\n’ + ‘Welcome to our site.’; const html = ” + content + ”; βœ… […]

Read More
JavaScript

JavaScript: Use Spread Operator (…) for Cleaner Arrays and Objects

- 14.06.26 - ErcanOPAK comment on JavaScript: Use Spread Operator (…) for Cleaner Arrays and Objects

… Spreads Arrays and Objects concat() is old. Object.assign() is verbose. Spread operator (…) spreads elements. Merge arrays, clone objects, convert to array. ❌ Old Way const combined = arr1.concat(arr2); const copy = Object.assign({}, obj); const args = Array.prototype.slice.call(arguments); βœ… Spread Operator const combined = […arr1, …arr2]; const copy = { …obj }; const args […]

Read More
JavaScript

JavaScript: Use Destructuring to Extract Object Properties Easily

- 13.06.26 - ErcanOPAK comment on JavaScript: Use Destructuring to Extract Object Properties Easily

πŸ“¦ const name = user.name is Verbose Extracting properties takes multiple lines. Destructuring extracts in one line. Cleaner code, fewer bugs. ❌ Old Way const name = user.name; const age = user.age; const email = user.email; βœ… Destructuring const { name, age, email } = user; 🎯 Advanced Destructuring // Rename variables const { name: […]

Read More
JavaScript

JavaScript: Use Optional Chaining to Avoid Cannot Read Property Errors

- 13.06.26 - ErcanOPAK comment on JavaScript: Use Optional Chaining to Avoid Cannot Read Property Errors

πŸ›‘οΈ Stop Cannot Read Property of Undefined user?.address?.city is safe. Optional chaining (?.) returns undefined instead of throwing error. Cleaner code, fewer crashes. ❌ Old Way (Crash) const city = user.address.city; // πŸ’₯ Cannot read property ‘city’ of undefined βœ… Optional Chaining const city = user?.address?.city; // Returns undefined if missing, no crash 🎯 Advanced […]

Read More
JavaScript

JavaScript: Use console.time to Measure Code Performance

- 13.06.26 - ErcanOPAK comment on JavaScript: Use console.time to Measure Code Performance

⏱️ How Long Does This Loop Take? Date.now() before and after is messy. console.time() measures execution time precisely. Built-in, easy. πŸ“ Basic Usage // Start timer console.time(‘processData’); // Code to measure for (let i = 0; i < 1000000; i++) { // do something } // End timer console.timeEnd('processData'); // Output: processData: 45.2ms // Multiple […]

Read More
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
Page 6 of 11
Β« Previous 1 2 3 4 5 6 7 8 9 10 11 Next Β»

Posts pagination

« Previous 1 … 4 5 6 7 8 … 11 Next »
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,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (661)
  • Add Constraint to SQL Table to ensure email contains @ (619)
  • Average of all values in a column that are not zero in SQL (577)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (553)
  • Find numbers with more than two decimal places in SQL (481)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ HΔ±zΔ± Δ°zleyici Windows UygulamasΔ± v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store
  • WordPress: Fix a Navigation Block Losing Submenu Items After Sync
  • Visual Studio: Fix CodeLens Reference Counts Stuck at Stale Numbers
  • C#: Fix a UTF-8 String Literal Behaving Differently in a Switch
  • Photoshop: Fix a Liquify Mesh Snapping Back on a Smart Object
  • The AI Prompt That Turns a Crash Dump Into a Short Repro Script

Most Viewed Posts

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

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ HΔ±zΔ± Δ°zleyici Windows UygulamasΔ± v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store

Social

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