๐ 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); […]
Category: JavaScript
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 […]
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 […]
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: […]
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 […]
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 […]
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 […]
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!) […]
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! […]
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’ } ]; // […]
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); // […]
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! […]
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 […]
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 […]
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; } […]
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 […]
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 […]
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, […]
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 […]
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 […]
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. […]
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 […]
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 […]
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
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 […]
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.
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.
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 […]
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 […]
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)









