Skip to content

Archive

JavaScript

47 articles
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:

JavaScript Updated 02 Sep 2025 1 min read

Truncate Text to a Maximum Length in JavaScript

User interfaces often need a shortened preview of longer text. A small helper can truncate a string to a maximum length and append an ellipsis when necessary. function limitText(text, limit) { if (typeof text !== 'string') return ''; if (!Number.isInteger(limit) || limit < 0) { throw new RangeError('limit must be a non-negative integer'); } if (text.length <= limit) return text; return `${text.slice(0, limit)}...`; } Examples:

JavaScript Updated 02 Sep 2025 1 min read

Extract a YouTube Video ID from a URL with JavaScript

YouTube links appear in several common formats, including youtube.com/watch?v=..., youtu.be/..., Shorts URLs, and embed URLs. A small JavaScript helper can normalize those formats and return the video ID. Use the URL API function getYouTubeVideoId(input) { const url = new URL(input); if (url.hostname === 'youtu.be') { return url.pathname.slice(1).split('/')[0] || null; } if (url.hostname.endsWith('youtube.com')) { if (url.pathname === '/watch') { return url.searchParams.get('v'); } const match = url.pathname.match(/^\/(?:embed|shorts|live)\/([^/?]+)/); return match?.[1] ?? null; } return null; } Examples console.log(getYouTubeVideoId('https://www.youtube.com/watch?v=QOM0xWASUwE')); console.log(getYouTubeVideoId('https://youtu.be/QOM0xWASUwE')); console.log(getYouTubeVideoId('https://www.youtube.com/embed/QOM0xWASUwE')); console.log(getYouTubeVideoId('https://www.youtube.com/shorts/QOM0xWASUwE')); Each returns:

JavaScript Updated 02 Sep 2025 2 min read

Remove Duplicates from JavaScript Arrays

Removing duplicates depends on what “duplicate” means for your data. Primitive values, objects with unique IDs, and records compared by several properties need different strategies. Primitive Values with Set const values = [1, 2, 3, 2, 4, 3]; const unique = [...new Set(values)]; console.log(unique); // [1, 2, 3, 4] Keep the First Object for Each ID const items = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 1, name: 'Alice again' }, ]; const seen = new Set(); const unique = items.filter((item) => { if (seen.has(item.id)) return false; seen.add(item.id); return true; }); Keep the Last Object for Each ID A Map naturally overwrites earlier values for the same key:

JavaScript Updated 07 Sep 2025 1 min read

Sort JavaScript Object Arrays by a Property Value

JavaScript comparator functions make it straightforward to sort arrays of objects by a numeric property. const data = [ { name: 'Edward', order: 21 }, { name: 'Sharpe', order: 37 }, { name: 'And', order: 45 }, { name: 'The', order: -12 }, { name: 'Magnetic', order: 13 }, { name: 'Zeros', order: 37 }, ]; Descending Order const sorted = data.toSorted((a, b) => b.order - a.order); This places the largest order value first.

JavaScript Updated 02 Sep 2025 1 min read

Find Text and Extract Context from a JavaScript String

Sometimes a search result is more useful when it includes nearby text instead of returning only an index. A small helper can find a substring and return a configurable amount of context around it. function findTextContext(text, query, context = 100) { const index = text.indexOf(query); if (index === -1) return null; const start = Math.max(0, index - context); const end = Math.min(text.length, index + query.length + context); return text.slice(start, end); } Example const text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor.'; const result = findTextContext(text, 'consectetur', 20); console.log(result); The helper finds the first occurrence and includes up to 20 characters before and after it.

JavaScript Updated 07 Sep 2025 2 min read

Filter JavaScript Arrays Quickly and Clearly

Array.prototype.filter() creates a new array containing only the elements that satisfy a predicate. It does not modify the original array. Filter by a Condition const values = [1, 2, 3, 4, 5, 6]; const even = values.filter((value) => value % 2 === 0); console.log(even); // [2, 4, 6] Filter Objects by a Property const users = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 25 }, ]; const age25 = users.filter((user) => user.age === 25); Remove Duplicates For primitive values, a Set is usually clearer than using filter() with indexOf:

JavaScript Updated 02 Sep 2025 2 min read

Manage Asynchronous Operations with Promises and Async/Await in JavaScript

Promises represent values that may become available later. async and await provide syntax for working with promises using control flow that resembles synchronous code. Create a Promise function callFirstName() { return new Promise((resolve) => { setTimeout(() => resolve('John'), 1000); }); } A promise can be fulfilled with resolve or rejected with reject.