Skip to content

Topic archive

JavaScript

A versatile programming language for frontend and backend web development, supported by a broad ecosystem of runtimes, frameworks, libraries, and developer tools.

55 articles
JavaScript Updated 02 Sep 2025 1 min read

JavaScript `||=`: Logical OR Assignment

The logical OR assignment operator, ||=, assigns a new value only when the current left-hand value is falsy. let name = ''; name ||= 'Guest'; console.log(name); // 'Guest' Falsy values include false, 0, -0, 0n, '', null, undefined, and NaN.

JavaScript Updated 02 Sep 2025 1 min read

JavaScript `&&=`: Logical AND Assignment

The logical AND assignment operator, &&=, assigns a new value to its left-hand operand only when the current value is truthy. Basic Syntax variable &&= newValue; Conceptually, this is similar to:

JavaScript Updated 07 Sep 2025 1 min read

JavaScript `??=`: Nullish Coalescing Assignment

The nullish coalescing assignment operator, ??=, assigns a value only when the current left-hand value is null or undefined. let name = null; name ??= 'Guest'; console.log(name); // Guest Function Defaults function greet(user) { user ??= 'Stranger'; console.log(`Hello, ${user}!`); } A default parameter may be even clearer when only undefined needs a fallback:

JavaScript Updated 02 Sep 2025 1 min read

Handle Multiple Promises with `Promise.allSettled()`

Promise.allSettled() waits until every input promise has either fulfilled or rejected, then returns the outcome of each operation. Unlike Promise.all(), one rejection does not stop you from receiving the other results. const tasks = [ Promise.resolve('first result'), Promise.reject(new Error('second failed')), Promise.resolve('third result'), ]; const results = await Promise.allSettled(tasks); for (const result of results) { if (result.status === 'fulfilled') { console.log('Value:', result.value); } else { console.error('Error:', result.reason); } } Each result has one of these shapes:

JavaScript Updated 02 Sep 2025 1 min read

Get Every RegExp Match with `String.matchAll()`

String.prototype.matchAll() returns an iterator containing every match of a global regular expression, including capturing groups and match indexes. const text = 'Order #123, Order #456, Order #789'; const regex = /Order #(\d+)/g; for (const match of text.matchAll(regex)) { console.log(match[0], match[1], match.index); } Named Capturing Groups const text = 'John: 123, Jane: 456'; const regex = /(?<name>\w+): (?<number>\d+)/g; for (const match of text.matchAll(regex)) { console.log(match.groups.name, match.groups.number); } Convert the Iterator to an Array const matches = [...'cat bat mat'.matchAll(/\b(\w+)at\b/g)]; This is convenient when you need map, filter, or other array operations, but iterating directly avoids storing all matches at once.

JavaScript Updated 02 Sep 2025 1 min read

Access JavaScript Array Elements with `at()`

Array.prototype.at() returns the element at a given integer index. Its main advantage over bracket notation is support for negative indexes. Positive Indexes const fruits = ['apple', 'banana', 'cherry']; console.log(fruits.at(0)); // 'apple' console.log(fruits.at(1)); // 'banana' Negative Indexes console.log(fruits.at(-1)); // 'cherry' console.log(fruits.at(-2)); // 'banana' Without at(), the traditional equivalent for the last element is:

JavaScript Updated 07 Sep 2025 1 min read

Update JavaScript Arrays Immutably with `with()`

Array.prototype.with() returns a copy of an array with one element replaced. The source array is left unchanged. const colors = ['red', 'blue', 'green', 'yellow']; const updated = colors.with(1, 'purple'); console.log(updated); // ['red', 'purple', 'green', 'yellow'] console.log(colors); // ['red', 'blue', 'green', 'yellow'] Negative Indexes Like at(), with() accepts negative indexes:

JavaScript Updated 02 Sep 2025 2 min read

Understanding Variable Scope in JavaScript

Variable scope determines where a name can be accessed. JavaScript uses lexical scope, with important differences between var, let, and const. Global Scope A binding declared at the top level can be visible throughout its module or script: const globalValue = 'global'; function showValue() { console.log(globalValue); } In modern ES modules, top-level declarations do not automatically become properties of window.

JavaScript Updated 02 Sep 2025 1 min read

Understanding `for`, `forEach`, and `map` in JavaScript

