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 02 Sep 2026 6 min read

JavaScript Property Descriptors with Object.defineProperty

Most JavaScript properties are created with assignment or object literals. That is usually the right choice, but it hides several controls that every property carries: whether the property can be assigned, whether common enumeration APIs expose it, and whether its definition can later be changed. Property descriptors make those controls explicit. They are useful for library APIs, metadata, computed properties, compatibility layers, and cases where ordinary assignment exposes more behavior than intended.

JavaScript 02 Sep 2026 4 min read

Deep Cloning in JavaScript with structuredClone

Copying JavaScript objects looks simple until values contain nested arrays, dates, maps, sets, typed arrays, or circular references. A shallow spread copies only the first level, while the old JSON.stringify and JSON.parse pattern changes or rejects several legitimate JavaScript values. structuredClone provides a standard deep-cloning operation based on the structured clone algorithm used by browser messaging APIs. Shallow copies keep nested references A spread expression creates a new outer object:

JavaScript 02 Sep 2026 4 min read

Async Iteration and Backpressure with for await...of

JavaScript promises represent one future result. Many systems produce a sequence of future results instead: paginated records, stream chunks, queue messages, or events from an asynchronous source. Async iteration models that shape directly. An async iterable exposes values over time, and for await...of consumes them one at a time. A minimal async generator An async generator can yield values after asynchronous work: async function* pages() { for (let page = 1; page <= 3; page++) { const response = await fetch(`https://example.com/api/items?page=${page}`); if (!response.ok) { throw new Error(`HTTP ${response.status}`); } yield await response.json(); } } for await (const page of pages()) { console.log(page); } The consumer does not need to know how pagination is implemented. It only sees an asynchronous sequence.

JavaScript 01 Sep 2026 3 min read

Use structuredClone for Safe Deep Copying in JavaScript

Copying JavaScript values is easy until nested objects, dates, maps, sets, binary data, or circular references appear. The common JSON round trip works only for a limited subset of values and silently changes some data. The built-in structuredClone() API provides a defined deep-cloning algorithm for many JavaScript data types. Spread syntax is only a shallow copy Object spread copies the first level: const original = { profile: { name: "Ada" } }; const copy = { ...original }; copy.profile.name = "Grace"; console.log(original.profile.name); // "Grace" Both objects still reference the same nested profile. Spread syntax is useful when shallow copying is intentional, but it is not a general deep-copy mechanism.

JavaScript 01 Sep 2026 3 min read

Use JavaScript Import Maps for Browser Module Aliases

Native ES modules normally require browser-resolvable URLs such as ./math.js or /vendor/lib.js. Import maps add a controlled indirection layer so application code can use stable bare specifiers such as app/config without a bundler rewriting imports. Define a map before modules load <script type="importmap"> { "imports": { "app/": "/js/app/", "vendor-utils": "/vendor/utils-v3.js" } } </script> <script type="module" src="/js/main.js"></script> Then /js/main.js can use:

JavaScript 01 Sep 2026 5 min read

Choosing JavaScript Promise Combinators: all, allSettled, any, and race

JavaScript provides several Promise combinators that look similar but encode very different failure policies. Choosing between Promise.all, Promise.allSettled, Promise.any, and Promise.race is less about syntax and more about defining what “success” means for a group of asynchronous operations. The important question is not “which one runs in parallel?” Promises usually start when you create them. The combinator decides how to observe their outcomes. Promise.all: every result is required Use Promise.all when the operation is successful only if every input fulfills.

JavaScript 01 Sep 2026 5 min read

Cancel Fetch Requests and Prevent Stale UI Updates with AbortController

Fast user interfaces frequently start requests that become irrelevant before they finish. A search box may issue a request for ca, then cat, then catalog. If the oldest request finishes last, it can overwrite the newest results. AbortController gives JavaScript a standard way to cancel Fetch requests and other APIs that accept an AbortSignal. The basic cancellation pattern Create a controller and pass its signal to fetch: const controller = new AbortController(); const request = fetch('/api/profile', { signal: controller.signal, }); controller.abort(); Once aborted, the fetch promise rejects. Cancellation is therefore part of normal control flow and should be handled deliberately.

JavaScript 11 Sep 2025 2 min read

Understanding bind:value Between Parent and Child Components in Svelte