JavaScript offers several ways to iterate over arrays. for, forEach, and map overlap in what they can express, but each communicates a different intent. Traditional for const numbers = [1, 2, 3, 4, 5]; for (let i = 0; i < numbers.length; i++) { console.log(numbers[i]); } Use a for loop when you need explicit index control, break, continue, unusual step sizes, or tight control over the iteration process.

JavaScript Updated 07 Sep 2025 2 min read

Sort JavaScript Arrays Immutably with `toSorted()`

toSorted() returns a sorted copy of an array without modifying the original. It is the non-mutating counterpart to sort(). Basic Usage For numbers, provide a comparator because the default sort order is based on strings: const numbers = [5, 3, 8, 1]; const sortedNumbers = numbers.toSorted((a, b) => a - b); console.log(sortedNumbers); // [1, 3, 5, 8] console.log(numbers); // [5, 3, 8, 1] Sort Objects const students = [ { name: 'Alice', grade: 85 }, { name: 'Bob', grade: 92 }, { name: 'Charlie', grade: 88 }, ]; const sortedByGrade = students.toSorted((a, b) => b.grade - a.grade); console.log(sortedByGrade); console.log(students); // unchanged Sort Strings with a Custom Rule const words = ['banana', 'apple', 'cherry']; const sortedWords = words.toSorted((a, b) => a.length - b.length); For locale-aware alphabetical ordering, use localeCompare:

JavaScript Updated 02 Sep 2025 1 min read

Reverse JavaScript Arrays Immutably with `toReversed()`

toReversed() returns a new array with the elements in reverse order while leaving the original array unchanged. It is the non-mutating counterpart to reverse(). Basic Usage const originalArray = [1, 2, 3, 4, 5]; const reversedArray = originalArray.toReversed(); console.log(reversedArray); // [5, 4, 3, 2, 1] console.log(originalArray); // [1, 2, 3, 4, 5] toReversed() vs. reverse() const a = [1, 2, 3]; const b = a.reverse(); console.log(a); // [3, 2, 1] console.log(b === a); // true reverse() changes the existing array. By contrast:

JavaScript Updated 07 Sep 2025 1 min read

Modify JavaScript Arrays Immutably with `toSpliced()`

toSpliced() creates a modified copy of an array without changing the source array. It is the non-mutating counterpart to splice(). Syntax array.toSpliced(start, deleteCount, ...items) start is the index where the change begins. deleteCount controls how many existing elements are removed. items are inserted at that position. Replace Elements const fruits = ['apple', 'banana', 'cherry', 'date']; const updated = fruits.toSpliced(1, 2, 'blueberry', 'fig'); console.log(updated); // ['apple', 'blueberry', 'fig', 'date'] console.log(fruits); // unchanged Insert Without Deleting const numbers = [1, 2, 5]; const result = numbers.toSpliced(2, 0, 3, 4); console.log(result); // [1, 2, 3, 4, 5] Remove Elements const values = ['a', 'b', 'c', 'd']; const result = values.toSpliced(1, 2); console.log(result); // ['a', 'd'] Why It Is Useful Non-mutating updates are especially helpful in UI state management, reducers, and code where several consumers share the same array reference. toSpliced() makes that intent explicit without manually combining slices.

JavaScript Updated 07 Sep 2025 2 min read

HTTP Requests in JavaScript with the Fetch API

The Fetch API is the built-in, promise-based HTTP client available in modern browsers and current JavaScript runtimes. It is a good default when you do not need a third-party request library. This guide uses DummyJSON to demonstrate common CRUD-style requests. Fetch All Products const response = await fetch('https://dummyjson.com/products'); if (!response.ok) throw new Error(`HTTP ${response.status}`); const data = await response.json(); console.log(data); Fetch a Product by ID const response = await fetch('https://dummyjson.com/products/1'); if (!response.ok) throw new Error(`HTTP ${response.status}`); console.log(await response.json()); Search Products Use URLSearchParams when query values are dynamic:

JavaScript Updated 02 Sep 2025 2 min read

HTTP Requests in JavaScript with Axios

Axios is a popular promise-based HTTP client for browsers and Node.js. It provides a compact API for requests, JSON handling, interceptors, timeouts, custom instances, and request cancellation. This guide uses the DummyJSON API to demonstrate common CRUD-style requests. 1. Install Axios With npm: npm install axios For a simple browser page, you can also load a CDN build:

JavaScript Updated 02 Sep 2025 1 min read

Group JavaScript Data with `Object.groupBy()`