One convenient Svelte feature is two-way binding with bind:value. It can keep state in a parent component synchronized with a value exposed by a child component without writing separate event-handling boilerplate. The following example connects a reusable input component to state in its parent. 1. Child Component: InputField.svelte Create src/lib/components/InputField.svelte: <script lang="ts"> export let value: string = ""; </script> <h2>Child Component</h2> <input type="text" bind:value /> <p>Input value in child: {value}</p> How it works:

JavaScript 11 Sep 2025 3 min read

Building a Todo List with Stores in SvelteKit

Svelte stores provide a simple way to share reactive state across components. In this tutorial, we will build a small Todo List with: Adding tasks Marking tasks complete Editing tasks Deleting tasks Task statistics A live clock The example uses Svelte + TypeScript and the classic Svelte store APIs. 1. Define the Task Type Create src/lib/types/task.ts: export interface Task { id: number; title: string; done: boolean; } Each task has:

JavaScript 11 Sep 2025 2 min read

Building a Simple Search Feature in Svelte

Svelte’s reactivity makes it straightforward to update the UI when component state changes. In this example, we will build a small product search: as the user types, matching items appear immediately. 1. Complete Example Create src/routes/+page.svelte: <script lang="ts"> let query = ""; let products = ["Laptop", "Mouse", "Keyboard", "Monitor", "Printer"]; let results: string[] = []; function searchProducts(q: string) { if (q.trim() === "") { results = []; } else { results = products.filter((p) => p.toLowerCase().includes(q.toLowerCase()) ); } } // Reactive statement: runs whenever query changes $: searchProducts(query); </script> <input bind:value={query} placeholder="Search products..." /> <ul> {#if query.trim() !== ""} {#if results.length > 0} {#each results as item} <li>{item}</li> {/each} {:else} <li>No results</li> {/if} {/if} </ul> 2. How It Works The component has three pieces of state:

JavaScript Updated 02 Sep 2025 3 min read

Understanding Watchers in Vue 3

Vue 3 watchers let you run side-effect logic when reactive data changes. They are useful for tasks such as triggering an API request, synchronizing with an external system, persisting state, or responding to a transition between values. 1. What Is a Watcher? A watcher observes one or more reactive sources and runs a callback when their values change. Unlike a computed property, which represents derived state, a watcher is usually intended for side effects.

JavaScript Updated 02 Sep 2025 3 min read

Understanding Computed Properties in Vue 3

Vue 3’s reactivity system makes it easy to derive values from reactive state. A computed property is a value that Vue automatically recalculates when its reactive dependencies change and caches between updates when those dependencies stay the same. 1. What Is a Computed Property? Computed properties are designed for derived state. Instead of storing both source data and a duplicated calculated value, you define how the value should be computed from its dependencies.

JavaScript Updated 02 Sep 2025 2 min read

Two-Way Binding with `v-model` in Vue 3

Two-way binding is a common part of interactive Vue applications. In Vue 3, v-model provides a concise way to synchronize form controls with component state. This guide covers the basic syntax, common input types, custom components, and a few practical guidelines. 1. What Is Two-Way Binding? Two-way binding keeps a UI control and JavaScript state synchronized. When the user changes an input, the state updates; when the state changes, the rendered input reflects the new value.

JavaScript Updated 02 Sep 2025 3 min read

State Management in Vue 3 with Pinia

Effective state management becomes increasingly important as a Vue application grows. Pinia is the recommended state-management library for Vue and provides a compact API, strong TypeScript support, and good integration with the Composition API. This guide covers the basic setup and the core concepts of state, getters, and actions. 1. What Is Pinia? Pinia is a state-management library designed for Vue applications. Compared with older Vuex patterns, it generally offers:

JavaScript Updated 02 Sep 2025 3 min read

Sending Data from a Child Component to Its Parent in Vue 3

Component communication is a fundamental part of Vue 3 applications. Parents usually pass data down through props, while children send information upward by emitting events. For values that represent a two-way component model, Vue also provides the v-model component contract. 1. Why Child-to-Parent Communication Matters Common examples include: A form field component informing its parent that a value changed. A list item notifying its parent that the user selected or removed it. A reusable control reporting an action such as submit, close, or confirm. Keeping this communication explicit helps components remain reusable and easier to test.

JavaScript Updated 02 Sep 2025 3 min read

Making API Requests in Vue 3 with Axios

HTTP APIs are a core part of modern web applications. In Vue 3, Axios is a popular HTTP client that provides a convenient API for making requests, configuring defaults, and handling responses and errors. This tutorial demonstrates common CRUD-style requests against the public DummyJSON example API. 1. Install and Configure Axios Install Axios: npm install axios You can configure a reusable Axios instance instead of modifying global defaults:

JavaScript Updated 07 Sep 2025 2 min read

Use Optional Chaining (`?.`) Safely in JavaScript

Optional chaining (?.) lets JavaScript stop a property-access chain when the value immediately before ?. is null or undefined. Instead of throwing, the expression evaluates to undefined. Nested Properties const user = { profile: { name: 'Alice', address: { city: 'Wonderland' }, }, }; const city = user.profile?.address?.city; const postalCode = user.profile?.address?.postalCode; postalCode is undefined rather than causing an error.

JavaScript Updated 02 Sep 2025 1 min read

Use `Promise.any()` for the First Successful Result

Promise.any() fulfills as soon as one input promise fulfills. Rejections are ignored until either a promise succeeds or every input promise has rejected. const first = Promise.reject(new Error('first failed')); const second = new Promise((resolve) => setTimeout(resolve, 100, 'second succeeded')); const third = new Promise((resolve) => setTimeout(resolve, 200, 'third succeeded')); console.log(await Promise.any([first, second, third])); // second succeeded When Everything Fails If every promise rejects, Promise.any() rejects with an AggregateError:

JavaScript Updated 02 Sep 2025 1 min read

Replace Every Match with JavaScript `String.replaceAll()`

String.prototype.replaceAll() replaces every occurrence of a substring or every match of a global regular expression and returns a new string. Replace a Literal Substring const text = 'Hello World! Welcome to the World of JavaScript.'; const result = text.replaceAll('World', 'Universe'); Use a Regular Expression When searchValue is a RegExp, it must use the g flag:

JavaScript Updated 02 Sep 2025 2 min read

Private Fields and Methods in JavaScript Classes

JavaScript classes support truly private fields and methods using names that begin with #. They can be accessed only from code inside the class body that declares them. Private Fields class Person { #name; constructor(name) { this.#name = name; } getName() { return this.#name; } } Trying to access person.#name outside the class is a syntax error.

JavaScript Updated 02 Sep 2025 1 min read

JavaScript RegExp `d` Flag: Get Match Indices

The JavaScript regular-expression d flag enables match indices. It does not collect repeated captures; instead, it adds an indices property that tells you the start and end offsets of the overall match and each capturing group. Basic Example const regex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/d; const match = regex.exec('Date: 2024-08-30'); console.log(match[0]); // 2024-08-30 console.log(match.indices[0]); // [6, 16] console.log(match.indices.groups.year); // [6, 10] console.log(match.indices.groups.month); // [11, 13] console.log(match.indices.groups.day); // [14, 16] The end index is exclusive, matching the behavior of String.prototype.slice().

JavaScript Updated 07 Sep 2025 1 min read

JavaScript Numeric Separators (`_`)

JavaScript numeric separators let you place underscores inside numeric literals to improve readability. They do not change the numeric value. const million = 1_000_000; console.log(million); // 1000000 Decimal Fractions const pi = 3.141_592_653; Binary, Octal, and Hexadecimal const binary = 0b1010_1011; const octal = 0o123_456; const hex = 0xFF_FF_FF; Separators can also be used in BigInt literals:

JavaScript Updated 07 Sep 2025 1 min read

JavaScript Nullish Coalescing Operator (`??`)

The nullish coalescing operator, ??, provides a fallback only when the left-hand value is null or undefined. const username = null; const name = username ?? 'Guest'; console.log(name); // Guest ?? vs. || || falls back for every falsy value. ?? preserves valid falsy data such as 0, false, and '':

JavaScript Updated 07 Sep 2025 2 min read

JavaScript BigInt: Handling Large Integers

JavaScript Number can represent integers exactly only up to Number.MAX_SAFE_INTEGER (2^53 - 1). When you need larger integer values without losing precision, use BigInt. Create a BigInt const a = 123456789012345678901234567890n; const b = BigInt('123456789012345678901234567890'); The n suffix creates a BigInt literal. BigInt() is useful when converting a string or an integer-valued Number.