Object.groupBy() groups iterable values by a key returned from a callback and produces an object whose properties contain arrays of matching items. Group Numbers const numbers = [1, 2, 3, 4, 5, 6]; const grouped = Object.groupBy(numbers, (number) => number % 2 === 0 ? 'even' : 'odd' ); The result has even and odd arrays.

JavaScript Updated 02 Sep 2025 2 min read

Group Data with JavaScript `Map.groupBy()`

Map.groupBy() groups iterable values into a Map. The callback determines the key for each group, and every map value is an array of matching elements. Basic Example const numbers = [1, 2, 3, 4, 5, 6]; const grouped = Map.groupBy(numbers, (number) => number % 2 === 0 ? 'even' : 'odd' ); console.log(grouped.get('even')); // [2, 4, 6] Group Objects const products = [ { name: 'Laptop', category: 'Electronics' }, { name: 'Shirt', category: 'Clothing' }, { name: 'Phone', category: 'Electronics' }, ]; const grouped = Map.groupBy(products, (product) => product.category); Arbitrary Map Keys The main advantage over Object.groupBy() is that map keys can be objects and other values without being converted to property keys:

JavaScript Updated 02 Sep 2025 2 min read

Format Dates in JavaScript

JavaScript provides several built-in ways to format dates. For user-facing text, Intl.DateTimeFormat is usually the best starting point because it understands locales and formatting options. toLocaleDateString() const date = new Date(); console.log(date.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric', })); Intl.DateTimeFormat Create a reusable formatter when formatting many values:

JavaScript Updated 02 Sep 2025 1 min read

Find the Last Matching Array Index with `findLastIndex()`

Array.prototype.findLastIndex() searches from the end of an array and returns the index of the first element, in reverse order, that matches a predicate. const numbers = [1, 3, 5, 8, 10, 12, 7, 6]; const index = numbers.findLastIndex((number) => number % 2 === 0); console.log(index); // 7 For object arrays:

JavaScript Updated 02 Sep 2025 1 min read

Find the Last Matching Array Element with `findLast()`

Array.prototype.findLast() searches an array from the end and returns the first element, in reverse order, that satisfies a predicate. const numbers = [1, 3, 5, 8, 10, 12, 7, 6]; const lastEven = numbers.findLast((number) => number % 2 === 0); console.log(lastEven); // 6 For objects:

JavaScript Updated 02 Sep 2025 2 min read

Arrow Functions vs Traditional Functions in JavaScript

JavaScript gives you several ways to define functions. Arrow functions are compact and capture lexical this, while traditional functions have their own this behavior and can be used as constructors. 1. Common Function Forms Function declaration: function greet(name) { return `Hello, ${name}!`; } Function expression:

JavaScript Updated 07 Sep 2025 2 min read

Understanding the Differences Between pnpm, Yarn, npm, and Bun

JavaScript projects commonly use npm, Yarn, pnpm, or Bun to install dependencies and run package scripts. They all work with the npm package ecosystem, but they differ in installation strategy, lockfiles, workspace tooling, runtime integration, and compatibility details. npm npm ships with Node.js and is the most universal default. It supports lockfiles, workspaces, package scripts, and the standard npm registry with minimal setup. npm install npm run build Choose npm when you want the conventional Node.js toolchain and broad compatibility without adding another package manager.

JavaScript Updated 07 Sep 2025 2 min read

Create a Simple Static Web Server with `http-server`

When you need to test static HTML, CSS, JavaScript, images, or a generated site locally, the Node.js package http-server provides a small command-line server with minimal setup. Run It Without a Global Install If Node.js and npm are already installed, you can run the package with npx: npx http-server . The final . means “serve the current directory.” The command prints the local addresses and port it is using.

JavaScript Updated 02 Sep 2025 2 min read

Split a JavaScript Array into Chunks

JavaScript does not have a built-in chunk method for splitting an array into equally sized groups, but the operation is easy to implement with slice. Chunking is useful for UI grids, pagination helpers, batching API operations, and processing large collections in smaller units. A Simple chunk Function function chunk(array, size) { if (!Number.isInteger(size) || size <= 0) { throw new RangeError('size must be a positive integer'); } const result = []; for (let i = 0; i < array.length; i += size) { result.push(array.slice(i, i + size)); } return result; } Use it like this:

JavaScript Updated 02 Sep 2025 1 min read

Convert Text to Title Case in JavaScript

A simple title-case helper can make labels, headings, and generated display text easier to read. Basic Helper function titleCase(text) { return text .toLowerCase() .split(/\s+/) .filter(Boolean) .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) .join(' '); } Examples: