<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>JavaScript on Smashing Magazine — For Web Designers And Developers</title><link>https://www.smashingmagazine.com/category/javascript/index.xml</link><description>Recent content in JavaScript on Smashing Magazine — For Web Designers And Developers</description><generator>Hugo -- gohugo.io</generator><language>en-us</language><lastBuildDate>Fri, 13 Nov 2026 04:40:45 +0000</lastBuildDate><item><author>Jad Joubran</author><title>How Baseline Can Help You Ship Less JavaScript</title><link>https://www.smashingmagazine.com/2026/08/how-baseline-can-help-ship-less-javascript/</link><pubDate>Fri, 07 Aug 2026 13:00:00 +0000</pubDate><guid>https://www.smashingmagazine.com/2026/08/how-baseline-can-help-ship-less-javascript/</guid><description>The gap between “you need a library for this” and “the browser does this” keeps closing. A practical guide to auditing your dependencies and finding what the web platform can now handle for you.</description><content:encoded><![CDATA[
          <html>
            <head>
              <meta charset="utf-8">
              <link rel="canonical" href="https://www.smashingmagazine.com/2026/08/how-baseline-can-help-ship-less-javascript/" />
              <title>How Baseline Can Help You Ship Less JavaScript</title>
            </head>
            <body>
              <article>
                <header>
                  <h1>How Baseline Can Help You Ship Less JavaScript</h1>
                  
                    
                    <address>Jad Joubran</address>
                  
                  <time datetime="2026-08-07T13:00:00&#43;00:00" class="op-published">2026-08-07T13:00:00+00:00</time>
                  <time datetime="2026-08-07T13:00:00&#43;00:00" class="op-modified">2026-11-13T04:40:45+00:00</time>
                </header>
                
                

<p>Most of us install a dependency once and never look at it again. It does its job, the tests pass, and we move on. But the web platform keeps moving too, and a surprising number of the libraries sitting in your <code>package.json</code> today are now built into the browser.</p>

<p>In a typical mid-sized JavaScript app, you can often find somewhere between 60KB and 90KB (minified and gzipped) of dependencies that the platform can now handle on its own. Date and number formatting, HTTP requests, modals, tooltips, deep cloning, grouping arrays: these were all real gaps a few years ago. A lot of them aren’t gaps anymore.</p>

<p>The reason those libraries stick around isn’t laziness. It’s that most teams don’t re-audit their dependencies on a Baseline cadence, or are simply not aware of how fast browsers are shipping these days. You check <code>npm audit</code> for security, but <em>is this library still doing something the browser can’t?</em> is a question that rarely gets asked. So the libraries stay.</p>

<p>In this article, we’ll run that audit together. Instead of going through dependencies one by one, we’ll work in clusters, because the wins tend to come in groups. We’ll do the bundle math, build a small decision framework you can reuse, and stay honest about the cases where the platform still falls short. By the end, you’ll have a repeatable process you can run on your own <code>package.json</code>.</p>














<figure class="
  
    break-out article__image
  
  
  ">
  
    <a href="https://files.smashing.media/articles/how-baseline-can-help-ship-less-javascript/1-git-diff-removed-npm-dependencies.png">
    
    <img
      loading="lazy"
      decoding="async"
      fetchpriority="low"
			width="800"
			height="340"
			
			srcset="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/how-baseline-can-help-ship-less-javascript/1-git-diff-removed-npm-dependencies.png 400w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_800/https://files.smashing.media/articles/how-baseline-can-help-ship-less-javascript/1-git-diff-removed-npm-dependencies.png 800w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1200/https://files.smashing.media/articles/how-baseline-can-help-ship-less-javascript/1-git-diff-removed-npm-dependencies.png 1200w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1600/https://files.smashing.media/articles/how-baseline-can-help-ship-less-javascript/1-git-diff-removed-npm-dependencies.png 1600w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_2000/https://files.smashing.media/articles/how-baseline-can-help-ship-less-javascript/1-git-diff-removed-npm-dependencies.png 2000w"
			src="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/how-baseline-can-help-ship-less-javascript/1-git-diff-removed-npm-dependencies.png"
			
			sizes="100vw"
			alt="Git diff showing removed npm dependencies highlighted in red from a package.json file, illustrating how Baseline helps reduce JavaScript bundle size."
		/>
    
    </a>
  

  
    <figcaption class="op-vertical-bottom">
      (<a href='https://files.smashing.media/articles/how-baseline-can-help-ship-less-javascript/1-git-diff-removed-npm-dependencies.png'>Large preview</a>)
    </figcaption>
  
</figure>

<h2 id="what-baseline-actually-means">What “Baseline” Actually Means</h2>

<p>Before we start deleting things, let’s quickly recap what Baseline is. Feel free to skip this section if you’re already familiar.</p>

<p>Baseline is a project from the <a href="https://github.com/web-platform-dx/web-features">WebDX Community Group</a> that tells you, in plain terms, how safe a web feature is to use across the major browsers (Chrome, Edge, Firefox, and Safari). A feature can be in one of three states:</p>

<ul>
<li><strong>Limited availability</strong><br />
The feature hasn’t shipped in all the major engines yet. Not safe to rely on without a fallback.</li>
<li><strong>Baseline Newly available</strong><br />
The feature has just landed in all the major engines. It works for users on up-to-date browsers, but older devices in the wild may not have it yet.</li>
<li><strong>Baseline Widely available</strong><br />
The feature has been in all the major engines for 30 months. At this point, you can reach for it without much thought.</li>
</ul>

<p>That 30-month gap between “Newly” and “Widely” matters a lot for this audit. A feature that’s Widely available is something you can usually drop a library for today. A feature that’s only Newly available is something you can drop a library for <em>if</em> you check your audience first, or if you’re comfortable with a small feature check. We’ll treat those two cases differently throughout.</p>

<p>You can look any feature up on <a href="https://webstatus.dev/">webstatus.dev</a>, on <a href="https://developer.mozilla.org/">MDN</a> (every reference page shows a Baseline badge near the top), or programmatically with the <code>web-features</code> npm package. We’ll use all three later when we run the audit on a real project.</p>

<div data-audience="non-subscriber" data-remove="true" class="feature-panel-container">

<aside class="feature-panel" style="">
<div class="feature-panel-left-col">

<div class="feature-panel-description"><p>Meet <strong><a data-instant href="/printed-books/typescript-in-50-lessons/">“TypeScript in 50 Lessons”</a></strong>, our shiny new guide to TypeScript. With detailed <strong>code walkthroughs</strong>, hands-on examples and common gotchas. For developers who know enough <strong>JavaScript</strong> to be dangerous.</p>
<a data-instant href="/printed-books/typescript-in-50-lessons/" class="btn btn--green btn--large" style="">Jump to table of contents&nbsp;↬</a></div>
</div>
<div class="feature-panel-right-col"><a data-instant href="/printed-books/typescript-in-50-lessons/" class="feature-panel-image-link">
<div class="feature-panel-image"><picture><source type="image/avif" srcSet="https://archive.smashing.media/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/2732dfe9-e1ee-41c3-871a-6252aeda741c/typescript-panel.avif" />
<img
    loading="lazy"
    decoding="async"
    class="feature-panel-image-img"
    src="https://archive.smashing.media/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/c2f2c6d6-4e85-449a-99f5-58bd053bc846/typescript-shop-cover-opt.png"
    alt="Feature Panel"
    width="481"
    height="698"
/>
</picture>
</div>
</a>
</div>
</aside>
</div>

<h2 id="a-decision-framework-before-you-delete-anything">A Decision Framework Before You Delete Anything</h2>

<p>It’s tempting to read <em>“the browser does this now”</em> and start ripping libraries out. Let’s not do that. A swap that looks free on paper can quietly break things for a chunk of your users, or cost you a feature you were relying on without realizing it.</p>

<p>So before dropping any library, ask three questions. We’ll reuse these in every cluster below.</p>

<p><strong>1. Is the replacement Baseline-safe for</strong> <strong><em>my</em></strong> <strong>audience?</strong></p>

<p>Not <em>“is it Baseline”</em> in the abstract, but <em>“is it safe for the people who actually use my app.”</em> If the native feature is Widely available, this is usually a yes. If it’s only Newly available, check your analytics or your <code>browserslist</code> config and see what share of your users would miss out. A B2B dashboard where everyone’s on the latest browser is a very different situation from a public-facing site with a long tail of old Android devices.</p>

<p><strong>2. What does the swap actually cost?</strong></p>

<p>Dropping a library isn’t always free. Sometimes the native feature isn’t supported widely enough yet, so you’d reach for a polyfill. If that polyfill is heavier than the library you’re removing, you’ve made your bundle <em>bigger</em>, unless you load it conditionally. We’ll see exactly this with Temporal later.</p>

<p><strong>3. Does the platform feature cover my real use case?</strong></p>

<p>Libraries often do more than the platform feature they resemble. <code>axios</code> isn’t just <code>fetch</code> with automatic JSON parsing; it has interceptors, request cancellation, and retries. If you’re using those, a straight swap to <code>fetch</code> will leave you reimplementing them. Check what you actually use before assuming it’s a drop-in replacement.</p>

<p>Keep these three in mind. Every cluster below is really just these questions applied to a different corner of your dependencies.</p>

<h2 id="cluster-1-internationalization-the-biggest-drop-today-win">Cluster 1: Internationalization (The Biggest Drop Today Win)</h2>

<p>This is the cluster where you’ll usually find the most KBs sitting on top of features that are already Widely available. The browser ships a whole family of formatting tools under the <code>Intl</code> namespace, and a lot of small, popular libraries became unnecessary.</p>

<p>Here are the usual suspects and what replaces them:</p>

<ul>
<li><code>timeago.js</code> (1 KB gz) → <code>Intl.RelativeTimeFormat</code></li>
<li><code>pluralize</code> (2.3 KB gz) → <code>Intl.PluralRules</code></li>
<li><code>numeral</code> (3.9 KB gz) → <code>Intl.NumberFormat</code></li>
<li><code>humanize-duration</code> (6.6 KB gz) → <code>Intl.DurationFormat</code></li>
<li>list-joining helpers → <code>Intl.ListFormat</code></li>
</ul>

<p>Let’s walk through some of them.</p>

<h3 id="relative-time">Relative Time</h3>

<p><code>timeago.js</code> exists to turn a timestamp into <em>“3 hours ago”</em>. <code>Intl.RelativeTimeFormat</code> does the same thing, and it’s Baseline Widely available.</p>

<pre><code class="language-javascript">const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });

rtf.format(-1, "day"); // "yesterday"
rtf.format(3, "hour"); // "in 3 hours"
rtf.format(-2, "week"); // "2 weeks ago"
</code></pre>

<p>The <code>numeric: &quot;auto&quot;</code> option is the nice touch here: it gives you “yesterday” instead of “1 day ago” where the language has a word for it. You pass a number and a unit, and you get a localized string back.</p>

<p>You may be wondering about the one thing <code>timeago.js</code> does that this snippet doesn’t: it picks the unit for you. Given a date, <code>timeago.js</code> decides whether to say “seconds” or “days.” <code>Intl.RelativeTimeFormat</code> expects you to do that part. It’s a few lines of arithmetic (work out the difference, find the largest unit that fits), and once you’ve written that helper, you don’t need the library anymore.</p>

<h3 id="numbers-currency-and-lists">Numbers, Currency, And Lists</h3>

<p><code>Intl.NumberFormat</code> covers most of what number-formatting libraries do: thousands separators, currency, percentages, and compact notation.</p>

<div class="break-out">
<pre><code class="language-javascript">new Intl.NumberFormat("en-US").format(1234567.89);
// "1,234,567.89"

new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(
  1234.5,
);
// "$1,234.50"

new Intl.NumberFormat("en", { notation: "compact" }).format(1200000);
// "1.2M"
</code></pre>
</div>

<p>And <code>Intl.ListFormat</code>, Widely available, handles the “join an array into a sentence” problem, including the Oxford comma, which is the kind of thing people write fiddly helper functions for:</p>

<div class="break-out">
<pre><code class="language-javascript">const lf = new Intl.ListFormat("en", { style: "long", type: "conjunction" });

lf.format(["Alice", "Bob", "Carol"]);
// "Alice, Bob, and Carol"
</code></pre>
</div>

<h3 id="the-one-caveat-durations">The One Caveat: Durations</h3>

<p><code>humanize-duration</code> turns a number of milliseconds into <em>“1 hour, 30 minutes”</em>. The platform equivalent is <code>Intl.DurationFormat</code>:</p>

<pre><code class="language-javascript">const df = new Intl.DurationFormat("en", { style: "long" });

df.format({ hours: 1, minutes: 30 });
// "1 hour, 30 minutes"
</code></pre>

<p>One thing to keep in mind is that <code>Intl.DurationFormat</code> is Baseline <em>Newly</em> available at the time of writing, not Widely available. It landed in all the major engines in March 2025, and it’s on track to become Widely available in 2027. So this one fails question 1 for broad-audience apps unless you check your traffic first or add a fallback. For an internal tool on modern browsers, it’s fine today. For a public site with old devices, give it another year or guard it with a feature check.</p>

<h3 id="the-math-on-this-cluster">The Math On This Cluster</h3>

<p>If your app uses the full set (<code>humanize-duration</code>, <code>timeago.js</code>, <code>pluralize</code>, <code>numeral</code>), that’s roughly <strong>14 KB gzipped</strong> of dependencies, most of it replaceable right now with Widely available APIs. The internationalization cluster is usually the easiest win in the whole audit.</p>

<div class="partners__lead-place"></div>

<h2 id="cluster-2-http-clients">Cluster 2: HTTP Clients</h2>

<p>This cluster is more nuanced, so it’s a good one to slow down on.</p>

<p>The browser HTTP libraries people reach for are <code>axios</code> (17 KB gz) and <code>superagent</code> (19 KB gz). For most requests, <code>fetch</code> plus <code>AbortController</code> covers what you need, and both are Widely available.</p>

<p>A basic GET looks like this:</p>

<pre><code class="language-javascript">// axios
const { data } = await axios.get("/api/users");

// fetch
const res = await fetch("/api/users");
const data = await res.json();
</code></pre>

<p>The one extra line (<code>res.json()</code>) is <code>fetch</code> being explicit where <code>axios</code> was implicit. That’s the pattern across this whole cluster: <code>fetch</code> does less for you by default, and you decide whether you want the things it leaves out.</p>

<h3 id="timeouts">Timeouts</h3>

<p><code>axios</code> has a <code>timeout</code> option. <code>fetch</code> has <code>AbortSignal.timeout()</code>:</p>

<pre><code class="language-javascript">const res = await fetch("/api/users", {
  signal: AbortSignal.timeout(5000), // abort after 5 seconds
});
</code></pre>

<h3 id="where-fetch-doesn-t-replace-axios">Where <code>fetch</code> Doesn’t Replace <code>axios</code></h3>

<p>This is where question 3 does most of the work, so let’s be specific about the gaps:</p>

<ul>
<li><strong><code>fetch</code> doesn’t reject on HTTP errors.</strong><br />
A <code>404</code> or <code>500</code> is a resolved promise, not a rejection. You have to check <code>res.ok</code> yourself. <code>axios</code> rejects on any non-2xx status.</li>
<li><strong>No interceptors.</strong><br />
If you rely on <code>axios</code> interceptors to attach auth tokens or handle 401s in one place, <code>fetch</code> has no equivalent. You’d wrap <code>fetch</code> in your own function or class to get the same behavior.</li>
<li><strong>No automatic retries.</strong><br />
<code>axios</code> (with a plugin) can retry failed requests. With <code>fetch</code>, that’s your code to write.</li>
<li><strong>No upload progress.</strong><br />
<code>fetch</code> still can’t report upload progress in a first-class way. If you have a file uploader with a progress bar, that’s a real reason to keep a library.</li>
</ul>

<p>I personally heavily rely on <em>interceptors</em> in my interactive online courses, such as <a href="https://learnjavascript.online/">Learn JavaScript</a>, and I have solved that for years using a custom <code>class</code> on top of <code>fetch</code>. I’ve shipped this to millions of users and have seen lots of success with it.</p>

<p>None of these are hard to rebuild, and most apps only use one or two of them. But this is exactly the kind of cluster where you shouldn’t do a blind find-and-replace. Look at how you actually use your HTTP client first. If it’s plain GETs and POSTs, dropping <code>axios</code> for a thin <code>fetch</code> wrapper saves you about <strong>17 KB gzipped</strong>.</p>

<h2 id="cluster-3-ui-primitives">Cluster 3: UI Primitives</h2>

<p>This cluster has some of the most satisfying swaps, because the platform features don’t just match the libraries, they’re often more accessible than what teams ship by hand.</p>

<p>The libraries here are modal dialogs (something like <code>a11y-dialog</code>, 1.8 KB gz), tooltip and popover libraries (<code>tippy.js</code>, 14 KB gz, which bundles Popper for positioning), <code>focus-trap</code> (6.6 KB gz), and <code>body-scroll-lock</code> (1.3 KB gz). They get replaced by three platform features: the <code>&lt;dialog&gt;</code> element, the Popover API, and CSS anchor positioning.</p>

<h3 id="the-dialog-element">The <code>&lt;dialog&gt;</code> Element</h3>

<p>A huge amount of modal-related code exists to solve accessibility problems: trapping focus inside the modal, closing on <code>Escape</code>, restoring focus to the previous element when the dialog is closed, and rendering above everything else. The <code>&lt;dialog&gt;</code> element, Widely available, does all of that for you.</p>

<div class="break-out">
<pre><code class="language-javascript">&lt;dialog id="confirm"&gt;
  &lt;form method="dialog"&gt;
    &lt;p&gt;Delete this file?&lt;/p&gt;
    &lt;button value="cancel"&gt;Cancel&lt;/button&gt;
    &lt;button value="delete"&gt;Delete&lt;/button&gt;
  &lt;/form&gt;
&lt;/dialog&gt;

const dialog = document.querySelector("&#35;confirm");

dialog.showModal(); // focus moves in, background goes inert, Escape closes it

dialog.addEventListener("close", () =&gt; {
  console.log(dialog.returnValue); // "cancel" or "delete"
});
</code></pre>
</div>

<p>Calling <code>showModal()</code> does the work that <code>focus-trap</code> was installed for: focus moves into the dialog, the rest of the page becomes inert so you can’t tab out of it, <code>Escape</code> closes it, and focus returns to the element that opened it. The dialog renders in the browser’s <em>Top layer</em>, so you don’t fight <code>z-index</code>. You also get a <code>::backdrop</code> pseudo-element to style the overlay.</p>

<p>That single element can replace your modal library <em>and</em> <code>focus-trap</code>. The one piece it doesn’t handle on its own is locking the background from scrolling, which is what <code>body-scroll-lock</code> was for. That’s now one line of CSS:</p>

<pre><code class="language-css">body:has(dialog:modal) {
  overflow: hidden;
}
</code></pre>

<p>If you’re wondering why we’re using <code>dialog:modal</code> instead of <code>dialog[open]</code>, it’s because the <code>open</code> attribute is set as soon as you call <code>show()</code>, but the dialog isn’t actually <em>modal</em> so you don’t want to lock scrolling yet. The <code>:modal</code> pseudo-class is only true when the dialog is actually <em>modal</em>, which is the case when you call <code>showModal()</code>.</p>

<p>So three libraries collapse into one element and one CSS rule.</p>

<h3 id="popover-api-and-anchor-positioning">Popover API And Anchor Positioning</h3>

<p>For things that aren’t full modals (dropdown menus, tooltips, the small floating panels that <code>tippy.js</code> handles), the <a href="https://www.smashingmagazine.com/2026/03/getting-started-popover-api/">Popover API</a> gives you light-dismiss behavior, top-layer rendering, and <code>Escape</code>-to-close with no JavaScript at all:</p>

<pre><code class="language-html">&lt;button popovertarget="menu" id="options"&gt;Options&lt;/button&gt;

&lt;div id="menu" popover&gt;
  &lt;!-- menu content --&gt;
&lt;/div&gt;
</code></pre>

<p>Clicking the button toggles the popover. Clicking outside it closes it. It’s Baseline Newly available (since January 2025).</p>

<p>The other half of what a tooltip library does is <em>positioning</em>: keeping the floating element pinned to its trigger and flipping it when it would overflow the viewport. That’s what Popper (bundled inside <code>tippy.js</code>) handles, and it’s now a CSS feature called anchor positioning. Here it pins the same <code>#menu</code> popover directly under its trigger button:</p>

<pre><code class="language-css">&#35;options {
  anchor-name: --trigger;
}

.tooltip {
  position-anchor: --trigger;
  position-area: top;
  margin: 0;
}
</code></pre>

<p>Anchor positioning is the newest feature in this article. It became Baseline Newly available in January 2026, when Firefox 147 shipped it (Chrome had it since version 125, and Safari since version 26). Because it’s this fresh, it’s squarely a question-1 feature: great for modern audiences, but check your traffic, and note that some of the more advanced parts (like position-try fallbacks) have uneven support across versions. Keep a sensible fallback for older browsers.</p>

<p>Between <code>&lt;dialog&gt;</code>, the Popover API, and anchor positioning, the UI primitives cluster (tooltip library, modal library, <code>focus-trap</code>, <code>body-scroll-lock</code>) adds up to roughly <strong>24 KB gzipped</strong>, and you come out the other side with better accessibility defaults than most hand-rolled solutions.</p>

<div class="partners__lead-place"></div>

<h2 id="cluster-4-lodash-utilities">Cluster 4: Lodash Utilities</h2>

<p>Lodash is rarely imported whole anymore, but its individual functions show up everywhere, either as the full <code>lodash</code> package (25 KB gz) or as standalone installs like <code>lodash.clonedeep</code> and <code>lodash.groupby</code>. Several of the most common ones now have direct platform equivalents.</p>

<h3 id="grouping">Grouping</h3>

<p><code>lodash.groupby</code> reorganizes an array into an object keyed by some property. <code>Object.groupBy</code> does exactly that:</p>

<pre><code class="language-javascript">const products = [
  { name: "Apple", category: "fruit" },
  { name: "Carrot", category: "vegetable" },
  { name: "Banana", category: "fruit" },
];

const grouped = Object.groupBy(products, (product) =&gt; product.category);
// {
//   fruit: [{ name: "Apple", ... }, { name: "Banana", ... }],
//   vegetable: [{ name: "Carrot", ... }],
// }
</code></pre>

<p>There’s also <code>Map.groupBy</code> for when you want a <code>Map</code> instead of a plain object (handy if your keys aren’t strings). Both are Baseline Newly available, since March 2024, and on track to become Widely available in late 2026.</p>

<h3 id="deep-cloning">Deep Cloning</h3>

<p><code>lodash.clonedeep</code> makes a deep copy of an object. <code>structuredClone</code> is the platform version, and it’s Widely available:</p>

<pre><code class="language-javascript">const original = { user: { name: "Sam", roles: ["admin"] } };

const copy = structuredClone(original);
copy.user.roles.push("editor");

original.user.roles; // ["admin"] (unchanged)
</code></pre>

<p><code>structuredClone</code> handles the tricky cases that trip up <code>JSON.parse(JSON.stringify(...))</code>: it clones <code>Date</code>, <code>Map</code>, <code>Set</code>, <code>ArrayBuffer</code>, and circular references correctly. The limit to know about (question 3 again) is that it can’t clone functions, DOM nodes, or class instances; it throws on functions and drops the prototype on class instances. For plain data, which is what most people deep-clone, it’s a clean replacement.</p>

<h3 id="set-operations">Set Operations</h3>

<p>If you’ve ever pulled in a Lodash helper for <code>union</code>, <code>intersection</code>, or <code>difference</code>, the <code>Set</code> object now has these built in. They’re Baseline Newly available, since June 2024:</p>

<pre><code class="language-javascript">const admins = new Set(["sam", "alex", "jo"]);
const editors = new Set(["alex", "kim"]);

admins.intersection(editors); // Set { "alex" }
admins.union(editors); // Set { "sam", "alex", "jo", "kim" }
admins.difference(editors); // Set { "sam", "jo" }
</code></pre>

<p>The full set of methods is <code>union</code>, <code>intersection</code>, <code>difference</code>, <code>symmetricDifference</code>, <code>isSubsetOf</code>, <code>isSupersetOf</code>, and <code>isDisjointFrom</code>.</p>

<h3 id="what-s-worth-keeping">What’s Worth Keeping</h3>

<p>Not all of Lodash has moved into the platform. <code>debounce</code> and <code>throttle</code> still have no native equivalent, and they’re genuinely useful, so cherry-picking <code>lodash.debounce</code> is reasonable. The point of this cluster isn’t “delete Lodash,” it’s “stop shipping the parts the browser already has.” Dropping <code>lodash.clonedeep</code> and <code>lodash.groupby</code> alone is about <strong>8 KB gzipped</strong>, and if you were importing the full <code>lodash</code> for a handful of functions, replacing the platform-covered ones can let you drop it entirely.</p>

<h2 id="cluster-5-temporal-a-case-study-in-not-dropping-a-library-yet">Cluster 5: Temporal, A Case Study In Not Dropping A Library Yet</h2>

<p>Every cluster so far has ended in “go ahead, drop it.” This one is the opposite, and that&rsquo;s why it&rsquo;s worth including: it shows the framework telling you to wait.</p>

<p><code>Temporal</code> is the long-awaited replacement for JavaScript&rsquo;s <code>Date</code>, and it&rsquo;s a genuinely better API: immutable objects, sane time zone handling, and no more month indexes starting at zero. It reached TC39 Stage 4 in March 2026 and is part of the ES2026 specification. Firefox shipped it in version 139 (in 2025), and Chrome shipped it in version 144 (January 2026). Safari hasn&rsquo;t shipped it in a stable release yet; it&rsquo;s in Safari Technology Preview, with stable support expected later in 2026.</p>

<p>If Temporal is news to you, check out the <a href="https://learnjavascript.online/temporal.html">Temporal Cheatsheet</a> for a quick overview of the API and a comparison to <code>Date</code>.</p>

<p>However, <code>Temporal</code> is <em>not</em> Baseline. It&rsquo;s still in <em>limited availability</em>, because Safari users don&rsquo;t have it. To use it across all browsers today, you need a polyfill, and this is where the math turns against you.</p>

<p>The official <code>@js-temporal/polyfill</code> is about <strong>44 KB gzipped</strong>. There&rsquo;s a smaller polyfill that internally does not depend on BigInt and it weighs <strong>19 KB gzipped</strong>. A lightweight date library like <code>dayjs</code> is about <strong>3 KB gzipped</strong>. So if you swap <code>dayjs</code> for <code>Temporal</code> plus its polyfill right now, you&rsquo;re not saving 3 KB, you&rsquo;re <em>adding</em> roughly 41 KB to your bundle, unless you are able to load the polyfill conditionally.</p>

<p>Run it through the framework:</p>

<ul>
<li><strong>Question 1 (audience):</strong> Temporal isn&rsquo;t Baseline. For a broad audience, that&rsquo;s a lot of people.</li>
<li><strong>Question 2 (cost):</strong> the polyfill is more than ten times the size of the library you&rsquo;d remove. The swap makes your bundle bigger.</li>
<li><strong>Question 3 (feature gap):</strong> Temporal actually wins here; it does more than <code>dayjs</code>. But that doesn&rsquo;t matter while questions 1 and 2 are failing.</li>
</ul>

<p>The verdict is generally clear: keep <code>dayjs</code> (or <code>date-fns</code>) for now. The moment to revisit is when Safari ships Temporal in a stable release and it reaches Baseline. At that point you can use Temporal natively and conditionally load the polyfill for users on older browsers. This is a feature to write down and check again in a few months, not one to act on today.</p>

<h2 id="how-to-run-this-audit-on-your-own-package-json">How To Run This Audit On Your Own <code>package.json</code></h2>

<p>The clusters above are a starting map, but your dependencies are your own. Here&rsquo;s a repeatable process you can run this quarter.</p>

<h3 id="step-1-list-your-production-dependencies">Step 1: List Your Production Dependencies</h3>

<p>Start by listing what actually ships to users:</p>

<pre><code class="language-bash">npm ls --omit=dev --depth=0
</code></pre>

<h3 id="step-2-measure-what-each-one-costs">Step 2: Measure What Each One Costs</h3>

<p>For a quick per-package number, <a href="https://bundlephobia.com/">Bundlephobia</a> gives you the minified and gzipped size of any npm package. For the real picture (what each dependency costs <em>in your actual bundle</em>, after tree-shaking and deduplication), run a bundle analyzer against your build. <code>npx source-map-explorer</code> works on most bundles, and <code>npx vite-bundle-visualizer</code> works for Vite projects.</p>














<figure class="
  
    break-out article__image
  
  
  ">
  
    <a href="https://files.smashing.media/articles/how-baseline-can-help-ship-less-javascript/2-bundlephobia-website.png">
    
    <img
      loading="lazy"
      decoding="async"
      fetchpriority="low"
			width="800"
			height="447"
			
			srcset="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/how-baseline-can-help-ship-less-javascript/2-bundlephobia-website.png 400w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_800/https://files.smashing.media/articles/how-baseline-can-help-ship-less-javascript/2-bundlephobia-website.png 800w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1200/https://files.smashing.media/articles/how-baseline-can-help-ship-less-javascript/2-bundlephobia-website.png 1200w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1600/https://files.smashing.media/articles/how-baseline-can-help-ship-less-javascript/2-bundlephobia-website.png 1600w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_2000/https://files.smashing.media/articles/how-baseline-can-help-ship-less-javascript/2-bundlephobia-website.png 2000w"
			src="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/how-baseline-can-help-ship-less-javascript/2-bundlephobia-website.png"
			
			sizes="100vw"
			alt="Bundlephobia website showing that axios weighs 44kb minified and 16.6kb minified &amp; gzipped. Such package takes 331ms to download on slow 3G and 19ms on emerging 4G."
		/>
    
    </a>
  

  
    <figcaption class="op-vertical-bottom">
      (<a href='https://files.smashing.media/articles/how-baseline-can-help-ship-less-javascript/2-bundlephobia-website.png'>Large preview</a>)
    </figcaption>
  
</figure>

<h3 id="step-3-check-the-baseline-status-of-each-replacement">Step 3: Check The Baseline Status Of Each Replacement</h3>

<p>For each candidate, find the platform feature that would replace it and check its Baseline status. The quickest way is<a href="https://webstatus.dev/"> webstatus.dev</a> or the Baseline badge on the feature&rsquo;s MDN page.</p>

<h3 id="step-4-run-the-three-questions">Step 4: Run The Three Questions</h3>

<p>For each library with a platform replacement, go back to the framework: Is it Baseline-safe for your audience? What does the swap cost? Does the feature cover how you actually use the library? Most of your decisions will fall out of question 1 (check the feature&rsquo;s status against your <code>browserslist</code>) and question 3 (check your own usage).</p>

<h3 id="step-5-swap-behind-progressive-enhancement-where-needed">Step 5: Swap Behind Progressive Enhancement Where Needed</h3>

<p>For Widely available features, swap and move on. For Newly available ones, either confirm your audience is on modern browsers or guard the new code with a quick feature check and keep a fallback:</p>

<pre><code class="language-javascript">if (typeof Intl.DurationFormat === "function") {
  // use the platform feature
} else {
  // fall back to the library, or a simpler format
}
</code></pre>

<p>That way you ship less code to the users who can run it, without breaking the ones who can&rsquo;t.</p>

<h2 id="wrapping-up">Wrapping Up</h2>

<p>Add the clusters up, and the picture is concrete. The internationalization cluster is around 14 KB gzipped, HTTP is around 17 KB, the UI primitives are around 24 KB, and the Lodash utilities are 8 KB or more depending on how much of the library you were shipping. For a typical mid-sized app, that&rsquo;s somewhere between 60 KB and 90 KB gzipped of dependencies you can hand back to the platform, and more if you were shipping the full <code>lodash</code> or several of these libraries at once. (The uncompressed numbers are two to three times larger, which is what you&rsquo;ll see in a bundle analyzer before gzip.)</p>

<p>I&rsquo;ve chosen relatively lean packages for most of these features, but some individual packages could still be heavy. Your dialog package, for instance, could alone weigh as much as 50KB gzipped depending on what you&rsquo;re using.</p>

<p>A few features are worth keeping an eye on over the next year, because they&rsquo;ll open up further swaps:</p>

<ul>
<li><strong>Temporal going native.</strong><br />
Once Safari ships it in a stable release and it reaches Baseline, you can drop both your date library <em>and</em> the polyfill, turning today&rsquo;s regression into a real win.</li>
<li><strong>CSS anchor positioning maturing.</strong><br />
It became Baseline Newly available in January 2026. As it ages toward Widely available, dropping tooltip and popover positioning libraries gets safer for broad audiences.</li>
<li><strong><code>Object.groupBy</code> and friends crossing into Widely available.</strong><br />
The 2024 batch (array grouping, Set methods) is on track to become Widely available in late 2026, which moves them from &ldquo;check your audience&rdquo; to &ldquo;just use it.&rdquo;</li>
</ul>

<p>None of this is a one-time cleanup. The platform ships new features constantly, and the gap between <em>&ldquo;you need a library for this&rdquo;</em> and <em>&ldquo;the browser does this&rdquo;</em> keeps closing. The habit worth building is small: once a quarter, run the audit. List your dependencies, check what&rsquo;s now Baseline, and hand back what you can.</p>

<p>Pick one cluster from this article, open your <code>package.json</code>, and see how much of it the browser already does for you.</p>

<div class="signature">
  <img src="https://www.smashingmagazine.com/images/logo/logo--red.png" alt="Smashing Editorial" width="35" height="46" loading="lazy" decoding="async" />
  <span>(yk)</span>
</div>


              </article>
            </body>
          </html>
        ]]></content:encoded></item><item><author>Victor Ayomipo</author><title>When It Makes Sense To “Block” The Main Thread</title><link>https://www.smashingmagazine.com/2026/07/when-makes-sense-block-main-thread/</link><pubDate>Fri, 17 Jul 2026 08:00:00 +0000</pubDate><guid>https://www.smashingmagazine.com/2026/07/when-makes-sense-block-main-thread/</guid><description>The common rule of thumb is to never “block” the browser’s main thread when running JavaScript tasks. But is this a hard rule? Victor Ayomipo describes a use case he encountered involving a screenshot extension where he made an exception to the rule and decided that blocking the main thread was absolutely the right thing to do.</description><content:encoded><![CDATA[
          <html>
            <head>
              <meta charset="utf-8">
              <link rel="canonical" href="https://www.smashingmagazine.com/2026/07/when-makes-sense-block-main-thread/" />
              <title>When It Makes Sense To “Block” The Main Thread</title>
            </head>
            <body>
              <article>
                <header>
                  <h1>When It Makes Sense To “Block” The Main Thread</h1>
                  
                    
                    <address>Victor Ayomipo</address>
                  
                  <time datetime="2026-07-17T08:00:00&#43;00:00" class="op-published">2026-07-17T08:00:00+00:00</time>
                  <time datetime="2026-07-17T08:00:00&#43;00:00" class="op-modified">2026-11-13T04:40:45+00:00</time>
                </header>
                
                

<p>We’ve all heard of the sacred rule in modern web development, the rule never to be broken. The rule of <em>“Never block the main thread.”</em></p>

<p>You almost can’t miss it as a web developer; it’s in almost every performance guide, and to be fair, it is good advice. We all know the browser’s main thread is <strong>single-threaded</strong>, meaning it can only do one thing at a time.</p>

<p>Plus, as we know, <a href="https://www.smashingmagazine.com/2023/10/speedcurve-fight-main-thread/">the main thread isn’t ours alone</a>; we share it with the browser’s rendering engine, input handlers, and other critical tasks. As a result, the less time we hold onto the main thread, the more responsive an app feels. That leads us to share tasks with background workers as we’ve convinced ourselves there should be a hard line between the UI and any computation, and that line shouldn’t be crossed.</p>

<p>And that is what a “recommended” architecture looks like.</p>

<p>But I dare say that *sometimes*<em>,</em> moving the data to a worker is slower than just letting the main thread do the work.</p>

<p>I found this out a few months ago while building a Chrome extension with screenshotting features called Fastary. I kept finding a latency of about 2 to 3 seconds in all my testing, even after using an <a href="https://developer.chrome.com/docs/extensions/reference/api/offscreen#main-content">Offscreen Document</a> (a background process in Chrome extensions) to handle the canvas operations. A screenshot task should feel instant without lag, after all.</p>

<p>It is quite ironic that by reflex, we move work away from the main thread to avoid freezing the UI, but sometimes the act of moving that work (e.g., serializing, copying, and deserializing) can also freeze the UI. And <em>sometimes</em> the recommended approach of letting the background do the work can be slower than just doing the work on the main thread.</p>

<p>Let’s talk about that.</p>

<div data-audience="non-subscriber" data-remove="true" class="feature-panel-container">

<aside class="feature-panel" style="">
<div class="feature-panel-left-col">

<div class="feature-panel-description"><p>Meet <strong><a data-instant href="/printed-books/typescript-in-50-lessons/">“TypeScript in 50 Lessons”</a></strong>, our shiny new guide to TypeScript. With detailed <strong>code walkthroughs</strong>, hands-on examples and common gotchas. For developers who know enough <strong>JavaScript</strong> to be dangerous.</p>
<a data-instant href="/printed-books/typescript-in-50-lessons/" class="btn btn--green btn--large" style="">Jump to table of contents&nbsp;↬</a></div>
</div>
<div class="feature-panel-right-col"><a data-instant href="/printed-books/typescript-in-50-lessons/" class="feature-panel-image-link">
<div class="feature-panel-image"><picture><source type="image/avif" srcSet="https://archive.smashing.media/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/2732dfe9-e1ee-41c3-871a-6252aeda741c/typescript-panel.avif" />
<img
    loading="lazy"
    decoding="async"
    class="feature-panel-image-img"
    src="https://archive.smashing.media/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/c2f2c6d6-4e85-449a-99f5-58bd053bc846/typescript-shop-cover-opt.png"
    alt="Feature Panel"
    width="481"
    height="698"
/>
</picture>
</div>
</a>
</div>
</aside>
</div>

<h2 id="the-architecture-of-browser-context-isolation">The Architecture Of Browser Context Isolation</h2>

<p>To put things in perspective, let’s understand why we isolate browser contexts and how they communicate with each other, with emphasis on the <em>communication</em> part.</p>

<p>A browser is more than a single environment. Different environments are running at the same time, each having its own memory space, what it can access, and rules:</p>

<ul>
<li>The <strong>main thread</strong> is what we are most familiar with; this is where JavaScript logic runs, where the DOM lives, where styles get rendered, and where users interact.</li>
<li>The <strong>Web Workers</strong> are separate threads that can also execute JavaScript without DOM access. We mostly use this for heavy data tasks.</li>
<li>The <strong>Service Workers</strong> are network-related proxies in charge of intercepting network requests and can even run when the page is closed.</li>
<li>And then there are <strong>Chrome extension contexts</strong>, where we have background service workers, content scripts, and Offscreen Documents (the relevant ones for this article).</li>
</ul>

<p>Each one of these is isolated from the others. A web worker or background script lives in a different memory space from the main thread. They cannot just reach and read each other’s variables or logic, and this is known as the <strong>“shared-nothing” architecture</strong>.</p>

<p>How do these isolated environments communicate? They explicitly message each other back and forth using APIs, like <code>postMessage()</code>.</p>

<h3 id="the-structured-clone-algorithm">The Structured Clone Algorithm</h3>

<p><code>postMessage()</code> tells the browser to take a piece of data and deliver it to the context that requested it. But to do this, the browser relies on the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">Structured Clone Algorithm (SCA)</a>.</p>

<p>You’re probably familiar with <code>JSON.stringify()</code>. SCA is similar, but much stronger and smarter. In its simplest form, SCA is a deep, recursive copy operation, i.e., cloning. It walks through the entire data structure it is given, clones every single value, serializes it into a transportable format, ships those bytes to the target contexts, and then reconstructs the original object on the receiving side.</p>

<p>SCA is fast, or maybe fast-<em>ish</em>&hellip; For a small regular config object like <code>{theme: &quot;dark&quot;}</code>, it is imperceptible; you don’t even notice it. The story changes, however, when dealing with heavy data because the SCA is a synchronous blocking <code>O(n)</code> operation, i.e., the cost increases linearly with the size of your data.</p>

<p>Let’s put that into perspective. A user clicks a button, and internally, an 8MB image payload is sent to a background worker for processing. When you call <code>postMessage()</code>, the main thread must immediately stop what it is doing to run this serialization and copying process.</p>

<blockquote>So, if the time it takes to pack, ship, unpack the data, and go back to the start is <stronger>longer</stronger> than the time to just process the data on the main thread, why not do that instead?</blockquote>

<h2 id="what-about-transferable-objects">What About Transferable Objects?</h2>

<p>I’m sure some of you are already thinking, <em>“Why not just use Transferable objects?”</em> And that is a valid point. Let’s talk about that.</p>

<p>Developers who really pursue ultra-high-performance web apps usually use <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Transferable_objects">Transferable objects</a> (e.g., <code>ArrayBuffer</code>, <code>ImageBitmap</code>, or <code>MessagePort</code>) to bypass the Structured Clone Algorithm. This is because when you transfer an object, you’re not making a copy (like SCM). Instead, the browser switches ownership of the data from one context to another.</p>

<p>The browser performs a hand-off whereby the sending context loses access to the data instantly, and the receiving context takes full control. It is actually insanely fast. According to <a href="https://developer.chrome.com/blog/transferable-objects-lightning-fast#benchmark_demo">Chrome Developers’ benchmark</a>, transferring a massive 32MB <code>ArrayBuffer</code> can take under 7ms, compared to about 300ms when cloning with SCM. That’s a 43x speed boost.</p>














<figure class="
  
  
  ">
  
    <a href="https://developer.chrome.com/blog/transferable-objects-lightning-fast#benchmark_demo">
    
    <img
      loading="lazy"
      decoding="async"
      fetchpriority="low"
			width="800"
			height="315"
			
			srcset="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/when-makes-sense-block-main-thread/1-structured-cloning-transferable-objects.png 400w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_800/https://files.smashing.media/articles/when-makes-sense-block-main-thread/1-structured-cloning-transferable-objects.png 800w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1200/https://files.smashing.media/articles/when-makes-sense-block-main-thread/1-structured-cloning-transferable-objects.png 1200w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1600/https://files.smashing.media/articles/when-makes-sense-block-main-thread/1-structured-cloning-transferable-objects.png 1600w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_2000/https://files.smashing.media/articles/when-makes-sense-block-main-thread/1-structured-cloning-transferable-objects.png 2000w"
			src="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/when-makes-sense-block-main-thread/1-structured-cloning-transferable-objects.png"
			
			sizes="100vw"
			alt="Structured cloning vs. Transferable Objects by Chrome Developers"
		/>
    
    </a>
  

  
    <figcaption class="op-vertical-bottom">
      Structured cloning vs. Transferable Objects by Chrome Developers. (Image source: <a href='https://developer.chrome.com/blog/transferable-objects-lightning-fast#benchmark_demo'>Chrome for Developers</a>) (<a href='https://files.smashing.media/articles/when-makes-sense-block-main-thread/1-structured-cloning-transferable-objects.png'>Large preview</a>)
    </figcaption>
  
</figure>

<p>But like all good things, there are downsides. To name a few:</p>

<ul>
<li><strong>You lose it once you send it.</strong><br />
If the UI still needs that data (like to show an image preview), you can’t access it anymore.</li>
<li><strong>Not all data is transferable.</strong><br />
A plain JS object is not. A Blob is not. Even a Base64 string is not.</li>
<li><strong>API limitations.</strong><br />
In the context of browser extensions, Chrome’s internal messaging (<code>chrome.runtime.sendMessage</code>) traditionally forces everything through JSON serialization.</li>
</ul>

<p>So, as far as my screenshot extension went, Transferable objects were not an option.</p>

<div class="partners__lead-place"></div>

<h2 id="why-we-isolate-contexts-anyway">Why We Isolate Contexts Anyway</h2>

<p>Why do we even bother isolating contexts at all? Why not just leave it all to the main thread?</p>

<p>Offloading long-running CPU tasks to a background thread is absolutely the right thing to do. The browser needs to paint a new frame <strong>every 16.6ms</strong> to keep things fluid; that means <a href="https://developer.mozilla.org/en-US/docs/Glossary/Long_task#:~:text=A%20long%20task%20is%20a%20task%20that%20takes%20more%20than%2050ms%20to%20complete.">any task that takes &gt;50ms is generally considered “long”</a>. Offloading to the background is absolutely the right thing to do.</p>

<p>The issue, however, is that we’ve turned this <em>“never block the main thread”</em> into an absolute rule, without asking <em>is this task expensive to process or expensive to move?</em></p>

<blockquote class="pull-quote">
  <p>
    <a class="pull-quote__link" aria-label="Share on Twitter" href="https://twitter.com/share?text=%0aI%20have%20come%20to%20realize%20now%20that%20the%20rule%20is%20less%20%e2%80%9cnever%20block%20the%20main%20thread%e2%80%9d%20than%20%e2%80%9cnever%20block%20the%20main%20thread%20for%20too%20long.%e2%80%9d%0a&url=https://smashingmagazine.com%2f2026%2f07%2fwhen-makes-sense-block-main-thread%2f">
      
I have come to realize now that the rule is less “never block the main thread” than “never block the main thread for too long.”

    </a>
  </p>
  <div class="pull-quote__quotation">
    <div class="pull-quote__bg">
      <span class="pull-quote__symbol">“</span></div>
  </div>
</blockquote>

<h2 id="when-the-right-architecture-is-the-wrong-architecture">When The Right Architecture Is The Wrong Architecture</h2>

<p>My goal with the Fastary extension was to make it feel like a native app, running as smoothly and instantly as you would expect a native app to.</p>

<p>As you already know, I took <a href="https://developer.chrome.google.cn/blog/Offscreen-Documents-in-Manifest-v3">the recommended approach</a> to use the Offscreen Document to handle DOM work in the background. But to my surprise, that took a different turn.</p>

<p>The Offscreen Document API is a clear winner. You create a hidden, undisplayed document that runs entirely in the background. It has a DOM and supports Canvas. For example, if I want to crop a screenshot, stitch multiple screenshots together, perform heavy image manipulation, or add a watermark, Offscreen Document was made for that.</p>

<p>Turns out that was not the best approach. This was my architecture:</p>

<ol>
<li>The background Service Worker captures a screenshot with <code>chrome.tabs.captureVisibleTab()</code>, which returns a Base64-encoded data URL string.</li>
<li>The background Service Worker uses <code>chrome.runtime.sendMessage()</code> to ship this image payload to the Offscreen Document.</li>
<li>The Offscreen Document receives the image, loads it into an <code>&lt;img&gt;</code> element, then draws it onto a canvas before it applies the user’s crop coordinates, encodes the result, and sends the processed image back to the background worker.</li>
</ol>

<p>But when I tested it, the screenshot didn’t feel instant. As I said earlier, there was a consistent 2&ndash;3 second lag.</p>

<p>I figured out that when <code>captureVisibleTab()</code> takes a screenshot, it returns a Base64 URL string, and on a standard 1080p screen, that string could be approximately 1MB or more, depending on how detailed the image is. It gets even more interesting on modern Retina displays (e.g., MacBooks) as they tend to automatically double the image’s size by default.</p>

<p>Keep in mind that since the image payload could be doubled and extension messaging relies on JSON serialization (as of this writing), we potentially deal with <strong>massive synchronous communication</strong> that costs an entire round trip.</p>

<p>The image string data is JSON-serialized at least twice: once when going into the Offscreen Document and once coming back out with the processed results to the background worker. The actual image processing (cropping) done inside the Offscreen Document was fast, no doubt, but I can’t say the same about the transfer overhead.</p>

<h3 id="the-retina-high-dpi-problem">The Retina High-DPI Problem</h3>

<p>As if the latency itself wasn’t enough, I noticed a rather subtle bug &mdash; which, now that I think of it, was more of my ignorance. After a screenshot was taken, the crop result was completely off in a way that either weirdly scaled the image or resulted in incorrect coordinates.</p>

<p>It turns out that when a user selects a region to crop, the content script gets the box coordinates using <code>getBoundingClientRect()</code>, which is measured in <strong>CSS pixels</strong>; this is what the DOM uses. But when the screenshot is captured natively in Chrome, the browser doesn’t crop it automatically; it instead uses the <strong>physical hardware pixels</strong> to get the full screen capture. And the browser uses <code>devicePixelRatio</code> (DPR) to know how many physical pixels should represent one CSS pixel. Basically, if a user on a Retinal display (DPR = 2) highlights an area of 400x300 CSS pixels, the actual captured image area is 800x600 physical pixels.</p>

<blockquote><strong>Note:</strong> One CSS pixel is equal to 1 physical pixel (DPR of 1) on a standard monitor. On a Mac Retina display or a modern 4K monitor, however, the DPR is usually 2 or 3.</blockquote>

<p>For an accurate crop, I needed to apply these two different measurement systems with the right DPR, i.e., scale the crop coordinates by the DPR. But remember, Offscreen Documents have no physical display. Processing any image would have a default DPR equal to 1. To fix this, I would have to capture the exact <code>devicePixelRatio</code> from the active tab, serialize it, pass it alongside the image payload, and manually do the scaling math inside the Offscreen Document. The complexity starts to compound.</p>

<p><em>What if I broke the golden rule and did the work on the main thread instead?</em></p>

<h2 id="working-on-the-main-thread">Working On The Main Thread</h2>

<p>Some developers will argue that UI tasks are the only things that should run on the main thread, but I don’t fully agree with that. Personally, I believe that user explicitly-invoked actions that need immediate results can sometimes get a solid pass to run on the main thread, provided the work is incredibly <em>fast</em> (e.g., 1s).</p>

<p>That’s what I did: scrap out the Offscreen Document and reengineer the logic. Instead of:</p>

<div class="break-out">
<pre><code class="language-markdown">Background → [serialize] → Offscreen Document → [serialize] → Background → Content Script</code></pre>
</div>

<p>…I decided to run the whole image processing in the active tab:</p>

<ol>
<li>The background Service Worker captures the screen and gets the Base64 string (same as before).</li>
<li>The background sends the payload directly to the content script in the active tab using <code>chrome.scripting.executeScript()</code>.</li>
<li>The content script (running on the main thread) receives the payload, draws it to a canvas, performs the crop using the correct DPR value, and copies the result to the clipboard.</li>
</ol>

<div class="break-out">
<pre><code class="language-javascript">// Background Script
const screenshotUrl = await chrome.tabs.captureVisibleTab(undefined, { format: "png" });

// Inject the processing function into the active tab as a content script
await chrome.scripting.executeScript({
  target: { tabId: activeTab.id },
  func: processAndCopyImage,
  args: [{ base64Image: screenshotUrl, cropData: userSelection }]
});
</code></pre>
</div>

<p>This approach completely clears out multiple context hops and round trips that JSON serialization requires. The only cross-context transfer involves sending the data URL from the background to the content script.</p>

<p>The Retina DPI issue essentially solved itself, as the content script runs directly inside the real, active browser tab because it knows the monitor’s real <code>devicePixelRatio</code>.</p>

<p>But there’s an elephant in the room that you may have noticed.</p>

<p>Sure, the image is now processed on the main thread, and the background manipulates the canvas in the active tab. I could technically be blocking the main thread. That’s where I amended the “no blocking the main thread” rule to “no blocking the main thread <em>for too long</em>.” In this specific case, at least, blocking the main thread for a task the user requests for approximately one second is justifiable. It works conversely as well: maybe <strong>don’t isolate processes if the data transfer cost is greater than the processing cost</strong>.</p>

<div class="partners__lead-place"></div>

<h2 id="conclusion-when-to-isolate-and-when-not-to">Conclusion: When To Isolate And When Not To</h2>

<p>I’ve boiled it down to a mental model that depends on whether the task is:</p>

<h3 id="1-compute-heavy-tasks-cpu-bound">1. Compute-Heavy Tasks (CPU-Bound)</h3>

<p>These are tasks where the primary cost is computation and not the size of the data itself. These are tasks where most of the time is spent on doing calculations or heavy transformations, e.g., image compression, audio profiling, physics simulation, etc.</p>

<p>The transfer cost for these tasks is minuscule compared to the actual work.</p>

<h3 id="2-data-heavy-tasks-data-bound">2. Data-Heavy Tasks (Data-Bound)</h3>

<p>These tasks are the exact opposite. These tasks are only expensive because of the size. The processing time is almost insignificant, but the data is expensive to transport, e.g., image cropping, filtering an array, shallow copy, etc.</p>

<p>In my specific case, offloading the task to the background falls mostly into <strong>negative-sum efficiency</strong>. If we are talking about moving megabytes of data to perform a 50ms operation, there is no benefit to offloading it to the background.</p>

<p>Perhaps we can think of it like this:</p>

<pre><code class="language-markdown">Total Time = Serialization Cost
  + Transit
  + Background Processing Time
  + Deserialization Cost
</code></pre>

<p>Looking at this, if the <strong>“background processing time”</strong> is the most dominant task in your operation, then isolation is the clear winner. But if serialization, plus deserialization, plus transit exceeds that cost, then there’s no need to isolate things.</p>

<p>And if you can’t figure out if the task is CPU-heavy or data-heavy, it certainly doesn’t hurt to measure it, for example, using <a href="https://developer.mozilla.org/en-US/docs/Web/API/Performance/mark"><code>performance.mark()</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/PerformanceMeasure"><code>performance.measure()</code></a> around <code>postMessage</code> calls to profile the transfer cost.</p>

<div class="signature">
  <img src="https://www.smashingmagazine.com/images/logo/logo--red.png" alt="Smashing Editorial" width="35" height="46" loading="lazy" decoding="async" />
  <span>(gg, yk)</span>
</div>


              </article>
            </body>
          </html>
        ]]></content:encoded></item><item><author>Joe Attardi</author><title>Moving From Moment.js To The JS Temporal API</title><link>https://www.smashingmagazine.com/2026/03/moving-from-moment-to-temporal-api/</link><pubDate>Fri, 13 Mar 2026 13:00:00 +0000</pubDate><guid>https://www.smashingmagazine.com/2026/03/moving-from-moment-to-temporal-api/</guid><description>The way JavaScript handles time has evolved significantly, from the built-in &lt;code>Date&lt;/code> API to Moment.js and now Temporal. The new standard fills gaps in the original &lt;code>Date&lt;/code> API while addressing limitations found in Moment and other libraries. Joe Attardi shares practical “recipes” for migrating Moment-based code to the new Temporal API.</description><content:encoded><![CDATA[
          <html>
            <head>
              <meta charset="utf-8">
              <link rel="canonical" href="https://www.smashingmagazine.com/2026/03/moving-from-moment-to-temporal-api/" />
              <title>Moving From Moment.js To The JS Temporal API</title>
            </head>
            <body>
              <article>
                <header>
                  <h1>Moving From Moment.js To The JS Temporal API</h1>
                  
                    
                    <address>Joe Attardi</address>
                  
                  <time datetime="2026-03-13T13:00:00&#43;00:00" class="op-published">2026-03-13T13:00:00+00:00</time>
                  <time datetime="2026-03-13T13:00:00&#43;00:00" class="op-modified">2026-11-13T04:40:45+00:00</time>
                </header>
                
                

<p>Almost any kind of application written in JavaScript works with times or dates in some capacity. In the beginning, this was limited to the built-in <code>Date</code> API. This API includes basic functionality, but is quite limited in what it can do.</p>

<p>Third-party libraries like Moment.js, and later built-in APIs such as the <code>Intl</code> APIs and the new <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal">Temporal API</a>, add much greater flexibility to working with times and dates.</p>

<h2 id="the-rise-and-fall-of-moment-js">The Rise And Fall Of Moment.js</h2>

<p><a href="https://momentjs.com">Moment.js</a> is a JavaScript library with powerful utilities for working with times and dates. It includes missing features from the basic <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date">Date API</a>, such as time zone manipulation, and makes many common operations simpler. Moment also includes functions for formatting dates and times. It became a widely used library in many different applications.</p>

<p>However, Moment also had its share of issues. It’s a large library, and can add significantly to an application’s bundle size. Because the library doesn’t support tree shaking (a feature of modern bundlers that can remove unused parts of libraries), the entire Moment library is included even if you only use one or two of its functions.</p>

<p>Another issue with Moment is the fact that the objects it creates are <em>mutable</em>. Calling certain functions on a Moment object has side effects and mutates the value of that object. This can lead to unexpected behavior or bugs.</p>

<p>In 2020, the maintainers of Moment decided to put the library into maintenance mode. No new feature development is being done, and the maintainers recommend against using it for new projects.</p>

<p>There are other JavaScript date libraries, such as <code>date-fns</code>, but there’s a new player in town, an API built directly into JavaScript: <strong>Temporal</strong>. It’s a new standard that fills in the holes of the original <code>Date</code> API as well as solves some of the limitations found in Moment and other libraries.</p>

<div data-audience="non-subscriber" data-remove="true" class="feature-panel-container">

<aside class="feature-panel" style="">
<div class="feature-panel-left-col">

<div class="feature-panel-description"><p>Meet <strong><a data-instant href="https://www.smashingconf.com/online-workshops/">Smashing Workshops</a></strong> on <strong>front-end, design &amp; UX</strong>, with practical takeaways, live sessions, <strong>video recordings</strong> and a friendly Q&amp;A. With Brad Frost, Stéph Walter and <a href="https://smashingconf.com/online-workshops/workshops">so many others</a>.</p>
<a data-instant href="smashing-workshops" class="btn btn--green btn--large" style="">Jump to the workshops&nbsp;↬</a></div>
</div>
<div class="feature-panel-right-col"><a data-instant href="smashing-workshops" class="feature-panel-image-link">
<div class="feature-panel-image">
<img
    loading="lazy"
    decoding="async"
    class="feature-panel-image-img"
    src="/images/smashing-cat/cat-scubadiving-panel.svg"
    alt="Feature Panel"
    width="257"
    height="355"
/>

</div>
</a>
</div>
</aside>
</div>

<h2 id="what-is-temporal">What Is Temporal?</h2>

<p>Temporal is a new time and date API being added to the ECMAScript standard, which defines modern JavaScript. As of March 2026, it has reached Stage 4 of the TC39 process (the committee that oversees proposals and additions to the JavaScript language), and will be included in the next version of the ECMAScript specification. It has already been implemented in several browsers: <a href="https://developer.chrome.com/release-notes/144">Chrome</a> <a href="https://developer.chrome.com/release-notes/144">144+</a> and <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Releases/139#javascript">Firefox</a> <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Releases/139#javascript">139+</a>, with <a href="https://bugs.webkit.org/show_bug.cgi?id=223166">Safari expected to follow soon</a>. A <a href="https://github.com/js-temporal/temporal-polyfill">polyfill is also available</a> for unsupported browsers and Node.js.</p>

<p>The Temporal API creates objects that, generally, represent moments in time. These can be full-time and date stamps in a given time zone, or they can be a generic instance of “wall clock” time without any time zone or date information. Some of the main features of Temporal include:</p>

<ul>
<li><strong>Times with or without dates.</strong><br />
A Temporal object can represent a specific time on a specific date, or a time without any date information. A specific date, without a time, can also be represented.</li>
<li><strong>Time zone support.</strong><br />
Temporal objects are fully time zone aware and can be converted across different time zones. Moment supports time zones, too, but it requires the additional <code>moment-timezone</code> library.</li>
<li><strong>Immutability.</strong><br />
Once a Temporal object is created, it cannot be changed. Time arithmetic or time zone conversions do not modify the underlying object. Instead, they generate a new Temporal object.</li>
<li><strong>1-based indexing.</strong><br />
A common source of bugs with the Date API (as well as with Moment) is that months are zero-indexed. This means that January is month <code>0</code>, rather than month <code>1</code> as we all understand in real life. Temporal fixes this by using 1-based indexing &mdash; January is month <code>1</code>.</li>
<li><strong>It’s built into the browser.</strong><br />
Since Temporal is an API in the browser itself, it adds nothing to your application’s bundle size.</li>
</ul>

<p>It’s also important to note that the Date API isn’t going away. While Temporal supersedes this API, it is not being removed or deprecated. Many applications would break if browsers suddenly removed the Date API. However, also keep in mind that Moment is now considered a legacy project in maintenance mode.</p>

<p>In the rest of the article, we’ll look at some “recipes” for migrating Moment-based code to the new Temporal API. Let’s start refactoring!</p>

<h2 id="creating-date-and-time-objects">Creating Date And Time Objects</h2>

<p>Before we can manipulate dates and times, we have to create objects representing them. To create a Moment object representing the current date and time, use the <code>moment</code> function.</p>

<pre><code class="language-javascript">const now = moment();
console.log(now); 
// Moment&lt;2026-02-18T21:26:29-05:00&gt;
</code></pre>  

<p>This object can now be formatted or manipulated as needed.</p>

<div class="break-out">
<pre><code class="language-javascript">// convert to UTC
// warning: This mutates the Moment object and puts it in UTC mode!
console.log(now.utc()); 
// Moment&lt;2026-02-19T02:26:29Z&gt;

// print a formatted string - note that it's using the UTC time now
console.log(now.format('MM/DD/YYYY hh:mm:ss a')); 
// 02/19/2026 02:27:07 am
</code></pre>
</div>

<p>The key thing to remember about Moment is that a Moment object always includes information about the time <em>and</em> the date. If you only need to work with time information, this is usually fine, but it can cause unexpected behavior in situations like Daylight Saving Time or leap years, where the date can have an effect on time calculations.</p>

<p>Temporal is more flexible. You can create an object representing the current date and time by creating a <code>Temporal.Instant</code> object. This represents a point in time defined by the time since “the epoch” (midnight UTC on January 1, 1970). Temporal can reference this instant in time with nanosecond-level precision.</p>

<pre><code class="language-javascript">const now = Temporal.Now.instant();

// see raw nanoseconds since the epoch
console.log(now.epochNanoseconds);
// 1771466342612000000n

// format for UTC
console.log(now.toString());
// 2026-02-19T01:55:27.844Z

// format for a particular time zone
console.log(now.toString({ timeZone: 'America/New&#95;York' }));
// 2026-02-18T20:56:57.905-05:00
</code></pre>

<p><code>Temporal.Instant</code> objects can also be created for a specific time and date by using the <code>from</code> static method.</p>

<div class="break-out">
<pre><code class="language-javascript">const myInstant = Temporal.Instant.from('2026-02-18T21:10:00-05:00');

// Format the instant in the local time zone. Note that this only controls
// the formatting - it does not mutate the object like `moment.utc` does.
console.log(myInstant.toString({ timeZone: 'America/New&#95;York' }));
// 2026-02-18T21:10:00-05:00
</code></pre>
</div>

<p>You can also create other types of Temporal objects, including:</p>

<ul>
<li><strong><code>Temporal.PlainDate</code></strong>: A date with no time information.</li>
<li><strong><code>Temporal.PlainTime</code></strong>: A time with no date information.</li>
<li><strong><code>Temporal.ZonedDateTime</code></strong>: A date and time in a specific time zone.</li>
</ul>

<p>Each of these has a <code>from</code> method that can be called with an object specifying the date and/or time, or a date string to parse.</p>

<pre><code class="language-javascript">// Just a date
const today = Temporal.PlainDate.from({
  year: 2026,
  month: 2, // note we're using 2 for February
  day: 18
});
console.log(today.toString());
// 2026-02-18

// Just a time
const lunchTime = Temporal.PlainTime.from({
  hour: 12
});
console.log(lunchTime.toString());
// 12:00:00 

// A date and time in the US Eastern time zone
const dueAt = Temporal.ZonedDateTime.from({
  timeZone: 'America/New&#95;York',
  year: 2026,
  month: 3,
  day: 1,
  hour: 12,
  minute: 0,
  second: 0
});
console.log(dueAt.toString());
// 2026-03-01T12:00:00-05:00[America/New&#95;York]
</code></pre>

<div class="partners__lead-place"></div>

<h2 id="parsing">Parsing</h2>

<p>We’ve covered programmatic creation of date and time information. Now let’s look at parsing. Parsing is one area where Moment is more flexible than the built-in Temporal API.</p>

<p>You can parse a date string by passing it to the <code>moment</code> function. With a single argument, Moment expects an ISO date string, but you can use alternative formats if you provide a second argument specifying the date format being used.</p>

<div class="break-out">
<pre><code class="language-javascript">const isoDate = moment('2026-02-21T09:00:00');
const formattedDate = moment('2/21/26 9:00:00', 'M/D/YY h:mm:ss');

console.log(isoDate);
// Moment&lt;2026-02-21T09:00:00-05:00&gt;

console.log(formattedDate);
// Moment&lt;2026-02-21T09:00:00-05:00&gt;
</code></pre>
</div>

<p>In older versions, Moment would make a best guess to parse any arbitrarily formatted date string. This could lead to unpredictable results. For example, is <code>02-03-2026</code> February 2 or March 3? For this reason, newer versions of Moment display a prominent deprecation warning if it’s called without an ISO formatted date string (unless the second argument with the desired format is also given).</p>

<p>Temporal will only parse a specifically formatted date string. The string must be compliant with the ISO 8601 format or its extension, RFC 9557. If a non-compliant date string is passed to a <code>from</code> method, Temporal will throw a <code>RangeError</code>.</p>

<div class="break-out">
<pre><code class="language-javascript">// Using an RFC 9557 date string
const myDate = Temporal.Instant.from('2026-02-21T09:00:00-05:00[America/New&#95;York]');
console.log(myDate.toString({ timeZone: 'America/New&#95;York' }));
// 2026-02-21T09:00:00-05:00

// Using an unknown date string
const otherDate = Temporal.Instant.from('2/21/26 9:00:00');
// RangeError: Temporal error: Invalid character while parsing year value.
</code></pre>
</div>

<p>The exact requirements of the date string depend on which kind of Temporal object you’re creating. In the above example, <code>Temporal.Instant</code> requires a full ISO 8601 or RFC 9557 date string specifying the date and time with a time zone offset, but you can also create <code>PlainDate</code> or <code>PlainTime</code> objects using just a subset of the date format.</p>

<pre><code class="language-javascript">const myDate = Temporal.PlainDate.from('2026-02-21');
console.log(myDate.toString());
// 2026-02-21

const myTime = Temporal.PlainTime.from('09:00:00');
console.log(myTime.toString());
// 09:00:00
</code></pre>

<p>Note that these strings must still comply with the expected format, or an error will be thrown.</p>

<div class="break-out">
<pre><code class="language-javascript">// Using a non-compliant time strings. These will all throw a RangeError.
Temporal.PlainTime.from('9:00');
Temporal.PlainTime.from('9:00:00 AM');
</code></pre>
</div>

<blockquote><strong>Pro tip: Handling non-ISO strings</strong><br /><br />Because Temporal prioritizes reliability, it won’t try to guess the format of a string like <code>02-01-2026</code>. If your data source uses such strings, you will need to do some string manipulation to rearrange the values into an ISO string like <code>2026-02-01</code> before attempting to use it with Temporal.</blockquote>

<h2 id="formatting">Formatting</h2>

<p>Once you have a Moment or Temporal object, you’ll probably want to convert it to a formatted string at some point.</p>

<p>This is an instance where Moment is a bit more terse. You call the object’s <code>format</code> method with a string of tokens that describe the desired date format.</p>

<pre><code class="language-javascript">const date = moment();

console.log(date.format('MM/DD/YYYY'));
// 02/22/2026

console.log(date.format('MMMM Do YYYY, h:mm:ss a'));
// February 22nd 2026, 8:18:30 pm
</code></pre>

<p>On the other hand, Temporal requires you to be a bit more verbose. Temporal objects, such as <code>Instant</code>, have a <code>toLocaleString</code> method that accepts various formatting options specified as properties of an object.</p>

<div class="break-out">
<pre><code class="language-javascript">const date = Temporal.Now.instant();

// with no arguments, we'll get the default format for the current locale
console.log(date.toLocaleString());
// 2/22/2026, 8:23:36 PM (assuming a locale of en-US)

// pass formatting options to generate a custom format string
console.log(date.toLocaleString('en-US', {
  month: 'long',
  day: 'numeric',
  year: 'numeric',
  hour: '2-digit',
  minute: '2-digit'
}));
// February 22, 2026 at 8:23 PM

// only pass the fields you want in the format string
console.log(date.toLocaleString('en-US', {
  month: 'short',
  day: 'numeric'
}));
// Feb 22
</code></pre>
</div>

<p><strong>Temporal date formatting actually uses the <code>Intl.DateTimeFormat</code> API</strong> (which is already readily available in modern browsers) under the hood. That means you can create a reusable <code>DateTimeFormat</code> object with your custom formatting options, then pass Temporal objects to its <code>format</code> method. Because of this, it doesn’t support custom date formats like Moment does. If you need something like <code>'Q1 2026'</code> or other specialized formatting, you may need some custom date formatting code or reach for a third-party library.</p>

<pre><code class="language-javascript">const formatter = new Intl.DateTimeFormat('en-US', {
  month: '2-digit',
  day: '2-digit',
  year: 'numeric'
});

const date = Temporal.Now.instant();
console.log(formatter.format(date));
// 02/22/2026
</code></pre>

<p>Moment’s formatting tokens are simpler to write, but they aren’t locale-friendly. The format strings “hard code” things like month/day order. The advantage of using a configuration object, as Temporal does, is that it will automatically adapt to any given locale and use the correct format.</p>

<pre><code class="language-javascript">const date = Temporal.Now.instant();

const formatOptions = {
  month: 'numeric',
  day: 'numeric',
  year: 'numeric'
};


console.log(date.toLocaleString('en-US', formatOptions));
// 2/22/2026

console.log(date.toLocaleString('en-GB', formatOptions));
// 22/02/2026
</code></pre>

<h2 id="date-calculations">Date calculations</h2>

<p>In many applications, you’ll need to end up performing some calculations on a date. You may want to add or subtract units of time (days, hours, seconds, etc.). For example, if you have the current date, you may want to show the user the date 1 week from now.</p>

<p>Moment objects have methods such as <code>add</code> and <code>subtract</code> that perform these operations. These functions take a value and a unit, for example: <code>add(7, 'days')</code>. One very important difference between Moment and Temporal, however, is that when performing these date calculations, the underlying object is modified and its original value is lost.</p>

<pre><code class="language-javascript">const now = moment();

console.log(now);
// Moment&lt;2026-02-24T20:08:36-05:00&gt;

const nextWeek = now.add(7, 'days');
console.log(nextWeek);
// Moment&lt;2026-03-03T20:08:36-05:00&gt;

// Gotcha - the original object was mutated
console.log(now);
// Moment&lt;2026-03-03T20:08:36-05:00&gt;
</code></pre>

<p>To avoid losing the original date, you can call <code>clone</code> on the Moment object to create a copy.</p>

<pre><code class="language-javascript">const now = moment();
const nextWeek = now.clone().add(7, 'days');

console.log(now);
// Moment&lt;2026-02-24T20:12:55-05:00&gt;

console.log(nextWeek);
// Moment&lt;2026-03-03T20:12:55-05:00&gt;
</code></pre>

<p>On the other hand, Temporal objects are <em>immutable</em>. Once you’ve created an object like an <code>Instant</code>, <code>PlainDate</code>, and so on, the value of that object will never change. Temporal objects also have <code>add</code> and <code>subtract</code> methods.</p>

<p>Temporal is a little picky about which time units can be added to which object types. For example, you can’t add days to an <code>Instant</code>:</p>

<div class="break-out">
<pre><code class="language-javascript">const now = Temporal.Now.instant();
const nextWeek = now.add({ days: 7 });
// RangeError: Temporal error: Largest unit cannot be a date unit
</code></pre>
</div>

<p>This is because <code>Instant</code> objects represent a specific point in time in UTC and are calendar-agnostic. Because the length of a day can change based on time zone rules such as Daylight Saving Time, this calculation isn’t available on an <code>Instant</code>. You <em>can</em>, however, perform this operation on other types of objects, such as a <code>PlainDateTime</code>:</p>

<pre><code class="language-javascript">const now = Temporal.Now.plainDateTimeISO();
console.log(now.toLocaleString());
// 2/24/2026, 8:23:59 PM

const nextWeek = now.add({ days: 7 });

// Note that the original PlainDateTime remains unchanged
console.log(now.toLocaleString());
// 2/24/2026, 8:23:59 PM

console.log(nextWeek.toLocaleString());
// 3/3/2026, 8:23:59 PM
</code></pre>

<p>You can also calculate how much time is between two Moment or Temporal objects.</p>

<p>With Moment’s <code>diff</code> function, you need to provide a unit for granularity, otherwise it will return the difference in milliseconds.</p>

<pre><code class="language-javascript">const date1 = moment('2026-02-21T09:00:00');
const date2 = moment('2026-02-22T10:30:00');

console.log(date2.diff(date1));
// 91800000

console.log(date2.diff(date1, 'days'));
// 1
</code></pre>

<p>To do this with a Temporal object, you can pass another Temporal object to its <code>until</code> or <code>since</code> methods. This returns a <code>Temporal.Duration</code> object containing information about the time difference. The <code>Duration</code> object has properties for each component of the difference, and also can generate an <a href="https://en.wikipedia.org/wiki/ISO_8601#Durations">ISO 8601</a> duration string representing the time difference.</p>

<div class="break-out">
<pre><code class="language-javascript">const date1 = Temporal.PlainDateTime.from('2026-02-21T09:00:00');
const date2 = Temporal.PlainDateTime.from('2026-02-22T10:30:00');

// largestUnit specifies the largest unit of time to represent
// in the duration calculation
const diff = date2.since(date1, { largestUnit: 'day' });

console.log(diff.days);
// 1

console.log(diff.hours);
// 1

console.log(diff.minutes);
// 30

console.log(diff.toString());
// P1DT1H30M
// (ISO 8601 duration string: 1 day, 1 hour, 30 minutes)
</code></pre>
</div>

<h2 id="comparing-dates-and-times">Comparing Dates And Times</h2>

<p>Moment and Temporal both let you compare dates and times to determine which comes before the other, but take different approaches with the API.</p>

<p>Moment provides methods such as <code>isBefore</code>, <code>isAfter</code>, and <code>isSame</code> to compare two Moment objects.</p>

<pre><code class="language-javascript">const date1 = moment('2026-02-21T09:00:00');
const date2 = moment('2026-02-22T10:30:00');

console.log(date1.isBefore(date2));
// true
</code></pre>

<p>Temporal uses a static <code>compare</code> method to perform a comparison between two objects of the same type. It returns <code>-1</code> if the first date comes before the second, <code>0</code> if they are equal, or <code>1</code> if the first date comes after the second. The following example shows how to compare two <code>PlainDate</code> objects. Both arguments to <code>Temporal.PlainDate.compare</code> must be <code>PlainDate</code> objects.</p>

<div class="break-out">
<pre><code class="language-javascript">const date1 = Temporal.PlainDate.from({ year: 2026, month: 2, day: 24 });
const date2 = Temporal.PlainDate.from({ year: 2026, month: 3, day: 24 });

// date1 comes before date2, so -1
console.log(Temporal.PlainDate.compare(date1, date2));

// Error if we try to compare two objects of different types
console.log(Temporal.PlainDate.compare(date1, Temporal.Now.instant()));
// TypeError: Temporal error: Invalid PlainDate fields provided.
</code></pre>
</div>

<p>In particular, this makes it easy to sort an array of Temporal objects chronologically.</p>

<pre><code class="language-javascript">// An array of Temporal.PlainDate objects
const dates = [ ... ];

// use Temporal.PlainDate.compare as the comparator function
dates.sort(Temporal.PlainDate.compare);
</code></pre>

<h2 id="time-zone-conversions">Time Zone Conversions</h2>

<p>The core Moment library doesn’t support time zone conversions. If you need this functionality, you also need to install the <code>moment-timezone</code> package. This package is not tree-shakable, and therefore can add significantly to your bundle size. Once you’ve installed <code>moment-timezone</code>, you can convert Moment objects to different time zones with the <code>tz</code> method. As with other Moment operations, this mutates the underlying object.</p>

<pre><code class="language-javascript">// Assuming US Eastern time
const now = moment();
console.log(now);
// Moment&lt;2026-02-28T20:08:20-05:00&gt;

// Convert to Pacific time.
// The original Eastern time is lost.
now.tz('America/Los&#95;Angeles');
console.log(now);
// Moment&lt;2026-02-28T17:08:20-08:00&gt;
</code></pre>

<p>Time zone functionality is built into the Temporal API when using a <code>Temporal.ZonedDateTime</code> object. These objects include a <code>withTimeZone</code> method that returns a new <code>ZonedDateTime</code> representing the same moment in time, but in the specified time zone.</p>

<pre><code class="language-javascript">// Again, assuming US Eastern time
const now = Temporal.Now.zonedDateTimeISO();
console.log(now.toLocaleString());
// 2/28/2026, 8:12:02 PM EST

// Convert to Pacific time
const nowPacific = now.withTimeZone('America/Los&#95;Angeles');
console.log(nowPacific.toLocaleString());
// 2/28/2026, 5:12:02 PM PST

// Original object remains unchanged
console.log(now.toLocaleString());
// 2/28/2026, 8:12:02 PM EST
</code></pre>

<p><strong>Note:</strong> <em>The formatted values returned by <code>toLocaleString</code> are, as the name implies, locale-dependent. The sample code was developed in the <code>en-US</code> locale, so the format is like this: <code>2/28/2026, 5:12:02 PM PST</code>. In another locale, this may be different. For example, in the <code>en-GB</code> locale, you would get something like <code>28/2/2026, 17:12:02 GMT-8</code>.</em></p>

<div class="partners__lead-place"></div>

<h2 id="a-real-world-refactoring">A Real-world Refactoring</h2>

<p>Suppose we’re building an app for scheduling events across time zones. Part of this app is a function, <code>getEventTimes</code>, which takes an ISO 8601 string representing the time and date of the event, a local time zone, and a target time zone. The function creates formatted time and date strings for the event in both time zones.</p>

<p>If the function is given an input string that’s not a valid time/date string, it will throw an error.</p>

<p>Here’s the original implementation, using Moment (also requiring use of the <code>moment-timezone</code> package).</p>

<div class="break-out">
<pre><code class="language-javascript">import moment from 'moment-timezone';

function getEventTimes(inputString, userTimeZone, targetTimeZone) {
  const timeFormat = 'MMM D, YYYY, h:mm:ss a z';

  // 1. Create the initial moment in the user's time zone
  const eventTime = moment.tz(
    inputString,
    moment.ISO&#95;8601, // Expect an ISO 8601 string
    true, // Strict parsing
    userTimeZone
  );
  
  // Throw an error if the inputString did not represent a valid date
  if (!eventTime.isValid()) {
    throw new Error('Invalid date/time input');
  }

  // 2. Calculate the target time
  // CRITICAL: We must clone, or 'eventTime' changes forever!
  const targetTime = eventTime.clone().tz(targetTimeZone);

  return {
    local: eventTime.format(timeFormat),
    target: targetTime.format(timeFormat),
  };
}

const schedule = getEventTimes(
  '2026-03-05T15:00-05:00',
  'America/New&#95;York',
  'Europe/London',
);

console.log(schedule.local);
// Mar 5, 2026, 3:00:00 pm EST

console.log(schedule.target); 
// Mar 5, 2026, 8:00:00 pm GMT
</code></pre>
</div>

<p>In this example, we’re using an expected date format of ISO 8601, which is helpfully built into Moment. We’re also using strict parsing, which means Moment won’t try to guess with a date string that doesn’t match the format. If a non-ISO date string is passed, it will result in an invalid date object, and we throw an error.</p>

<p>The Temporal implementation looks similar, but has a few key differences.</p>

<div class="break-out">
<pre><code class="language-javascript">function getEventTimes(inputString, userTimeZone, targetTimeZone) {
  // 1. Parse the input directly into an Instant, then create
  // a ZonedDateTime in the user's zone.
  const instant = Temporal.Instant.from(inputString);
  const eventTime = instant.toZonedDateTimeISO(userTimeZone);

  // 2. Convert to the target zone
  // This automatically returns a NEW object; 'eventTime' is safe.
  const targetTime = eventTime.withTimeZone(targetTimeZone);

  // 3. Format using Intl (built-in)
  const options = {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
    second: '2-digit',
    timeZoneName: 'short'
  };

  return {
    local: eventTime.toLocaleString(navigator.language, options),
    target: targetTime.toLocaleString(navigator.language, options)
  };
}

const schedule = getEventTimes(
  '2026-03-05T15:00-05:00',
  'America/New&#95;York',
  'Europe/London',
);

console.log(schedule.local);
// Mar 5, 2026, 3:00:00 PM EST

console.log(schedule.target);
// Mar 5, 2026, 8:00:00 PM GMT
</code></pre>
</div>

<p>With Moment, we have to explicitly specify a format string for the resulting date strings. Regardless of the user’s location or locale, the event times will always be formatted as <code>Mar 5, 2026, 3:00:00 pm EST</code>.</p>

<p>Also, we don’t have to explicitly throw an exception. If an invalid string is passed to <code>Temporal.Instant.from</code>, Temporal will throw the exception for us. One thing to note is that even with strict parsing, the Moment version is still more lenient. Temporal requires the time zone offset at the end of the string.</p>

<p>You should also note that since we’re using <code>navigator.language</code>, this code will only run in a browser environment, as <code>navigator</code> is not defined in a Node.js environment.</p>

<p>The Temporal implementation uses the browser’s current locale (<code>navigator.language</code>), so the user will automatically get event times formatted in their local time format. In the <code>en-US</code> locale, this is <code>Mar 5, 2026, 3:00:00 pm EST</code>. However, if the user is in London, for example, the event times will be formatted as <code>5 Mar 2026, 15:00:00 GMT-5</code>.</p>

<h2 id="summary">Summary</h2>

<table class="tablesaw break-out">
    <thead>
        <tr>
            <th>Action</th>
            <th>Moment.js</th>
      <th>Temporal</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Current time</td>
            <td><code>moment()</code></td>
      <td><code>Temporal.Now.zonedDateTimeISO()</code></td>
        </tr>
        <tr>
            <td>Parsing ISO</td>
            <td><code>moment(str)</code></td>
      <td><code>Temporal.Instant.from(str)</code></td>
        </tr>
        <tr>
            <td>Add time</td>
            <td><code>.add(7, 'days')</code> (mutates)</td>
      <td><code>.add({ days: 7 })</code> (new object)</td>
        </tr>
    <tr>
            <td>Difference</td>
            <td><code>.diff(other, 'hours')</code></td>
      <td><code>.since(other).hours</code></td>
        </tr>
    <tr>
            <td>Time zone</td>
            <td><code>.tz('Zone/Name')</code></td>
      <td><code>.withTimeZone('Zone/Name')</code></td>
        </tr>
    </tbody>
</table>

<p>At first glance, the difference may be slightly different (and in the case of Temporal, sometimes more verbose and more strict) syntax, but there are several key advantages to using Temporal over Moment.js:</p>

<ul>
<li>Being more explicit means <strong>fewer surprises and unintended bugs</strong>. Moment may appear to be more lenient, but it involves “guesswork,” which can sometimes result in incorrect dates. If you give Temporal something invalid, it throws an error. If the code runs, you know you’ve got a valid date.</li>
<li>Moment can add significant size to the application’s bundle, particularly if you’re using the <code>moment-timezone</code> package. Temporal adds nothing (once it’s shipped in your target browsers).</li>
<li><strong>Immutability</strong> gives you the confidence that you’ll never lose or overwrite data when performing date conversions and operations.</li>
<li><strong>Different representations of time</strong> (<code>Instant</code>, <code>PlainDateTime</code>, <code>ZonedDateTime</code>) depending on your requirements, where Moment is always a wrapper around a UTC timestamp.</li>
<li>Temporal uses the <strong><code>Intl</code> APIs for date formatting</strong>, which means you can have locale-aware formatting without having to explicitly specify tokens.</li>
</ul>

<h2 id="notes-on-the-polyfill">Notes On The Polyfill</h2>

<p>As mentioned earlier, there is a Temporal polyfill available, distributed as an npm package named <code>@js-temporal/polyfill</code>. If you want to use Temporal today, you’ll need this polyfill to support browsers like Safari that haven’t shipped the API yet. The bad news with this is that it will add to your bundle size. The good news is that it still adds significantly less than <code>moment</code> or <code>moment-timezone</code>. Here is a comparison of the bundle sizes as reported by Bundlephobia.com, a website that presents information on npm package sizes (click on each package name to see the Bundlephobia analysis):</p>

<table class="tablesaw break-out">
    <thead>
        <tr>
            <th>Package</th>
            <th>Minified</th>
      <th>Minified & gzipped</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><a href="https://bundlephobia.com/package/@js-temporal/polyfill"><code>@js-temporal/polyfill</code></a></td>
            <td>154.1 kB</td>
      <td>44.1 kB</td>
        </tr>
        <tr>
            <td><a href="https://bundlephobia.com/package/moment"><code>moment</code></a></td>
            <td>294.4 kB</td>
      <td>75.4 kB</td>
        </tr>
        <tr>
            <td><a href="https://bundlephobia.com/package/moment-timezone"><code>moment-timezone</code></a></td>
            <td>1 MB</td>
      <td>114.2 kB</td>
        </tr>
    </tbody>
</table>

<p>The polyfill also has historically had some performance issues around memory usage, and at the time of writing, it’s considered to be in an alpha state. Because of this, you may not want to use it in production until it reaches a more mature state.</p>

<p>The other good news is that hopefully the polyfill won’t be needed much longer (unless you need to support older browsers, of course). At the time of writing, Temporal has shipped in Chrome, Edge, and Firefox. It’s not quite ready in Safari yet, though it appears to be available with a runtime flag on the latest Technology Preview.</p>

<div class="signature">
  <img src="https://www.smashingmagazine.com/images/logo/logo--red.png" alt="Smashing Editorial" width="35" height="46" loading="lazy" decoding="async" />
  <span>(gg, yk)</span>
</div>


              </article>
            </body>
          </html>
        ]]></content:encoded></item><item><author>Sunil Sandhu</author><title>Building Dynamic Forms In React And Next.js</title><link>https://www.smashingmagazine.com/2026/03/building-dynamic-forms-react-next-js/</link><pubDate>Tue, 10 Mar 2026 13:00:00 +0000</pubDate><guid>https://www.smashingmagazine.com/2026/03/building-dynamic-forms-react-next-js/</guid><description>Some forms stay UI, while others quietly become rule engines. Here’s why these two different approaches exist and how to choose between them.</description><content:encoded><![CDATA[
          <html>
            <head>
              <meta charset="utf-8">
              <link rel="canonical" href="https://www.smashingmagazine.com/2026/03/building-dynamic-forms-react-next-js/" />
              <title>Building Dynamic Forms In React And Next.js</title>
            </head>
            <body>
              <article>
                <header>
                  <h1>Building Dynamic Forms In React And Next.js</h1>
                  
                    
                    <address>Sunil Sandhu</address>
                  
                  <time datetime="2026-03-10T13:00:00&#43;00:00" class="op-published">2026-03-10T13:00:00+00:00</time>
                  <time datetime="2026-03-10T13:00:00&#43;00:00" class="op-modified">2026-11-13T04:40:45+00:00</time>
                </header>
                <p>This article is sponsored by <b>SurveyJS</b></p>
                

<p>There’s a mental model most React developers share without ever discussing it out loud. That forms are <em>always</em> supposed to be components. This means a stack like:</p>

<ul>
<li><strong>React Hook Form</strong> for local state (minimal re-renders, ergonomic field registration, imperative interaction).</li>
<li><strong>Zod</strong> for validation (input correctness, boundary validation, type-safe parsing).</li>
<li><strong>React Query</strong> for backend: submission, retries, caching, server sync, and so on.</li>
</ul>

<p>And for the vast majority of forms &mdash; your login screens, your settings pages, your CRUD modals &mdash; this works really well. Each piece does its job, they compose cleanly, and you can move on to the parts of your application that actually differentiate your product.</p>

<p>But every once in a while, a form starts accumulating things like visibility rules that depend on earlier answers, or derived values that cascade through three fields. Maybe even entire pages that should be skipped or shown based on a running total.</p>

<p>You handle the first conditional with a <code>useWatch</code> and an inline branch, which is fine. Then another. <a href="https://zod.dev/api#superrefine">Then you’re reaching for <code>superRefine</code></a> to encode cross-field rules that your Zod schema can’t express in the normal way. Then, step navigation starts leaking business logic. At some point, you look at what you’ve built and realize that the form isn’t really UI anymore. It’s more of a decision process, and the component tree is just where you happened to store it.</p>

<p>This is where I think the mental model for forms in React breaks down, and it’s really nobody’s fault. The RHF + Zod stack is excellent at what it was designed for. <strong>The issue is that we tend to keep using it past the point where its abstractions match the problem</strong> because the alternative requires a different way of thinking about forms entirely.</p>

<p>This article is about that alternative. To show this, we’ll build the exact same multi-step form twice:</p>

<ol>
<li>With React Hook Form + Zod wired to React Query for submission,</li>
<li>With SurveyJS, which treats a form as data &mdash; a simple JSON schema &mdash; rather than a component tree.</li>
</ol>

<p>Same requirements, same conditional logic, same API call at the end. Then we’ll map exactly what moved and what stayed, and lay out a practical way to decide which model you should use, and when.</p>

<p><strong>The form we’re building:</strong></p>














<figure class="
  
    break-out article__image
  
  
  ">
  
    <a href="https://files.smashing.media/articles/building-dynamic-forms-react-next-js/1-dynamic-form.png">
    
    <img
      loading="lazy"
      decoding="async"
      fetchpriority="low"
			width="800"
			height="798"
			
			srcset="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/building-dynamic-forms-react-next-js/1-dynamic-form.png 400w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_800/https://files.smashing.media/articles/building-dynamic-forms-react-next-js/1-dynamic-form.png 800w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1200/https://files.smashing.media/articles/building-dynamic-forms-react-next-js/1-dynamic-form.png 1200w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1600/https://files.smashing.media/articles/building-dynamic-forms-react-next-js/1-dynamic-form.png 1600w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_2000/https://files.smashing.media/articles/building-dynamic-forms-react-next-js/1-dynamic-form.png 2000w"
			src="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/building-dynamic-forms-react-next-js/1-dynamic-form.png"
			
			sizes="100vw"
			alt="Multi-step dynamic form"
		/>
    
    </a>
  

  
    <figcaption class="op-vertical-bottom">
      (<a href='https://files.smashing.media/articles/building-dynamic-forms-react-next-js/1-dynamic-form.png'>Large preview</a>)
    </figcaption>
  
</figure>

<p>This form will use a 4-step flow:</p>

<p><strong>Step 1: Details</strong></p>

<ul>
<li>First name (required),</li>
<li>Email (required, valid format).</li>
</ul>

<p><strong>Step 2: Order</strong></p>

<ul>
<li>Unit price,</li>
<li>Quantity,</li>
<li>Tax rate,</li>
<li>Derived:

<ul>
<li>Subtotal,</li>
<li>Tax,</li>
<li>Total.</li>
</ul></li>
</ul>

<p><strong>Step 3: Account &amp; Feedback</strong></p>

<ul>
<li>Do you have an account? (Yes/No)

<ul>
<li>If Yes → username + password, both required.</li>
<li>If No → email already collected in step 1.</li>
</ul></li>
<li>Satisfaction rating (1–5)

<ul>
<li>If ≥ 4 → ask “What did you like?”</li>
<li>If ≤ 2 → ask “What can we improve?”</li>
</ul></li>
</ul>

<p><strong>Step 4: Review</strong></p>

<ul>
<li>Only appears if <code>total &gt;= 100</code></li>
<li>Final submission.</li>
</ul>

<p>This is not extreme. But it’s enough to expose architectural differences.</p>

<h2 id="part-1-component-driven-react-hook-form-zod">Part 1: Component-Driven (React Hook Form + Zod)</h2>

<h3 id="installation">Installation</h3>

<pre><code class="language-bash">npm install react-hook-form zod @hookform/resolvers @tanstack/react-query
</code></pre>

<h3 id="zod-schema">Zod Schema</h3>

<p>Let’s start with the Zod schema, because that’s usually where the shape of the form gets established. For the first two steps &mdash; personal details and order inputs &mdash; everything is straightforward: required strings, numbers with minimums, and an enum. The interesting part starts when you try to express the conditional rules.</p>

<div class="break-out">
<pre><code class="language-typescript">import { z } from "zod";

export const formSchema = z.object({  
  firstName: z.string().min(1, "Required"),  
  email: z.string().email("Invalid email"),  
  price: z.number().min(0),  
  quantity: z.number().min(1),  
  taxRate: z.number(),  
  hasAccount: z.enum(["Yes", "No"]),  
  username: z.string().optional(),  
  password: z.string().optional(),  
  satisfaction: z.number().min(1).max(5),  
  positiveFeedback: z.string().optional(),  
  improvementFeedback: z.string().optional(),  
}).superRefine((data, ctx) =&gt; {  
  if (data.hasAccount === "Yes") {  
    if (!data.username) {  
      ctx.addIssue({ code: "custom", path: ["username"], message: "Required" });  
    }  
    if (!data.password || data.password.length &lt; 6) {  
      ctx.addIssue({ code: "custom", path: ["password"], message: "Min 6 characters" });  
    }  
  }

  if (data.satisfaction &gt;= 4 && !data.positiveFeedback) {  
    ctx.addIssue({ code: "custom", path: ["positiveFeedback"], message: "Please share what you liked" });  
  }

  if (data.satisfaction &lt;= 2 && !data.improvementFeedback) {  
    ctx.addIssue({ code: "custom", path: ["improvementFeedback"], message: "Please tell us what to improve" });  
  }  
});

export type FormData = z.infer&lt;typeof formSchema&gt;;
</code></pre>
</div>

<p>Notice that <code>username</code> and <code>password</code> are typed as <code>optional()</code> even though they’re conditionally required because Zod’s type-level schema describes the <em>shape</em> of the object, not the rules governing when fields matter.</p>

<p>The conditional requirement has to live inside <code>superRefine</code>, which runs after the shape is validated and has access to the full object. That separation is not a flaw; it’s just what the tool is designed for: <code>superRefine</code> is where cross-field logic goes when it can’t be expressed in the schema structure itself.</p>

<p>What’s also notable here is what this schema <em>doesn’t</em> express. It has no concept of pages, no concept of which fields are visible at which point, and no concept of navigation. All of that will live somewhere else.</p>

<h3 id="form-component">Form Component</h3>

<div class="break-out">
<pre><code class="language-typescript">import { useForm, useWatch } from "react-hook-form";  
import { zodResolver } from "@hookform/resolvers/zod";  
import { useMutation } from "@tanstack/react-query";  
import { useState, useMemo } from "react";  
import { formSchema, type FormData } from "./schema";

const STEPS = ["details", "order", "account", "review"];

type OrderPayload = FormData & { subtotal: number; tax: number; total: number };

export function RHFMultiStepForm() {  
  const [step, setStep] = useState(0);

  const mutation = useMutation({
    mutationFn: async (payload: OrderPayload) =&gt; {
      const res = await fetch("/api/orders", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      if (!res.ok) throw new Error("Failed to submit");
      return res.json();
    },
  });

  const {  
    register,  
    control,  
    handleSubmit,  
    formState: { errors },  
  } = useForm&lt;FormData&gt;({  
    resolver: zodResolver(formSchema),  
    defaultValues: {  
      price: 0,  
      quantity: 1,  
      taxRate: 0.1,  
      satisfaction: 3,  
      hasAccount: "No",  
    },  
  });  

  const price = useWatch({ control, name: "price" });  
  const quantity = useWatch({ control, name: "quantity" });  
  const taxRate = useWatch({ control, name: "taxRate" });  
  const hasAccount = useWatch({ control, name: "hasAccount" });  
  const satisfaction = useWatch({ control, name: "satisfaction" });  

  const subtotal = useMemo(() =&gt; (price ?? 0) &#42; (quantity ?? 1), [price, quantity]);  
  const tax = useMemo(() =&gt; subtotal &#42; (taxRate ?? 0), [subtotal, taxRate]);  
  const total = useMemo(() =&gt; subtotal + tax, [subtotal, tax]);  

  const onSubmit = (data: FormData) =&gt; mutation.mutate({ ...data, subtotal, tax, total });  

  const showSubmit = (step === 2 && total &lt; 100) || (step === 3 && total &gt;= 100)

  return (  
    &lt;form onSubmit={handleSubmit(onSubmit)}&gt;  
      {step === 0 && (  
        &lt;&gt;  
          &lt;input {...register("firstName")} placeholder="First Name" /&gt;  
          &lt;input {...register("email")} placeholder="Email" /&gt;  
        &lt;/&gt;  
      )}

      {step === 1 && (  
        &lt;&gt;  
          &lt;input type="number" {...register("price", { valueAsNumber: true })} /&gt;  
          &lt;input type="number" {...register("quantity", { valueAsNumber: true })} /&gt;  
          &lt;select {...register("taxRate", { valueAsNumber: true })}&gt;  
            &lt;option value="0.05"&gt;5%&lt;/option&gt;  
            &lt;option value="0.1"&gt;10%&lt;/option&gt;  
            &lt;option value="0.15"&gt;15%&lt;/option&gt;  
          &lt;/select&gt;

          &lt;div&gt;Subtotal: {subtotal}&lt;/div&gt;  
          &lt;div&gt;Tax: {tax}&lt;/div&gt;  
          &lt;div&gt;Total: {total}&lt;/div&gt;  
        &lt;/&gt;  
      )}

      {step === 2 && (  
        &lt;&gt;  
          &lt;select {...register("hasAccount")}&gt;  
            &lt;option value="Yes"&gt;Yes&lt;/option&gt;  
            &lt;option value="No"&gt;No&lt;/option&gt;  
          &lt;/select&gt;

          {hasAccount === "Yes" && (  
            &lt;&gt;  
              &lt;input {...register("username")} placeholder="Username" /&gt;  
              &lt;input {...register("password")} placeholder="Password" /&gt;  
            &lt;/&gt;  
          )}

          &lt;input type="number" {...register("satisfaction", { valueAsNumber: true })} /&gt;

          {satisfaction &gt;= 4 && (  
            &lt;textarea {...register("positiveFeedback")} /&gt;  
          )}

          {satisfaction &lt;= 2 && (  
            &lt;textarea {...register("improvementFeedback")} /&gt;  
          )}  
        &lt;/&gt;  
      )}

      {step === 3 && total &gt;= 100 && &lt;div&gt;Review and submit&lt;/div&gt;}

      &lt;div&gt;  
        {step &gt; 0 && &lt;button type="button" onClick={() =&gt; setStep(step - 1)}&gt;Back&lt;/button&gt;}  
        {showSubmit ? (  
          &lt;button type="submit" disabled={mutation.isPending}&gt;  
            {mutation.isPending ? "Submitting…" : "Submit"}  
          &lt;/button&gt;  
        ) : step &lt; STEPS.length - 1 ? (  
          &lt;button type="button" onClick={() =&gt; setStep(step + 1)}&gt;Next&lt;/button&gt;  
        ) : null}  
      &lt;/div&gt;  
      {mutation.isError && &lt;div&gt;Error: {mutation.error.message}&lt;/div&gt;}  
    &lt;/form&gt;  
  );  
}
</code></pre>
</div>

<figure class="break-out">
	<p data-height="480"
	data-theme-id="light"
	data-slug-hash="gbwwmNO"
	data-user="smashingmag"
	data-default-tab="result"
	class="codepen">See the Pen [SurveyJS-03-RHF [forked]](https://codepen.io/smashingmag/pen/gbwwmNO) by <a href="https://codepen.io/sixthextinction">sixthextinction</a>.</p>
	<figcaption>See the Pen <a href="https://codepen.io/smashingmag/pen/gbwwmNO">SurveyJS-03-RHF [forked]</a> by <a href="https://codepen.io/sixthextinction">sixthextinction</a>.</figcaption>
</figure>

<p>There’s quite a lot happening here, and it’s worth slowing down to notice where things ended up.</p>

<ul>
<li>The derived values &mdash; <code>subtotal</code>, <code>tax</code>, <code>total</code> &mdash; are computed in the component via <code>useWatch</code> and <code>useMemo</code> because they depend on live field values and there’s no other natural place for them.</li>
<li>The visibility rules for <code>username</code>, <code>password</code>, <code>positiveFeedback</code>, and <code>improvementFeedback</code> live in JSX as inline conditionals.</li>
<li>The step-skipping logic &mdash; the review page only appearing when <code>total &gt;= 100</code> &mdash; is embedded into the <code>showSubmit</code> variable and the render condition on step 3.</li>
<li>Navigation itself is just a <code>useState</code> counter that we’re manually incrementing.</li>
<li>React Query handles retries, caching, and invalidation. The form just calls <code>mutation.mutate</code> with validated data.</li>
</ul>

<p>None of this is <em>wrong,</em> per se. This is still idiomatic React, and the component is quite performant thanks to how RHF isolates re-renders.</p>

<p>But if you were to hand this to someone who hadn’t written it and ask them to explain <em>under what conditions the review page appears</em>, they’d have to trace through <code>showSubmit</code>, the step 3 render condition, and the nav button logic &mdash; three separate places &mdash; to reconstruct a rule that could have been stated in one line.</p>

<p><strong>The form works, yes, but the behavior isn’t really inspectable as a system.</strong> It has to be executed mentally.</p>

<p>More importantly, changing it requires engineering involvement. Even a small tweak, like adjusting when the review step shows up, means editing the component, updating validation, opening a pull request, waiting for review, and deploying again.</p>

<h2 id="part-2-schema-driven-surveyjs">Part 2: Schema-Driven (SurveyJS)</h2>

<p>Now let’s build the same flow using a schema.</p>

<h3 id="installation-1">Installation</h3>

<pre><code class="language-bash">npm install survey-core survey-react-ui @tanstack/react-query
</code></pre>

<ul>
<li><code>survey-core</code><br />
The MIT-licensed platform-independent runtime engine that powers SurveyJS’s form rendering &mdash; the part we care about here. It takes a JSON schema, builds an internal model from it, and handles everything that would otherwise live in your React component: evaluating visibility expressions, computing derived values, managing page state, tracking validation, and deciding what “complete” means given which pages were actually shown.</li>
<li><code>survey-react-ui</code><br />
The UI / rendering layer that connects that model to React. It’s essentially a <code>&lt;Survey model={model} /&gt;</code> component that re-renders whenever the engine’s state changes. SurveyJS UI libraries are also available for <a href="https://www.npmjs.com/package/survey-angular">Angular</a>, <a href="https://www.npmjs.com/package/survey-vue3-ui">Vue3</a>, and many other frameworks.</li>
</ul>

<p>Together, they give you a fully functional, multi-page form runtime without writing a single line of control flow.</p>

<p>The schema format itself is, as said before, just a JSON &mdash; no DSL or anything proprietary. You can inline it, import it from a file, fetch it from an API, or store it in a database column and hydrate it at runtime.</p>

<h3 id="the-same-form-as-data">The Same Form, As Data</h3>

<p>Here’s the same form, this time expressed as a JSON object. The schema defines everything: structure, validation, visibility rules, derived calculations, page navigation &mdash; and hands it to a <code>Model</code> that evaluates it at runtime. Here’s what that looks like in full:</p>

<div class="break-out">
<pre><code class="language-javascript">export const surveySchema = {  
  title: "Order Flow",  
  showProgressBar: "top",  
  pages: [  
    {  
      name: "details",  
      elements: [  
        { type: "text", name: "firstName", isRequired: true },  
        { type: "text", name: "email", inputType: "email", isRequired: true, validators: [{ type: "email", text: "Invalid email" }] }  
      ]  
    },  
    {  
      name: "order",  
      elements: [  
        { type: "text", name: "price", inputType: "number", defaultValue: 0 },  
        { type: "text", name: "quantity", inputType: "number", defaultValue: 1 },  
        {  
          type: "dropdown",  
          name: "taxRate",  
          defaultValue: 0.1,  
          choices: [  
            { value: 0.05, text: "5%" },  
            { value: 0.1, text: "10%" },  
            { value: 0.15, text: "15%" }  
          ]  
        },  
        {  
          type: "expression",  
          name: "subtotal",  
          expression: "{price} * {quantity}"  
        },  
        {  
          type: "expression",  
          name: "tax",  
          expression: "{subtotal} * {taxRate}"  
        },  
        {  
          type: "expression",  
          name: "total",  
          expression: "{subtotal} + {tax}"  
        }  
      ]  
    },  
    {  
      name: "account",  
      elements: [  
        {  
          type: "radiogroup",  
          name: "hasAccount",  
          choices: ["Yes", "No"]  
        },  
        {  
          type: "text",  
          name: "username",  
          visibleIf: "{hasAccount} = 'Yes'",  
          isRequired: true  
        },  
        {  
          type: "text",  
          name: "password",  
          inputType: "password",  
          visibleIf: "{hasAccount} = 'Yes'",  
          isRequired: true,  
          validators: [{ type: "text", minLength: 6, text: "Min 6 characters" }]  
        },  
        {  
          type: "rating",  
          name: "satisfaction",  
          rateMin: 1,  
          rateMax: 5  
        },  
        {  
          type: "comment",  
          name: "positiveFeedback",  
          visibleIf: "{satisfaction} &gt;= 4"  
        },  
        {  
          type: "comment",  
          name: "improvementFeedback",  
          visibleIf: "{satisfaction} &lt;= 2"  
        }  
      ]  
    },  
    {  
      name: "review",  
      visibleIf: "{total} &gt;= 100",  
      elements: []  
    }  
  ]  
};
</code></pre>
</div>

<p>Compare this to the RHF version for a moment.</p>

<ul>
<li>The <code>superRefine</code> block that conditionally required <code>username</code> and <code>password</code> is gone. <code>visibleIf: &quot;{hasAccount} = 'Yes'&quot;</code> combined with <code>isRequired: true</code> handles both concerns together, on the field itself, where you&rsquo;d expect to find them.</li>
<li>The <code>useWatch</code> + <code>useMemo</code> chain that computed <code>subtotal</code>, <code>tax</code>, and <code>total</code> is replaced by three <code>expression</code> fields that reference each other by name.</li>
<li>The review page condition, which in the RHF version was reconstructable only by tracing through <code>showSubmit</code>, the step 3 render branch.</li>
<li>And finally, the nav button logic is a single <code>visibleIf</code> property on the page object.</li>
</ul>

<p>The same logic is there. It’s just that the schema gives it a place to live where it’s visible in isolation, rather than spread across the component.</p>

<p>Also, note that the schema uses <code>type: 'expression'</code> for subtotal, tax, and total. <a href="https://surveyjs.io/form-library/documentation/api-reference/expression-model">Expression</a> is read-only and used mainly to display calculated values. SurveyJS also supports <code>type: 'html'</code> for static content, but for calculated values, <code>expression</code> is the right choice.</p>

<p>Now for the React side.</p>

<h3 id="rendering-and-submission">Rendering And Submission</h3>

<p>Very simple. Wire <code>onComplete</code> to your API the same way &mdash; via <code>useMutation</code> or plain <code>fetch</code>:</p>

<div class="break-out">
<pre><code class="language-javascript">import { useState, useEffect, useRef } from "react";  
import { useMutation } from "@tanstack/react-query";  
import { Model } from "survey-core";  
import { Survey } from "survey-react-ui";  
import "survey-core/survey-core.css";

export function SurveyForm() {  
  const [model] = useState(() =&gt; new Model(surveySchema));

  const mutation = useMutation({
    mutationFn: async (data) =&gt; {
      const res = await fetch("/api/orders", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });
      if (!res.ok) throw new Error("Failed to submit");
      return res.json();
    },
  });

  const mutationRef = useRef(mutation);
  mutationRef.current = mutation;
  useEffect(() =&gt; {  
    const handler = (sender) =&gt; mutationRef.current.mutate(sender.data);  
    model.onComplete.add(handler);  
    return () =&gt; model.onComplete.remove(handler);  
  }, [model]); // ref avoids re-registering handler every render (mutation object identity changes)

  return (
    &lt;&gt;
      &lt;Survey model={model} /&gt;  
      {mutation.isError && &lt;div&gt;Error: {mutation.error.message}&lt;/div&gt;}
    &lt;/&gt;
  );
}
</code></pre>
</div>

<figure class="break-out">
	<p data-height="480"
	data-theme-id="light"
	data-slug-hash="emddWNV"
	data-user="smashingmag"
	data-default-tab="result"
	class="codepen">See the Pen [SurveyJS-03-SurveyJS [forked]](https://codepen.io/smashingmag/pen/emddWNV) by <a href="https://codepen.io/sixthextinction">sixthextinction</a>.</p>
	<figcaption>See the Pen <a href="https://codepen.io/smashingmag/pen/emddWNV">SurveyJS-03-SurveyJS [forked]</a> by <a href="https://codepen.io/sixthextinction">sixthextinction</a>.</figcaption>
</figure>

<ul>
<li><code>onComplete</code> fires when the user reaches the end of the last <em>visible</em> page. So if <code>total</code> never crosses 100 and the review page is skipped, it still fires correctly because SurveyJS evaluates visibility before deciding what “last page” means.</li>
<li>Then, <code>sender.data</code> contains all answers along with the calculated values (<code>subtotal</code>, <code>tax</code>, <code>total</code>) as first-class fields, so the API payload is identical to what the RHF version assembled manually in <code>onSubmit</code>.</li>
<li>The <code>mutationRef</code> pattern is the same one you’d reach for anywhere you need a stable event handler over a value that changes on every render &mdash; nothing SurveyJS-specific about it.</li>
</ul>

<p>The React component no longer contains any business logic at all. There’s no <code>useWatch</code>, no conditional JSX, no step counter, no <code>useMemo</code> chain, no <code>superRefine</code>. React is doing what it’s actually good at: rendering a component and wiring it to an API call.</p>

<h2 id="what-moved-out-of-react">What Moved Out Of React?</h2>

<table class="tablesaw break-out">
    <thead>
        <tr>
            <th>Concern</th>
            <th>RHF Stack</th>
      <th>SurveyJS</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Visibility</td>
            <td>JSX branches</td>
      <td><code>visibleIf</code></td>
        </tr>
        <tr>
            <td>Derived values</td>
            <td><code>useWatch</code> / <code>useMemo</code></td>
      <td><code>expression</code></td>
        </tr>
        <tr>
            <td>Cross-field rules</td>
            <td><code>superRefine</code></td>
      <td>Schema conditions</td>
        </tr>
    <tr>
            <td>Navigation</td>
            <td><code>step</code> state</td>
      <td>Page <code>visibleIf</code></td>
        </tr>
     <tr>
            <td>Rule location</td>
            <td>Distributed across files</td>
      <td>Centralized in the schema</td>
        </tr>
    </tbody>
</table>

<p>What stays in React is layout, styling, submission wiring, and app integration, which is to say, <strong>the things React is actually designed for</strong>.</p>

<p>Everything else moved into the schema, and because the schema is just a JSON object, it can be stored in a database, versioned independently of your application code, or edited through internal tooling without requiring a deploy.</p>

<p>A product manager who needs to change the threshold that triggers the review page can do that without touching the component. That’s a meaningful operational difference for teams where form behavior evolves frequently and isn’t always driven by engineers.</p>

<h2 id="when-to-use-each-approach">When To Use Each Approach?</h2>

<p>Here’s a good rule of thumb that works for me: <strong>imagine deleting the form entirely</strong>. What would you lose?</p>

<ul>
<li>If it’s screens, you want component-driven forms.</li>
<li>If it’s business logic, like thresholds, branching rules, and conditional requirements that encode real decisions, you want a schema engine.</li>
</ul>

<p>Similarly, if the changes coming your way are mostly about labels, fields, and layout, RHF will serve you fine. If they’re about conditions, outcomes, and rules that your ops or legal team might need to adjust on a Tuesday afternoon without filing a ticket, the schema model with SurveyJS is the more honest fit.</p>

<p><strong>These two approaches are not really in competition with each other.</strong> They address different classes of problems, and the mistake worth avoiding is mismatching the abstraction to the weight of the logic &mdash; treating a rule system like a component because that’s the familiar tool, or reaching for a policy engine because a form grew to three steps and acquired a conditional field.</p>

<p>The form we built here sits near the boundary deliberately, complex enough to expose the difference but not so extreme that the comparison feels rigged. Most real forms that have gotten unwieldy in your codebase probably sit near that same boundary, and the question is usually just whether anyone has named what they actually are.</p>

<p><strong>Use React Hook Form + Zod when:</strong></p>

<ul>
<li>Forms are CRUD-oriented;</li>
<li>Logic is shallow and UI-driven;</li>
<li>Engineers own all behavior;</li>
<li>Backend remains the source of truth.</li>
</ul>

<p><strong>Use SurveyJS when:</strong></p>

<ul>
<li>Forms encode business decisions;</li>
<li>Rules evolve independently of UI;</li>
<li>Logic must be visible, auditable, or versioned;</li>
<li>Non-engineers influence behavior;</li>
<li>The same form must run across multiple frontends.</li>
</ul>

<div class="signature">
  <img src="https://www.smashingmagazine.com/images/logo/logo--red.png" alt="Smashing Editorial" width="35" height="46" loading="lazy" decoding="async" />
  <span>(yk)</span>
</div>


              </article>
            </body>
          </html>
        ]]></content:encoded></item><item><author>Mat Marquis</author><title>JavaScript For Everyone: Iterators</title><link>https://www.smashingmagazine.com/2025/10/javascript-for-everyone-iterators/</link><pubDate>Mon, 27 Oct 2025 13:00:00 +0000</pubDate><guid>https://www.smashingmagazine.com/2025/10/javascript-for-everyone-iterators/</guid><description>Here is a lesson on Iterators: iterables implement the iterable iteration interface, and iterators implement the iterator iteration interface. Sounds confusing? Mat breaks it all down in the article.</description><content:encoded><![CDATA[
          <html>
            <head>
              <meta charset="utf-8">
              <link rel="canonical" href="https://www.smashingmagazine.com/2025/10/javascript-for-everyone-iterators/" />
              <title>JavaScript For Everyone: Iterators</title>
            </head>
            <body>
              <article>
                <header>
                  <h1>JavaScript For Everyone: Iterators</h1>
                  
                    
                    <address>Mat Marquis</address>
                  
                  <time datetime="2025-10-27T13:00:00&#43;00:00" class="op-published">2025-10-27T13:00:00+00:00</time>
                  <time datetime="2025-10-27T13:00:00&#43;00:00" class="op-modified">2026-11-13T04:40:45+00:00</time>
                </header>
                
                

<p>Hey, I’m Mat, but “Wilto” works too &mdash; I’m here to teach you JavaScript. Well, not <em>here</em>-here; technically, I’m over at <a href="https://piccalil.li/javascript-for-everyone">Piccalil.li’s <em>JavaScript for Everyone</em></a> course to teach you JavaScript. The following is an excerpt from the <strong>Iterables and Iterators</strong> module: the lesson on Iterators.</p>

<p>Iterators are one of JavaScript’s more linguistically confusing topics, sailing <em>easily</em> over what is already a pretty high bar. There are <em>iterables</em> &mdash; array, Set, Map, and string &mdash; all of which follow the <strong>iterable protocol</strong>. To follow said protocol, an object must implement the <strong>iterable interface</strong>. In practice, that means that the object needs to include a <code>[Symbol.iterator]()</code> method somewhere in its prototype chain. Iterable protocol is one of two <strong>iteration protocols</strong>. The other iteration protocol is the <strong>iterator protocol</strong>.</p>

<p>See what I mean about this being linguistically fraught? Iterables implement the iterable iteration interface, and iterators implement the iterator iteration interface! If you can say that five times fast, then you’ve pretty much got the gist of it; easy-peasy, right?</p>

<p>No, listen, by the time you reach the end of this lesson, I promise it won’t be half as confusing as it might sound, especially with the context you’ll have from the lessons that precede it.</p>

<p>An <strong>iterable</strong> object follows the iterable protocol, which just means that the object has a conventional method for making iterators. The elements that it contains can be looped over with <code>for</code>…<code>of</code>.</p>

<p>An <strong>iterator</strong> object follows the iterator protocol, and the elements it contains can be accessed <em>sequentially</em>, one at a time.</p>

<div data-audience="non-subscriber" data-remove="true" class="feature-panel-container">

<aside class="feature-panel" style="">
<div class="feature-panel-left-col">

<div class="feature-panel-description"><p><strong>Web forms</strong> are at the center of every meaningful interaction. Meet Adam Silver&rsquo;s <strong><a href="https://www.smashingmagazine.com/printed-books/form-design-patterns/">Form Design Patterns</a></strong>, a practical guide to <strong>designing and building forms</strong> for the web.</p>
<a data-instant href="https://www.smashingmagazine.com/printed-books/form-design-patterns/" class="btn btn--green btn--large" style="">Jump to table of contents&nbsp;↬</a></div>
</div>
<div class="feature-panel-right-col"><a data-instant href="https://www.smashingmagazine.com/printed-books/form-design-patterns/" class="feature-panel-image-link">
<div class="feature-panel-image"><picture><source type="image/avif" srcSet="https://archive.smashing.media/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/64e57b41-b7f1-4ae3-886a-806cce580ef9/form-design-patterns-shop-image-1-1.avif" />
<img
    loading="lazy"
    decoding="async"
    class="feature-panel-image-img"
    src="https://archive.smashing.media/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/51e0f837-d85d-4b28-bfab-1c9a47f0ce33/form-design-patterns-shop-image.png"
    alt="Feature Panel"
    width="481"
    height="698"
/>
</picture>
</div>
</a>
</div>
</aside>
</div>

<p>To <em>reiterate</em> &mdash; a play on words for which I do not forgive myself, nor expect you to forgive me &mdash; an <strong>iterator</strong> object follows iterator protocol, and the elements it contains can be accessed <em>sequentially</em>, one at a time. Iterator protocol defines a standard way to produce a sequence of values, and optionally <code>return</code> a value once all possible values have been generated.</p>

<p>In order to follow the iterator protocol, an object has to &mdash; you guessed it &mdash; implement the <strong>iterator interface</strong>. In practice, that once again means that a certain method has to be available somewhere on the object&rsquo;s prototype chain. In this case, it’s the <code>next()</code> method that advances through the elements it contains, one at a time, and returns an object each time that method is called.</p>

<p>In order to meet the iterator interface criteria, the returned object must contain two properties with specific keys: one with the key <code>value</code>, representing the value of the current element, and one with the key <code>done</code>, a Boolean value that tells us if the iterator has advanced beyond the final element in the data structure. That’s not an awkward phrasing the editorial team let slip through: the value of that <code>done</code> property is <code>true</code> only when a call to <code>next()</code> results in an attempt to access an element <em>beyond</em> the final element in the iterator, not upon accessing the final element in the iterator. Again, a lot in print, but it’ll make more sense when you see it in action.</p>

<p>You’ve seen an example of a built-in iterator before, albeit briefly:</p>

<pre><code class="language-jsx">const theMap = new Map([ [ "aKey", "A value." ] ]);

console.log( theMap.keys() );
// Result: Map Iterator { constructor: Iterator() }
</code></pre>

<p>That’s right: while a Map object itself is an iterable, Map’s built-in methods <code>keys()</code>, <code>values()</code>, and <code>entries()</code> all return Iterator objects. You’ll also remember that I looped through those using <code>forEach</code> (a relatively recent addition to the language). Used that way, an iterator is indistinguishable from an iterable:</p>

<pre><code class="language-jsx">const theMap = new Map([ [ "key", "value " ] ]);

theMap.keys().forEach( thing =&gt; {
  console.log( thing );
});
// Result: key
</code></pre>

<p>All iterators are iterable; they all implement the iterable interface:</p>

<pre><code class="language-jsx">const theMap = new Map([ [ "key", "value " ] ]);

theMap.keys()[ Symbol.iterator ];
// Result: function Symbol.iterator()
</code></pre>

<p>And if you’re angry about the increasing blurriness of the line between iterators and iterables, wait until you get a load of this “top ten anime betrayals” video candidate: I’m going to demonstrate how to interact with an iterator by using an array.</p>

<p>“BOO,” you surely cry, having been so betrayed by one of your oldest and most indexed friends. “Array is an itera<em>ble</em>, not an itera<em>tor</em>!” You are both right to yell at me in general, and right about array in specific &mdash; an array <em>is</em> an iterable, not an iterator. In fact, while all iterators are iterable, none of the built-in iterables are iterators.</p>

<p>However, when you call that <code>[ Symbol.iterator ]()</code> method &mdash; the one that defines an object as an iterable &mdash; it returns an iterator object created from an iterable data structure:</p>

<pre><code class="language-jsx">const theIterable = [ true, false ];
const theIterator = theIterable[ Symbol.iterator ]();

theIterable;
// Result: Array [ true, false ]

theIterator;
// Result: Array Iterator { constructor: Iterator() }
</code></pre>

<p>The same goes for Set, Map, and &mdash; yes &mdash; even strings:</p>

<pre><code class="language-jsx">const theIterable = "A string."
const theIterator = theIterable[ Symbol.iterator ]();

theIterator;
// Result: String Iterator { constructor: Iterator() }
</code></pre>

<p>What we’re doing here manually &mdash; creating an iterator from an iterable using <code>%Symbol.iterator%</code> &mdash; is precisely how iterable objects work internally, and why they have to implement <code>%Symbol.iterator%</code> in order to <em>be</em> iterables. Any time you loop through an array, you’re actually looping through an iterator created from that Array. All built-in iterators <em>are</em> iterable. All built-in iterables can be used to <em>create</em> iterators.</p>

<p>Alternately &mdash; <em>preferably</em>, even, since it doesn’t require you to graze up against <code>%Symbol.iterator%</code> directly &mdash; you can use the built-in <code>Iterator.from()</code> method to create an iterator object from any iterable:</p>

<pre><code class="language-jsx">const theIterator = Iterator.from([ true, false ]);

theIterator;
// Result: Array Iterator { constructor: Iterator() }
</code></pre>

<p>You remember how I mentioned that an iterator has to provide a <code>next()</code> method (that returns a very specific Object)? Calling that <code>next()</code> method steps through the elements that the iterator contains one at a time, with each call returning an instance of that Object:</p>

<pre><code class="language-jsx">const theIterator = Iterator.from([ 1, 2, 3 ]);

theIterator.next();
// Result: Object { value: 1, done: false }

theIterator.next();
// Result: Object { value: 2, done: false }

theIterator.next();
// Result: Object { value: 3, done: false }

theIterator.next();
// Result: Object { value: undefined, done: true }
</code></pre>

<p>You can think of this as a more controlled form of traversal than the traditional “wind it up and watch it go” <code>for</code> loops you’re probably used to &mdash; a method of accessing elements one step at a time, as-needed. Granted, you don’t <em>have</em> to step through an iterator in this way, since they have their very own <code>Iterator.forEach</code> method, which works exactly like you would expect &mdash; to a point:</p>

<pre><code class="language-jsx">const theIterator = Iterator.from([ true, false ]);

theIterator.forEach( element =&gt; console.log( element ) );
/&#42; Result:
true
false
&#42;/
</code></pre>

<p>But there’s another big difference between iterables and iterators that we haven’t touched on yet, and for my money, it actually goes a long way toward making <em>linguistic</em> sense of the two. You might need to humor me for a little bit here, though.</p>

<p>See, an iterable object is an object that is iterable. No, listen, stay with me: you can iterate over an Array, and when you’re done doing so, you can still iterate over that Array. It is, by definition, an object that can be iterated over; it is the essential nature of an iterable to be iterable:</p>

<pre><code class="language-jsx">const theIterable = [ 1, 2 ];

theIterable.forEach( el =&gt; {
  console.log( el );
});
/&#42; Result:
1
2
&#42;/

theIterable.forEach( el =&gt; {
  console.log( el );
});
/&#42; Result:
1
2
&#42;/
</code></pre>

<p>In a way, an iterator object represents the singular <em>act</em> of iteration. Internal to an iterable, it is the mechanism by which the iterable is iterated over, each time that iteration is performed. As a stand-alone iterator object &mdash; whether you step through it using the <code>next</code> method or loop over its elements using <code>forEach</code> &mdash; once iterated over, that iterator is <em>past tense</em>; it is <em>iterated</em>. Because they maintain an internal state, the essential nature of an iterator is to be iterated over, singular:</p>

<pre><code class="language-jsx">const theIterator = Iterator.from([ 1, 2 ]);

theIterator.next();
// Result: Object { value: 1, done: false }

theIterator.next();
// Result: Object { value: 2, done: false }

theIterator.next();
// Result: Object { value: undefined, done: true }

theIterator.forEach( el =&gt; console.log( el ) );
// Result: undefined
</code></pre>

<p>That makes for neat work when you&rsquo;re using the Iterator constructor’s built-in methods to, say, filter or extract part of an Iterator object:</p>

<div class="break-out">
<pre><code class="language-jsx">const theIterator = Iterator.from([ "First", "Second", "Third" ]);

// Take the first two values from `theIterator`:
theIterator.take( 2 ).forEach( el =&gt; {
  console.log( el );
});
/&#42; Result:
"First"
"Second"
&#42;/

// theIterator now only contains anything left over after the above operation is complete:
theIterator.next();
// Result: Object { value: "Third", done: false }
</code></pre>
</div>

<p>Once you reach the end of an iterator, the act of iterating over it is complete. Iterated. Past-tense.</p>

<p>And so too is your time in this lesson, you might be relieved to hear. I know this was kind of a rough one, but the good news is: this course is iterable, not an iterator. This step in your iteration through it &mdash; this lesson &mdash; may be over, but the essential nature of this course is that you can iterate through it again. Don’t worry about committing all of this to memory right now &mdash; you can come back and revisit this lesson anytime.</p>

<div class="partners__lead-place"></div>

<h2 id="conclusion">Conclusion</h2>

<p>I stand by what I wrote there, unsurprising as that probably is: this lesson is a tricky one, but listen, <em>you got this</em>. <a href="https://piccalil.li/javascript-for-everyone">JavaScript for Everyone</a> is designed to take you inside JavaScript’s head. Once you’ve started seeing how the gears mesh &mdash; seen the fingerprints left behind by the people who built the language, and the good, bad, and sometimes baffling decisions that went into that &mdash; no <em>itera-</em>, whether <em>-ble</em> or <em>-tor</em> will be able to stand in your way.</p>














<figure class="
  
    break-out article__image
  
  
  ">
  
    <a href="https://piccalil.li/javascript-for-everyone">
    
    <img
      loading="lazy"
      decoding="async"
      fetchpriority="low"
			width="800"
			height="450"
			
			srcset="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/javascript-for-everyone-iterators/1-javascript-for-everyone.png 400w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_800/https://files.smashing.media/articles/javascript-for-everyone-iterators/1-javascript-for-everyone.png 800w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1200/https://files.smashing.media/articles/javascript-for-everyone-iterators/1-javascript-for-everyone.png 1200w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1600/https://files.smashing.media/articles/javascript-for-everyone-iterators/1-javascript-for-everyone.png 1600w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_2000/https://files.smashing.media/articles/javascript-for-everyone-iterators/1-javascript-for-everyone.png 2000w"
			src="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/javascript-for-everyone-iterators/1-javascript-for-everyone.png"
			
			sizes="100vw"
			alt="Javascript for everyone course announcement"
		/>
    
    </a>
  

  
    <figcaption class="op-vertical-bottom">
      <a href='https://piccalil.li/javascript-for-everyone'>JavaScript for Everyone</a> is now available and the launch price runs until midnight, October 28. Save £60 off the full price of £249 and get it for £189! (<a href='https://files.smashing.media/articles/javascript-for-everyone-iterators/1-javascript-for-everyone.png'>Large preview</a>)
    </figcaption>
  
</figure>

<p>My goal is to teach you the <em>deep magic</em> &mdash; the <em>how</em> and the <em>why</em> of JavaScript, using the syntaxes you’re most likely to encounter in your day-to-day work, at your pace and on your terms. If you’re new to the language, you’ll walk away from this course with a foundational understanding of JavaScript worth hundreds of hours of trial-and-error. If you’re a junior developer, you’ll finish this course with a depth of knowledge to rival any senior.</p>

<p>I hope to see you there.</p>

<div class="signature">
  <img src="https://www.smashingmagazine.com/images/logo/logo--red.png" alt="Smashing Editorial" width="35" height="46" loading="lazy" decoding="async" />
  <span>(gg, yk)</span>
</div>


              </article>
            </body>
          </html>
        ]]></content:encoded></item><item><author>Fuqiao Xue</author><title>The Power Of The &lt;code>Intl&lt;/code> API: A Definitive Guide To Browser-Native Internationalization</title><link>https://www.smashingmagazine.com/2025/08/power-intl-api-guide-browser-native-internationalization/</link><pubDate>Fri, 08 Aug 2025 10:00:00 +0000</pubDate><guid>https://www.smashingmagazine.com/2025/08/power-intl-api-guide-browser-native-internationalization/</guid><description>Internationalization isn’t just translation. It’s about formatting dates, pluralizing words, sorting names, and more, all according to specific locales. Instead of relying on heavy third-party libraries, modern JavaScript offers the Intl API &amp;mdash; a powerful, native way to handle i18n. A quiet reminder that the web truly is worldwide.</description><content:encoded><![CDATA[
          <html>
            <head>
              <meta charset="utf-8">
              <link rel="canonical" href="https://www.smashingmagazine.com/2025/08/power-intl-api-guide-browser-native-internationalization/" />
              <title>The Power Of The &lt;code&gt;Intl&lt;/code&gt; API: A Definitive Guide To Browser-Native Internationalization</title>
            </head>
            <body>
              <article>
                <header>
                  <h1>The Power Of The &lt;code&gt;Intl&lt;/code&gt; API: A Definitive Guide To Browser-Native Internationalization</h1>
                  
                    
                    <address>Fuqiao Xue</address>
                  
                  <time datetime="2025-08-08T10:00:00&#43;00:00" class="op-published">2025-08-08T10:00:00+00:00</time>
                  <time datetime="2025-08-08T10:00:00&#43;00:00" class="op-modified">2026-11-13T04:40:45+00:00</time>
                </header>
                
                

<p>It’s a common misconception that internationalization (i18n) is simply about translating text. While crucial, translation is merely one facet. One of the complexities lies in <strong>adapting information for diverse cultural expectations</strong>: How do you display a date in Japan versus Germany? What’s the correct way to pluralize an item in Arabic versus English? How do you sort a list of names in various languages?</p>

<p>Many developers have relied on weighty third-party libraries or, worse, custom-built formatting functions to tackle these challenges. These solutions, while functional, often come with significant overhead: increased bundle size, potential performance bottlenecks, and the constant struggle to keep up with evolving linguistic rules and locale data.</p>

<p>Enter the <strong>ECMAScript Internationalization API</strong>, more commonly known as the <code>Intl</code> object. This silent powerhouse, built directly into modern JavaScript environments, is an often-underestimated, yet incredibly <strong>potent, native, performant, and standards-compliant solution</strong> for handling data internationalization. It’s a testament to the web’s commitment to being <em>worldwide</em>, providing a unified and efficient way to format numbers, dates, lists, and more, according to specific locales.</p>

<h2 id="intl-and-locales-more-than-just-language-codes"><code>Intl</code> And Locales: More Than Just Language Codes</h2>

<p>At the heart of <code>Intl</code> lies the concept of a <strong>locale</strong>. A locale is far more than just a two-letter language code (like <code>en</code> for English or <code>es</code> for Spanish). It encapsulates the complete context needed to present information appropriately for a specific cultural group. This includes:</p>

<ul>
<li><strong>Language</strong>: The primary linguistic medium (e.g., <code>en</code>, <code>es</code>, <code>fr</code>).</li>
<li><strong>Script</strong>: The script (e.g., <code>Latn</code> for Latin, <code>Cyrl</code> for Cyrillic). For example, <code>zh-Hans</code> for Simplified Chinese, vs. <code>zh-Hant</code> for Traditional Chinese.</li>
<li><strong>Region</strong>: The geographic area (e.g., <code>US</code> for United States, <code>GB</code> for Great Britain, <code>DE</code> for Germany). This is crucial for variations within the same language, such as <code>en-US</code> vs. <code>en-GB</code>, which differ in date, time, and number formatting.</li>
<li><strong>Preferences/Variants</strong>: Further specific cultural or linguistic preferences. See <a href="https://www.w3.org/International/questions/qa-choosing-language-tags">“Choosing a Language Tag”</a> from W3C for more information.</li>
</ul>

<p>Typically, you’ll want to choose the locale according to the language of the web page. This can be determined from the <code>lang</code> attribute:</p>

<div class="break-out">
<pre><code class="language-javascript">// Get the page's language from the HTML lang attribute
const pageLocale = document.documentElement.lang || 'en-US'; // Fallback to 'en-US'
</code></pre>
</div>

<p>Occasionally, you may want to override the page locale with a specific locale, such as when displaying content in multiple languages:</p>

<div class="break-out">
<pre><code class="language-javascript">// Force a specific locale regardless of page language
const tutorialFormatter = new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY' });

console.log(`Chinese example: ${tutorialFormatter.format(199.99)}`); // Output: ¥199.99
</code></pre>
</div>

<p>In some cases, you might want to use the user’s preferred language:</p>

<div class="break-out">
<pre><code class="language-javascript">// Use the user's preferred language
const browserLocale = navigator.language || 'ja-JP';

const formatter = new Intl.NumberFormat(browserLocale, { style: 'currency', currency: 'JPY' });
</code></pre>
</div>

<p>When you instantiate an <code>Intl</code> formatter, you can optionally pass one or more locale strings. The API will then select the most appropriate locale based on availability and preference.</p>

<h2 id="core-formatting-powerhouses">Core Formatting Powerhouses</h2>

<p>The <code>Intl</code> object exposes several constructors, each for a specific formatting task. Let’s delve into the most frequently used ones, along with some powerful, often-overlooked gems.</p>

<h3 id="1-intl-datetimeformat-dates-and-times-globally">1. <code>Intl.DateTimeFormat</code>: Dates and Times, Globally</h3>

<p>Formatting dates and times is a classic i18n problem. Should it be MM/DD/YYYY or DD.MM.YYYY? Should the month be a number or a full word? <code>Intl.DateTimeFormat</code> handles all this with ease.</p>

<div class="break-out">
<pre><code class="language-javascript">const date = new Date(2025, 6, 27, 14, 30, 0); // June 27, 2025, 2:30 PM

// Specific locale and options (e.g., long date, short time)
const options = {
  weekday: 'long',
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  timeZoneName: 'shortOffset' // e.g., "GMT+8"
};

console.log(new Intl.DateTimeFormat('en-US', options).format(date));

// "Friday, June 27, 2025 at 2:30 PM GMT+8"
console.log(new Intl.DateTimeFormat('de-DE', options).format(date));

// "Freitag, 27. Juni 2025 um 14:30 GMT+8"

// Using dateStyle and timeStyle for common patterns
console.log(new Intl.DateTimeFormat('en-GB', { dateStyle: 'full', timeStyle: 'short' }).format(date));

// "Friday 27 June 2025 at 14:30"

console.log(new Intl.DateTimeFormat('ja-JP', { dateStyle: 'long', timeStyle: 'short' }).format(date));

// "2025年6月27日 14:30"
</code></pre>
</div>

<p>The flexibility of <code>options</code> for <code>DateTimeFormat</code> is vast, allowing control over year, month, day, weekday, hour, minute, second, time zone, and more.</p>

<h3 id="2-intl-numberformat-numbers-with-cultural-nuance">2. <code>Intl.NumberFormat</code>: Numbers With Cultural Nuance</h3>

<p>Beyond simple decimal places, numbers require careful handling: thousands separators, decimal markers, currency symbols, and percentage signs vary wildly across locales.</p>

<div class="break-out">
<pre><code class="language-javascript">const price = 123456.789;

// Currency formatting
console.log(new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(price));

// "$123,456.79" (auto-rounds)

console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(price));

// "123.456,79 €"

// Units
console.log(new Intl.NumberFormat('en-US', { style: 'unit', unit: 'meter', unitDisplay: 'long' }).format(100));

// "100 meters"

console.log(new Intl.NumberFormat('fr-FR', { style: 'unit', unit: 'kilogram', unitDisplay: 'short' }).format(5.5));

// "5,5 kg"
</code></pre>
</div>

<p>Options like <code>minimumFractionDigits</code>, <code>maximumFractionDigits</code>, and <code>notation</code> (e.g., <code>scientific</code>, <code>compact</code>) provide even finer control.</p>

<h3 id="3-intl-listformat-natural-language-lists">3. <code>Intl.ListFormat</code>: Natural Language Lists</h3>

<p>Presenting lists of items is surprisingly tricky. English uses “and” for conjunction and “or” for disjunction. Many languages have different conjunctions, and some require specific punctuation.</p>

<p>This API simplifies a task that would otherwise require complex conditional logic:</p>

<div class="break-out">
<pre><code class="language-javascript">const items = ['apples', 'oranges', 'bananas'];

// Conjunction ("and") list
console.log(new Intl.ListFormat('en-US', { type: 'conjunction' }).format(items));

// "apples, oranges, and bananas"

console.log(new Intl.ListFormat('de-DE', { type: 'conjunction' }).format(items));

// "Äpfel, Orangen und Bananen"

// Disjunction ("or") list
console.log(new Intl.ListFormat('en-US', { type: 'disjunction' }).format(items));

// "apples, oranges, or bananas"

console.log(new Intl.ListFormat('fr-FR', { type: 'disjunction' }).format(items));

// "apples, oranges ou bananas"
</code></pre>
</div>

<h3 id="4-intl-relativetimeformat-human-friendly-timestamps">4. <code>Intl.RelativeTimeFormat</code>: Human-Friendly Timestamps</h3>

<p>Displaying “2 days ago” or “in 3 months” is common in UI, but localizing these phrases accurately requires extensive data. <code>Intl.RelativeTimeFormat</code> automates this.</p>

<div class="break-out">
<pre><code class="language-javascript">const rtf = new Intl.RelativeTimeFormat('en-US', { numeric: 'auto' });

console.log(rtf.format(-1, 'day'));    // "yesterday"
console.log(rtf.format(1, 'day'));     // "tomorrow"
console.log(rtf.format(-7, 'day'));    // "7 days ago"
console.log(rtf.format(3, 'month'));   // "in 3 months"
console.log(rtf.format(-2, 'year'));   // "2 years ago"

// French example:
const frRtf = new Intl.RelativeTimeFormat('fr-FR', { numeric: 'auto', style: 'long' });

console.log(frRtf.format(-1, 'day'));    // "hier"
console.log(frRtf.format(1, 'day'));     // "demain"
console.log(frRtf.format(-7, 'day'));    // "il y a 7 jours"
console.log(frRtf.format(3, 'month'));   // "dans 3 mois"
</code></pre>
</div>

<p>The <code>numeric: 'always'</code> option would force “1 day ago” instead of “yesterday”.</p>

<h3 id="5-intl-pluralrules-mastering-pluralization">5. <code>Intl.PluralRules</code>: Mastering Pluralization</h3>

<p>This is arguably one of the most critical aspects of i18n. Different languages have vastly different pluralization rules (e.g., English has singular/plural, Arabic has zero, one, two, many&hellip;). <code>Intl.PluralRules</code> allows you to determine the “plural category” for a given number in a specific locale.</p>

<pre><code class="language-javascript">const prEn = new Intl.PluralRules('en-US');

console.log(prEn.select(0));    // "other" (for "0 items")
console.log(prEn.select(1));    // "one"   (for "1 item")
console.log(prEn.select(2));    // "other" (for "2 items")

const prAr = new Intl.PluralRules('ar-EG');

console.log(prAr.select(0));    // "zero"
console.log(prAr.select(1));    // "one"
console.log(prAr.select(2));    // "two"
console.log(prAr.select(10));   // "few"
console.log(prAr.select(100));  // "other"
</code></pre>

<p>This API doesn’t pluralize text directly, but it provides the essential classification needed to select the correct translation string from your message bundles. For example, if you have message keys like <code>item.one</code>, <code>item.other</code>, you’d use <code>pr.select(count)</code> to pick the right one.</p>

<h3 id="6-intl-displaynames-localized-names-for-everything">6. <code>Intl.DisplayNames</code>: Localized Names For Everything</h3>

<p>Need to display the name of a language, a region, or a script in the user’s preferred language? <code>Intl.DisplayNames</code> is your comprehensive solution.</p>

<div class="break-out">
<pre><code class="language-javascript">// Display language names in English
const langNamesEn = new Intl.DisplayNames(['en'], { type: 'language' });

console.log(langNamesEn.of('fr'));      // "French"
console.log(langNamesEn.of('es-MX'));   // "Mexican Spanish"

// Display language names in French
const langNamesFr = new Intl.DisplayNames(['fr'], { type: 'language' });

console.log(langNamesFr.of('en'));      // "anglais"
console.log(langNamesFr.of('zh-Hans')); // "chinois (simplifié)"

// Display region names
const regionNamesEn = new Intl.DisplayNames(['en'], { type: 'region' });

console.log(regionNamesEn.of('US'));    // "United States"
console.log(regionNamesEn.of('DE'));    // "Germany"

// Display script names
const scriptNamesEn = new Intl.DisplayNames(['en'], { type: 'script' });

console.log(scriptNamesEn.of('Latn'));  // "Latin"
console.log(scriptNamesEn.of('Arab'));  // "Arabic"
</code></pre>
</div>

<p>With <code>Intl.DisplayNames</code>, you avoid hardcoding countless mappings for language names, regions, or scripts, keeping your application robust and lean.</p>

<h2 id="browser-support">Browser Support</h2>

<p>You might be wondering about browser compatibility. The good news is that <code>Intl</code> has excellent support across modern browsers. All major browsers (Chrome, Firefox, Safari, Edge) fully support the core functionality discussed (<code>DateTimeFormat</code>, <code>NumberFormat</code>, <code>ListFormat</code>, <code>RelativeTimeFormat</code>, <code>PluralRules</code>, <code>DisplayNames</code>). You can confidently use these APIs without polyfills for the majority of your user base.</p>

<h2 id="conclusion-embrace-the-global-web-with-intl">Conclusion: Embrace The Global Web With <code>Intl</code></h2>

<p>The <code>Intl</code> API is a cornerstone of modern web development for a global audience. It empowers front-end developers to deliver <strong>highly localized user experiences</strong> with minimal effort, leveraging the browser’s built-in, optimized capabilities.</p>

<p>By adopting <code>Intl</code>, you <strong>reduce dependencies</strong>, <strong>shrink bundle sizes</strong>, and <strong>improve performance</strong>, all while ensuring your application respects and adapts to the diverse linguistic and cultural expectations of users worldwide. Stop wrestling with custom formatting logic and embrace this standards-compliant tool!</p>

<p>It’s important to remember that <code>Intl</code> handles the <em>formatting</em> of data. While incredibly powerful, it doesn’t solve every aspect of internationalization. Content translation, bidirectional text (RTL/LTR), locale-specific typography, and deep cultural nuances beyond data formatting still require careful consideration. (I may write about these in the future!) However, for presenting dynamic data accurately and intuitively, <code>Intl</code> is the browser-native answer.</p>

<h3 id="further-reading-resources">Further Reading &amp; Resources</h3>

<ul>
<li>MDN Web Docs:

<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl"><code>Intl namespace object</code></a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat"><code>Intl.DateTimeFormat</code></a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat"><code>Intl.NumberFormat</code></a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat"><code>Intl.ListFormat</code></a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat"><code>Intl.RelativeTimeFormat</code></a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules"><code>Intl.PluralRules</code></a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames"><code>Intl.DisplayNames</code></a></li>
</ul></li>
<li>ECMAScript Internationalization API Specification: <a href="https://tc39.es/ecma402/">The official ECMA-402 Standard</a></li>
<li><a href="https://www.w3.org/International/questions/qa-choosing-language-tags">Choosing a Language Tag</a></li>
</ul>

<div class="signature">
  <img src="https://www.smashingmagazine.com/images/logo/logo--red.png" alt="Smashing Editorial" width="35" height="46" loading="lazy" decoding="async" />
  <span>(gg, yk)</span>
</div>


              </article>
            </body>
          </html>
        ]]></content:encoded></item><item><author>Amejimaobari Ollornwi</author><title>Handling JavaScript Event Listeners With Parameters</title><link>https://www.smashingmagazine.com/2025/07/handling-javascript-event-listeners-parameters/</link><pubDate>Mon, 21 Jul 2025 10:00:00 +0000</pubDate><guid>https://www.smashingmagazine.com/2025/07/handling-javascript-event-listeners-parameters/</guid><description>Event listeners are essential for interactivity in JavaScript, but they can quietly cause memory leaks if not removed properly. And what if your event listener needs parameters? That’s where things get interesting. Amejimaobari Ollornwi shares which JavaScript features make handling parameters with event handlers both possible and well-supported.</description><content:encoded><![CDATA[
          <html>
            <head>
              <meta charset="utf-8">
              <link rel="canonical" href="https://www.smashingmagazine.com/2025/07/handling-javascript-event-listeners-parameters/" />
              <title>Handling JavaScript Event Listeners With Parameters</title>
            </head>
            <body>
              <article>
                <header>
                  <h1>Handling JavaScript Event Listeners With Parameters</h1>
                  
                    
                    <address>Amejimaobari Ollornwi</address>
                  
                  <time datetime="2025-07-21T10:00:00&#43;00:00" class="op-published">2025-07-21T10:00:00+00:00</time>
                  <time datetime="2025-07-21T10:00:00&#43;00:00" class="op-modified">2026-11-13T04:40:45+00:00</time>
                </header>
                
                

<p>JavaScript event listeners are very important, as they exist in almost every web application that requires interactivity. As common as they are, it is also essential for them to be managed properly. Improperly managed event listeners can lead to memory leaks and can sometimes cause performance issues in extreme cases.</p>

<p>Here’s the real problem: <strong>JavaScript event listeners are often not removed after they are added.</strong> And when they are added, they do not require parameters most of the time &mdash; except in rare cases, which makes them a little trickier to handle.</p>

<p>A common scenario where you may need to use parameters with event handlers is when you have a dynamic list of tasks, where each task in the list has a “Delete” button attached to an event handler that uses the task’s ID as a parameter to remove the task. In a situation like this, it is a good idea to remove the event listener once the task has been completed to ensure that the deleted element can be successfully cleaned up, a process known as <a href="https://javascript.info/garbage-collection">garbage collecti</a><a href="https://javascript.info/garbage-collection">on</a>.</p>

<h2 id="a-common-mistake-when-adding-event-listeners">A Common Mistake When Adding Event Listeners</h2>

<p>A very common mistake when adding parameters to event handlers is calling the function with its parameters inside the <code>addEventListener()</code> method. This is what I mean:</p>

<pre><code class="language-javascript">button.addEventListener('click', myFunction(param1, param2));
</code></pre>

<p>The browser responds to this line by immediately calling the function, irrespective of whether or not the click event has happened. In other words, the function is invoked right away instead of being deferred, so it never fires when the click event actually occurs.</p>

<p>You may also receive the following console error in some cases:</p>














<figure class="
  
    break-out article__image
  
  
  ">
  
    <a href="https://files.smashing.media/articles/handling-javascript-event-listeners-parameters/1-uncaught-typeerror.png">
    
    <img
      loading="lazy"
      decoding="async"
      fetchpriority="low"
			width="800"
			height="75"
			
			srcset="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/handling-javascript-event-listeners-parameters/1-uncaught-typeerror.png 400w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_800/https://files.smashing.media/articles/handling-javascript-event-listeners-parameters/1-uncaught-typeerror.png 800w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1200/https://files.smashing.media/articles/handling-javascript-event-listeners-parameters/1-uncaught-typeerror.png 1200w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1600/https://files.smashing.media/articles/handling-javascript-event-listeners-parameters/1-uncaught-typeerror.png 1600w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_2000/https://files.smashing.media/articles/handling-javascript-event-listeners-parameters/1-uncaught-typeerror.png 2000w"
			src="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/handling-javascript-event-listeners-parameters/1-uncaught-typeerror.png"
			
			sizes="100vw"
			alt="Uncaught TypeError"
		/>
    
    </a>
  

  
    <figcaption class="op-vertical-bottom">
      Uncaught TypeError: Failed to execute. <code>addEventListener</code> on <code>EventTarget</code>: parameter is not of type <code>Object</code>. (<a href='https://files.smashing.media/articles/handling-javascript-event-listeners-parameters/1-uncaught-typeerror.png'>Large preview</a>)
    </figcaption>
  
</figure>

<p>This error makes sense because the second parameter of the <code>addEventListener</code> method <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#listener">can only accept</a> a JavaScript function, an object with a <code>handleEvent()</code> method, or simply <code>null</code>. A quick and easy way to avoid this error is by changing the second parameter of the <code>addEventListener</code> method to an arrow or anonymous function.</p>

<pre><code class="language-javascript">button.addEventListener('click', (event) =&gt; {
  myFunction(event, param1, param2); // Runs on click
});
</code></pre>

<p>The only hiccup with using arrow and anonymous functions is that they cannot be removed with the traditional <code>removeEventListener()</code> method; you will have to make use of <code>AbortController</code>, which may be overkill for simple cases. <code>AbortController</code> shines when you have multiple event listeners to remove at once.</p>

<p>For simple cases where you have just one or two event listeners to remove, the <code>removeEventListener()</code> method still proves useful. However, in order to make use of it, you’ll need to store your function as a reference to the listener.</p>

<h2 id="using-parameters-with-event-handlers">Using Parameters With Event Handlers</h2>

<p>There are several ways to include parameters with event handlers. However, for the purpose of this demonstration, we are going to constrain our focus to the following two:</p>

<h3 id="option-1-arrow-and-anonymous-functions">Option 1: Arrow And Anonymous Functions</h3>

<p>Using arrow and anonymous functions is the fastest and easiest way to get the job done.</p>

<p>To add an event handler with parameters using arrow and anonymous functions, we’ll first need to call the function we’re going to create inside the arrow function attached to the event listener:</p>

<pre><code class="language-javascript">const button = document.querySelector("#myButton");

button.addEventListener("click", (event) =&gt; {
  handleClick(event, "hello", "world");
});
</code></pre>

<p>After that, we can create the function with parameters:</p>

<pre><code class="language-javascript">function handleClick(event, param1, param2) {
  console.log(param1, param2, event.type, event.target);
}
</code></pre>

<p>Note that with this method, removing the event listener requires the <a href="https://developer.mozilla.org/en-US/docs/Web/API/AbortController"><code>AbortController</code></a>. To remove the event listener, we create a new <code>AbortController</code> object and then retrieve the <code>AbortSignal</code> object from it:</p>

<pre><code class="language-javascript">const controller = new AbortController();
const { signal } = controller;
</code></pre>

<p>Next, we can pass the <code>signal</code> from the <code>controller</code> as an option in the <code>removeEventListener()</code> method:</p>

<pre><code class="language-javascript">button.addEventListener("click", (event) =&gt; {
  handleClick(event, "hello", "world");
}, { signal });
</code></pre>

<p>Now we can remove the event listener by calling <code>AbortController.abort()</code>:</p>

<pre><code class="language-javascript">controller.abort()
</code></pre>

<h3 id="option-2-closures">Option 2: Closures</h3>

<p>Closures in JavaScript are another feature that can help us with event handlers. Remember the mistake that produced a type error? That mistake can also be corrected with closures. Specifically, with closures, a function can access variables from its outer scope.</p>

<p>In other words, we can access the parameters we need in the event handler from the outer function:</p>

<div class="break-out">
<pre><code class="language-javascript">function createHandler(message, number) {
  // Event handler
  return function (event) {
  console.log(`${message} ${number} - Clicked element:`, event.target);
    };
  }

  const button = document.querySelector("&#35;myButton");
  button.addEventListener("click", createHandler("Hello, world!", 1));
}
</code></pre>
</div>

<p>This establishes a function that returns another function. The function that is created is then called as the second parameter in the <code>addEventListener()</code> method so that the inner function is returned as the event handler. And with the power of closures, the parameters from the outer function will be made available for use in the inner function.</p>

<p>Notice how the <code>event</code> object is made available to the inner function. This is because the inner function is what is being attached as the event handler. The event object is passed to the function automatically because it’s the event handler.</p>

<p>To remove the event listener, we can use the <code>AbortController</code> like we did before. However, this time, let’s see how we can do that using the <code>removeEventListener()</code> method instead.</p>

<p>In order for the <code>removeEventListener</code> method to work, a reference to the <code>createHandler</code> function needs to be stored and used in the <code>addEventListener</code> method:</p>

<div class="break-out">
<pre><code class="language-javascript">function createHandler(message, number) {
  return function (event) {
    console.log(`${message} ${number} - Clicked element:`, event.target);
  };
}
const handler = createHandler("Hello, world!", 1);
button.addEventListener("click", handler);
</code></pre>
</div>

<p>Now, the event listener can be removed like this:</p>

<pre><code class="language-javascript">button.removeEventListener("click", handler);
</code></pre>

<h2 id="conclusion">Conclusion</h2>

<p>It is good practice to always remove event listeners whenever they are no longer needed to prevent memory leaks. Most times, event handlers do not require parameters; however, in rare cases, they do. Using JavaScript features like closures, <code>AbortController</code>, and <code>removeEventListener</code>, handling parameters with event handlers is both possible and well-supported.</p>

<div class="signature">
  <img src="https://www.smashingmagazine.com/images/logo/logo--red.png" alt="Smashing Editorial" width="35" height="46" loading="lazy" decoding="async" />
  <span>(gg, yk)</span>
</div>


              </article>
            </body>
          </html>
        ]]></content:encoded></item><item><author>Blake Lundquist</author><title>Creating The &amp;ldquo;Moving Highlight&amp;rdquo; Navigation Bar With JavaScript And CSS</title><link>https://www.smashingmagazine.com/2025/06/creating-moving-highlight-navigation-bar-javascript-css/</link><pubDate>Wed, 11 Jun 2025 13:00:00 +0000</pubDate><guid>https://www.smashingmagazine.com/2025/06/creating-moving-highlight-navigation-bar-javascript-css/</guid><description>In this tutorial, Blake Lundquist walks us through two methods of creating the “moving-highlight” navigation pattern using only plain JavaScript and CSS. The first technique uses the &lt;code>getBoundingClientRect&lt;/code> method to explicitly animate the border between navigation bar items when they are clicked. The second approach achieves the same functionality using the new View Transition API.</description><content:encoded><![CDATA[
          <html>
            <head>
              <meta charset="utf-8">
              <link rel="canonical" href="https://www.smashingmagazine.com/2025/06/creating-moving-highlight-navigation-bar-javascript-css/" />
              <title>Creating The &amp;ldquo;Moving Highlight&amp;rdquo; Navigation Bar With JavaScript And CSS</title>
            </head>
            <body>
              <article>
                <header>
                  <h1>Creating The &amp;ldquo;Moving Highlight&amp;rdquo; Navigation Bar With JavaScript And CSS</h1>
                  
                    
                    <address>Blake Lundquist</address>
                  
                  <time datetime="2025-06-11T13:00:00&#43;00:00" class="op-published">2025-06-11T13:00:00+00:00</time>
                  <time datetime="2025-06-11T13:00:00&#43;00:00" class="op-modified">2026-11-13T04:40:45+00:00</time>
                </header>
                
                

<p>I recently came across an old jQuery tutorial demonstrating a <strong>“moving highlight” navigation bar</strong> and decided the concept was due for a modern upgrade. With this pattern, the border around the active navigation item animates directly from one element to another as the user clicks on menu items. In 2025, we have much better tools to manipulate the DOM via vanilla JavaScript. New features like the <a href="https://developer.mozilla.org/en-US/docs/Web/API/View_Transition_API">View Transition API</a> make progressive enhancement more easily achievable and handle a lot of the animation minutiae.</p>

<figure><a href="https://files.smashing.media/articles/creating-moving-highlight-navigation-bar-vanilla-javascript/1-moving-highlight-navigation-bar.gif"><img src="https://files.smashing.media/articles/creating-moving-highlight-navigation-bar-vanilla-javascript/1-moving-highlight-navigation-bar.gif" width="800" height="131" alt="An example of a “moving highlight” navigation bar" /></a><figcaption>(<a href="https://files.smashing.media/articles/creating-moving-highlight-navigation-bar-vanilla-javascript/1-moving-highlight-navigation-bar.gif">Large preview</a>)</figcaption></figure>

<p>In this tutorial, I will demonstrate two methods of creating the “moving highlight” navigation bar using plain JavaScript and CSS. The first example uses the <code>getBoundingClientRect</code> method to explicitly animate the border between navigation bar items when they are clicked. The second example achieves the same functionality using the new View Transition API.</p>

<h2 id="the-initial-markup">The Initial Markup</h2>

<p>Let’s assume that we have a single-page application where content changes without the page being reloaded. The starting HTML and CSS are your standard navigation bar with an additional <code>div</code> element containing an <code>id</code> of <code>#highlight</code>. We give the first navigation item a class of <code>.active</code>.</p>

<figure class="break-out">
	<p data-height="480"
	data-theme-id="light"
	data-slug-hash="EajQyBW"
	data-user="smashingmag"
	data-default-tab="result"
	class="codepen">See the Pen [Moving Highlight Navbar Starting Markup [forked]](https://codepen.io/smashingmag/pen/EajQyBW) by <a href="https://codepen.io/blakeeric">Blake Lundquist</a>.</p>
	<figcaption>See the Pen <a href="https://codepen.io/smashingmag/pen/EajQyBW">Moving Highlight Navbar Starting Markup [forked]</a> by <a href="https://codepen.io/blakeeric">Blake Lundquist</a>.</figcaption>
</figure>

<p>For this version, we will position the <code>#highlight</code> element around the element with the <code>.active</code> class to create a border. We can utilize <code>absolute</code> positioning and animate the element across the navigation bar to create the desired effect. We’ll hide it off-screen initially by adding <code>left: -200px</code> and include <code>transition</code> styles for all properties so that any changes in the position and size of the element will happen gradually.</p>

<pre><code class="language-css">&#35;highlight {
  z-index: 0;
  position: absolute;
  height: 100%;
  width: 100px;
  left: -200px;
  border: 2px solid green;
  box-sizing: border-box;
  transition: all 0.2s ease;
}
</code></pre>

<div data-audience="non-subscriber" data-remove="true" class="feature-panel-container">

<aside class="feature-panel" style="">
<div class="feature-panel-left-col">

<div class="feature-panel-description"><p>Meet <strong><a data-instant href="/printed-books/image-optimization/">Image Optimization</a></strong>, Addy Osmani’s new practical guide to optimizing and delivering <strong>high-quality images</strong> on the web. Everything in one single <strong>528-pages</strong> book.</p>
<a data-instant href="https://www.smashingmagazine.com/printed-books/image-optimization/" class="btn btn--green btn--large" style="">Jump to table of contents&nbsp;↬</a></div>
</div>
<div class="feature-panel-right-col"><a data-instant href="https://www.smashingmagazine.com/printed-books/image-optimization/" class="feature-panel-image-link">
<div class="feature-panel-image"><picture><source type="image/avif" srcSet="https://archive.smashing.media/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/2c669cf1-c6ef-4c87-9901-018b04f7871f/image-optimization-shop-cover-opt.avif" />
<img
    loading="lazy"
    decoding="async"
    class="feature-panel-image-img"
    src="https://archive.smashing.media/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/87fd0cfa-692e-459c-b2f3-15209a1f6aa7/image-optimization-shop-cover-opt.png"
    alt="Feature Panel"
    width="480"
    height="697"
/>
</picture>
</div>
</a>
</div>
</aside>
</div>

<h2 id="add-a-boilerplate-event-handler-for-click-interactions">Add A Boilerplate Event Handler For Click Interactions</h2>

<p>We want the highlight element to animate when a user changes the <code>.active</code> navigation item. Let’s add a <code>click</code> event handler to the <code>nav</code> element, then filter for events caused only by elements matching our desired selector. In this case, we only want to change the <code>.active</code> nav item if the user clicks on a link that does not already have the <code>.active</code> class.</p>

<p>Initially, we can call <code>console.log</code> to ensure the handler fires only when expected:</p>

<div class="break-out">
<pre><code class="language-javascript">const navbar = document.querySelector('nav');

navbar.addEventListener('click', function (event) {
  // return if the clicked element doesn't have the correct selector
  if (!event.target.matches('nav a:not(active)')) {
    return;
  }
  
  console.log('click');
});
</code></pre>
</div>

<p>Open your browser console and try clicking different items in the navigation bar. You should only see <code>&quot;click&quot;</code> being logged when you select a new item in the navigation bar.</p>

<p>Now that we know our event handler is working on the correct elements let’s add code to move the <code>.active</code> class to the navigation item that was clicked. We can use the object passed into the event handler to find the element that initialized the event and give that element a class of <code>.active</code> after removing it from the previously active item.</p>

<div class="break-out">
<pre><code class="language-javascript">const navbar = document.querySelector('nav');

navbar.addEventListener('click', function (event) {
  // return if the clicked element doesn't have the correct selector
  if (!event.target.matches('nav a:not(active)')) {
    return;
  }
  
-  console.log('click');
+  document.querySelector('nav a.active').classList.remove('active');
+  event.target.classList.add('active');
  
});
</code></pre>
</div>

<p>Our <code>#highlight</code> element needs to move across the navigation bar and position itself around the active item. Let’s write a function to calculate a new position and width. Since the <code>#highlight</code> selector has <code>transition</code> styles applied, it will move gradually when its position changes.</p>

<p>Using <code>getBoundingClientRect</code>, we can get information about the position and size of an element. We calculate the width of the active navigation item and its offset from the left boundary of the parent element. Then, we assign styles to the highlight element so that its size and position match.</p>

<div class="break-out">
<pre><code class="language-javascript">// handler for moving the highlight
const moveHighlight = () =&gt; {
  const activeNavItem = document.querySelector('a.active');
  const highlighterElement = document.querySelector('#highlight');
  
  const width = activeNavItem.offsetWidth;

  const itemPos = activeNavItem.getBoundingClientRect();
  const navbarPos = navbar.getBoundingClientRect()
  const relativePosX = itemPos.left - navbarPos.left;

  const styles = {
    left: `${relativePosX}px`,
    width: `${width}px`,
  };

  Object.assign(highlighterElement.style, styles);
}
</code></pre>
</div>

<p>Let’s call our new function when the click event fires:</p>

<div class="break-out">
<pre><code class="language-javascript">navbar.addEventListener('click', function (event) {
  // return if the clicked element doesn't have the correct selector
  if (!event.target.matches('nav a:not(active)')) {
    return;
  }
  
  document.querySelector('nav a.active').classList.remove('active');
  event.target.classList.add('active');
  
+  moveHighlight();
});
</code></pre>
</div>

<p>Finally, let’s also call the function immediately so that the border moves behind our initial active item when the page first loads:</p>

<pre><code class="language-javascript">// handler for moving the highlight
const moveHighlight = () =&gt; {
 // ...
}

// display the highlight when the page loads
moveHighlight();
</code></pre>

<p>Now, the border moves across the navigation bar when a new item is selected. Try clicking the different navigation links to animate the navigation bar.</p>

<figure class="break-out">
	<p data-height="480"
	data-theme-id="light"
	data-slug-hash="WbvMxqV"
	data-user="smashingmag"
	data-default-tab="result"
	class="codepen">See the Pen [Moving Highlight Navbar [forked]](https://codepen.io/smashingmag/pen/WbvMxqV) by <a href="https://codepen.io/blakeeric">Blake Lundquist</a>.</p>
	<figcaption>See the Pen <a href="https://codepen.io/smashingmag/pen/WbvMxqV">Moving Highlight Navbar [forked]</a> by <a href="https://codepen.io/blakeeric">Blake Lundquist</a>.</figcaption>
</figure>

<p>That only took a few lines of vanilla JavaScript and could easily be extended to account for other interactions, like <code>mouseover</code> events. In the next section, we will explore refactoring this feature using the View Transition API.</p>

<div class="partners__lead-place"></div>

<h2 id="using-the-view-transition-api">Using The View Transition API</h2>

<p>The View Transition API provides functionality to create animated transitions between website views. Under the hood, the API creates snapshots of “before” and “after” views and then handles transitioning between them. View transitions are useful for creating animations between documents, providing the <strong>native-app-like user experience</strong> featured in frameworks like <a href="https://docs.astro.build/en/guides/view-transitions/">Astro</a>. However, the API also provides handlers meant for <strong>SPA-style applications</strong>. We will use it to reduce the JavaScript needed in our implementation and more easily create fallback functionality.</p>

<p>For this approach, we no longer need a separate <code>#highlight</code> element. Instead, we can style the <code>.active</code> navigation item directly using pseudo-selectors and let the View Transition API handle the animation between the before-and-after UI states when a new navigation item is clicked.</p>

<p>We’ll start by getting rid of the <code>#highlight</code> element and its associated CSS and replacing it with styles for the <code>nav a::after</code> pseudo-selector:</p>

<pre><code class="language-html">&lt;nav&gt;
  - &lt;div id="highlight"&gt;&lt;/div&gt;
  &lt;a href="#" class="active"&gt;Home&lt;/a&gt;
  &lt;a href="#services"&gt;Services&lt;/a&gt;
  &lt;a href="#about"&gt;About&lt;/a&gt;
  &lt;a href="#contact"&gt;Contact&lt;/a&gt;
&lt;/nav&gt;
</code></pre>

<pre><code class="language-css">- &#35;highlight {
-  z-index: 0;
-  position: absolute;
-  height: 100%;
-  width: 0;
-  left: 0;
-  box-sizing: border-box;
-  transition: all 0.2s ease;
- }

+ nav a::after {
+  content: " ";
+  position: absolute;
+  left: 0;
+  top: 0;
+  width: 100%;
+  height: 100%;
+  border: none;
+  box-sizing: border-box;
+ }
</code></pre>

<p>For the <code>.active</code> class, we include the <code>view-transition-name</code> property, thus unlocking the magic of the View Transition API. Once we trigger the view transition and change the location of the <code>.active</code> navigation item in the DOM, “before” and “after” snapshots will be taken, and the browser will animate the border across the bar. We’ll give our view transition the name of <code>highlight</code>, but we could theoretically give it any name.</p>

<pre><code class="language-css">nav a.active::after {
  border: 2px solid green;
  view-transition-name: highlight;
}
</code></pre>

<p>Once we have a selector that contains a <code>view-transition-name</code> property, the only remaining step is to trigger the transition using the <code>startViewTransition</code> method and pass in a callback function.</p>

<div class="break-out">
<pre><code class="language-javascript">const navbar = document.querySelector('nav');

// Change the active nav item on click
navbar.addEventListener('click', async  function (event) {

  if (!event.target.matches('nav a:not(.active)')) {
    return;
  }
  
  document.startViewTransition(() =&gt; {
    document.querySelector('nav a.active').classList.remove('active');

    event.target.classList.add('active');
  });
});
</code></pre>
</div>

<p>Above is a revised version of the <code>click</code> handler. Instead of doing all the calculations for the size and position of the moving border ourselves, the View Transition API handles all of it for us. We only need to call <code>document.startViewTransition</code> and pass in a callback function to change the item that has the <code>.active</code> class!</p>

<div class="partners__lead-place"></div>

<h2 id="adjusting-the-view-transition">Adjusting The View Transition</h2>

<p>At this point, when clicking on a navigation link, you’ll notice that the transition works, but some strange sizing issues are visible.</p>

<figure><a href="https://files.smashing.media/articles/creating-moving-highlight-navigation-bar-vanilla-javascript/2-view-transition-sizing-issues.gif"><img src="https://files.smashing.media/articles/creating-moving-highlight-navigation-bar-vanilla-javascript/2-view-transition-sizing-issues-800px.gif" width="800" height="163" alt="The view transition with sizing issues" /></a><figcaption>(<a href="https://files.smashing.media/articles/creating-moving-highlight-navigation-bar-vanilla-javascript/2-view-transition-sizing-issues.gif">Large preview</a>)</figcaption></figure>

<p>This sizing inconsistency is caused by aspect ratio changes during the course of the view transition. We won’t go into detail here, but <a href="https://jakearchibald.com/2024/view-transitions-handling-aspect-ratio-changes/">Jake Archibald has a detailed explanation you can read</a> for more information. In short, to ensure the height of the border stays uniform throughout the transition, we need to declare an explicit <code>height</code> for the <code>::view-transition-old</code> and <code>::view-transition-new</code> pseudo-selectors representing a static snapshot of the old and new view, respectively.</p>

<pre><code class="language-css">::view-transition-old(highlight) {
  height: 100%;
}

::view-transition-new(highlight) {
  height: 100%;
}
</code></pre>

<p>Let’s do some final refactoring to tidy up our code by moving the callback to a separate function and adding a fallback for when view transitions aren’t supported:</p>

<div class="break-out">
<pre><code class="language-javascript">const navbar = document.querySelector('nav');

// change the item that has the .active class applied
const setActiveElement = (elem) =&gt; {
  document.querySelector('nav a.active').classList.remove('active');
  elem.classList.add('active');
}

// Start view transition and pass in a callback on click
navbar.addEventListener('click', async  function (event) {
  if (!event.target.matches('nav a:not(.active)')) {
    return;
  }

  // Fallback for browsers that don't support View Transitions:
  if (!document.startViewTransition) {
    setActiveElement(event.target);
    return;
  }
  
  document.startViewTransition(() =&gt; setActiveElement(event.target));
});
</code></pre>
</div>

<p>Here’s our view transition-powered navigation bar! Observe the smooth transition when you click on the different links.</p>

<figure class="break-out">
	<p data-height="480"
	data-theme-id="light"
	data-slug-hash="ogXELKE"
	data-user="smashingmag"
	data-default-tab="result"
	class="codepen">See the Pen [Moving Highlight Navbar with View Transition [forked]](https://codepen.io/smashingmag/pen/ogXELKE) by <a href="https://codepen.io/blakeeric">Blake Lundquist</a>.</p>
	<figcaption>See the Pen <a href="https://codepen.io/smashingmag/pen/ogXELKE">Moving Highlight Navbar with View Transition [forked]</a> by <a href="https://codepen.io/blakeeric">Blake Lundquist</a>.</figcaption>
</figure>

<h2 id="conclusion">Conclusion</h2>

<p>Animations and transitions between website UI states used to require many kilobytes of external libraries, along with verbose, confusing, and error-prone code, but vanilla JavaScript and CSS have since incorporated features to achieve <strong>native-app-like interactions without breaking the bank</strong>. We demonstrated this by implementing the “moving highlight” navigation pattern using two approaches: CSS transitions combined with the <code>getBoundingClientRect()</code> method and the View Transition API.</p>

<h3 id="resources">Resources</h3>

<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect"><code>getBoundingClientRect()</code> method documentation</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/View_Transition_API">View Transition API documentation</a></li>
<li>“<a href="https://jakearchibald.com/2024/view-transitions-handling-aspect-ratio-changes/">View Transitions: Handling Aspect Ratio Changes</a>” by Jake Archibald</li>
</ul>

<div class="signature">
  <img src="https://www.smashingmagazine.com/images/logo/logo--red.png" alt="Smashing Editorial" width="35" height="46" loading="lazy" decoding="async" />
  <span>(gg, yk)</span>
</div>


              </article>
            </body>
          </html>
        ]]></content:encoded></item><item><author>Amejimaobari Ollornwi</author><title>Building An Offline-Friendly Image Upload System</title><link>https://www.smashingmagazine.com/2025/04/building-offline-friendly-image-upload-system/</link><pubDate>Wed, 23 Apr 2025 10:00:00 +0000</pubDate><guid>https://www.smashingmagazine.com/2025/04/building-offline-friendly-image-upload-system/</guid><description>Poor internet connectivity doesn’t have to mean poor UX. With PWA technologies like &lt;code>IndexedDB&lt;/code>, service workers, and the Background Sync API, you can build an offline-friendly image upload system that queues uploads and retries them automatically — so your users can upload stress-free, even when offline.</description><content:encoded><![CDATA[
          <html>
            <head>
              <meta charset="utf-8">
              <link rel="canonical" href="https://www.smashingmagazine.com/2025/04/building-offline-friendly-image-upload-system/" />
              <title>Building An Offline-Friendly Image Upload System</title>
            </head>
            <body>
              <article>
                <header>
                  <h1>Building An Offline-Friendly Image Upload System</h1>
                  
                    
                    <address>Amejimaobari Ollornwi</address>
                  
                  <time datetime="2025-04-23T10:00:00&#43;00:00" class="op-published">2025-04-23T10:00:00+00:00</time>
                  <time datetime="2025-04-23T10:00:00&#43;00:00" class="op-modified">2026-11-13T04:40:45+00:00</time>
                </header>
                
                

<p>So, you’re filling out an online form, and it asks you to upload a file. You click the input, select a file from your desktop, and are good to go. But something happens. The network drops, the file disappears, and you’re stuck having to re-upload the file. <strong>Poor network connectivity</strong> can lead you to spend an unreasonable amount of time trying to upload files successfully.</p>

<p>What ruins the user experience stems from having to constantly check network stability and retry the upload several times. While we may not be able to do much about network connectivity, as developers, we can always do something to ease the pain that comes with this problem.</p>

<p>One of the ways we can solve this problem is by tweaking image upload systems in a way that enables users to upload images offline &mdash; <strong>eliminating the need for a reliable network connection</strong>, and then having the system retry the upload process when the network becomes stable, without the user intervening.</p>

<p>This article is going to focus on explaining how to build <strong>an offline-friendly image upload system</strong> using PWA (progressive web application) technologies such as <code>IndexedDB</code>, service workers, and the Background Sync API. We will also briefly cover tips for improving the user experience for this system.</p>

<h2 id="planning-the-offline-image-upload-system">Planning The Offline Image Upload System</h2>

<p>Here’s a flow chart for an offline-friendly image upload system.</p>














<figure class="
  
    break-out article__image
  
  
  ">
  
    <a href="https://files.smashing.media/articles/building-offline-friendly-image-upload-system/1-upload-system-flow-chart.png">
    
    <img
      loading="lazy"
      decoding="async"
      fetchpriority="low"
			width="800"
			height="678"
			
			srcset="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/building-offline-friendly-image-upload-system/1-upload-system-flow-chart.png 400w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_800/https://files.smashing.media/articles/building-offline-friendly-image-upload-system/1-upload-system-flow-chart.png 800w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1200/https://files.smashing.media/articles/building-offline-friendly-image-upload-system/1-upload-system-flow-chart.png 1200w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1600/https://files.smashing.media/articles/building-offline-friendly-image-upload-system/1-upload-system-flow-chart.png 1600w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_2000/https://files.smashing.media/articles/building-offline-friendly-image-upload-system/1-upload-system-flow-chart.png 2000w"
			src="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/building-offline-friendly-image-upload-system/1-upload-system-flow-chart.png"
			
			sizes="100vw"
			alt="Flow chart of an offline-friendly image upload system"
		/>
    
    </a>
  

  
    <figcaption class="op-vertical-bottom">
      Flow chart of an offline-friendly image upload system (<a href='https://files.smashing.media/articles/building-offline-friendly-image-upload-system/1-upload-system-flow-chart.png'>Large preview</a>)
    </figcaption>
  
</figure>

<p>As shown in the flow chart, the process unfolds as follows:</p>

<ol>
<li><strong>The user selects an image.</strong><br />
The process begins by letting the user select their image.</li>
<li><strong>The image is stored locally in <code>IndexedDB</code>.</strong><br />
Next, the system checks for network connectivity. If network connectivity is available, the system uploads the image directly, avoiding unnecessary local storage usage. However, if the network is not available, the image will be stored in <code>IndexedDB</code>.</li>
<li><strong>The service worker detects when the network is restored.</strong><br />
With the image stored in <code>IndexedDB</code>, the system waits to detect when the network connection is restored to continue with the next step.</li>
<li><strong>The background sync processes pending uploads.</strong><br />
The moment the connection is restored, the system will try to upload the image again.</li>
<li><strong>The file is successfully uploaded</strong>.<br />
The moment the image is uploaded, the system will remove the local copy stored in <code>IndexedDB</code>.

<br /></li>
</ol>

<div data-audience="non-subscriber" data-remove="true" class="feature-panel-container">

<aside class="feature-panel" style="">
<div class="feature-panel-left-col">

<div class="feature-panel-description"><p>Meet <strong><a data-instant href="/printed-books/touch-design-for-mobile-interfaces/">Touch Design for Mobile Interfaces</a></strong>, Steven Hoober’s brand-new guide on <strong>designing for mobile</strong> with proven, universal, human-centric guidelines. <strong>400 pages</strong>, jam-packed with in-depth user research and <strong>best practices</strong>.</p>
<a data-instant href="https://www.smashingmagazine.com/printed-books/touch-design-for-mobile-interfaces/" class="btn btn--green btn--large" style="">Jump to table of contents&nbsp;↬</a></div>
</div>
<div class="feature-panel-right-col"><a data-instant href="https://www.smashingmagazine.com/printed-books/touch-design-for-mobile-interfaces/" class="feature-panel-image-link">
<div class="feature-panel-image"><picture><source type="image/avif" srcSet="https://archive.smashing.media/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/14bcab88-b622-47f6-a51d-76b0aa003597/touch-design-book-shop-opt.avif" />
<img
    loading="lazy"
    decoding="async"
    class="feature-panel-image-img"
    src="https://archive.smashing.media/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/b14658fc-bb2d-41a6-8d1a-70eaaf1b8ec8/touch-design-book-shop-opt.png"
    alt="Feature Panel"
    width="480"
    height="697"
/>
</picture>
</div>
</a>
</div>
</aside>
</div>

<h2 id="implementing-the-system">Implementing The System</h2>

<p>The first step in the system implementation is allowing the user to select their images. There are different ways you can achieve this:</p>

<ul>
<li>You can use a simple <code>&lt;input type=&quot;file&quot;&gt;</code> element;</li>
<li>A drag-and-drop interface.</li>
</ul>

<p>I would advise that you use both. Some users prefer to use the drag-and-drop interface, while others think the only way to upload images is through the <code>&lt;input type=&quot;file&quot;&gt;</code> element. Having both options will help improve the user experience. You can also consider allowing users to paste images directly in the browser using the Clipboard API.</p>

<h3 id="registering-the-service-worker">Registering The Service Worker</h3>

<p>At the heart of this solution is the <a href="https://www.smashingmagazine.com/2016/02/making-a-service-worker/">service worker</a>. Our service worker is going to be responsible for retrieving the image from the <code>IndexedDB</code> store, uploading it when the internet connection is restored, and clearing the <code>IndexedDB</code> store when the image has been uploaded.</p>

<p>To use a service worker, you first have to register one:</p>

<div class="break-out">
<pre><code class="language-javascript">if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/service-worker.js')
    .then(reg =&gt; console.log('Service Worker registered', reg))
    .catch(err =&gt; console.error('Service Worker registration failed', err));
}
</code></pre>
</div>

<h3 id="checking-for-network-connectivity">Checking For Network Connectivity</h3>

<p>Remember, the problem we are trying to solve is caused by <strong>unreliable network connectivity</strong>. If this problem does not exist, there is no point in trying to solve anything. Therefore, once the image is selected, we need to check if the user has a reliable internet connection before registering a sync event and storing the image in <code>IndexedDB</code>.</p>

<pre><code class="language-javascript">function uploadImage() {
  if (navigator.onLine) {
    // Upload Image
  } else {
    // register Sync Event
    // Store Images in IndexedDB
  }
}
</code></pre>

<p><strong>Note</strong>: I’m only using the <code>navigator.onLine</code> property here to demonstrate how the system would work. The <code>navigator.onLine</code> property is <strong>unreliable</strong>, and I would suggest you come up with a custom solution to check whether the user is connected to the internet or not. One way you can do this is by sending a ping request to a server endpoint you’ve created.</p>

<h3 id="registering-the-sync-event">Registering The Sync Event</h3>

<p>Once the network test fails, the next step is to register a sync event. The sync event needs to be registered at the point where the system fails to upload the image due to a poor internet connection.</p>

<pre><code class="language-javascript">async function registerSyncEvent() {
  if ('SyncManager' in window) {
    const registration = await navigator.serviceWorker.ready;
    await registration.sync.register('uploadImages');
    console.log('Background Sync registered');
  }
}
</code></pre>

<p>After registering the sync event, you need to listen for it in the service worker.</p>

<pre><code class="language-javascript">self.addEventListener('sync', (event) =&gt; {
  if (event.tag === 'uploadImages') {
    event.waitUntil(sendImages());
  }
});
</code></pre>

<p>The <code>sendImages</code> function is going to be an asynchronous process that will retrieve the image from <code>IndexedDB</code> and upload it to the server. This is what it’s going to look like:</p>

<pre><code class="language-javascript">async function sendImages() {
  try {
    // await image retrieval and upload
  } catch (error) {
    // throw error
  }
}
</code></pre>

<h3 id="opening-the-database">Opening The Database</h3>

<p>The first thing we need to do in order to store our image locally is to open an <code>IndexedDB</code> store. As you can see from the code below, we are creating <strong>a global variable to store the database instance</strong>. The reason for doing this is that, subsequently, when we want to retrieve our image from <code>IndexedDB</code>, we wouldn’t need to write the code to open the database again.</p>

<div class="break-out">
<pre><code class="language-javascript">let database; // Global variable to store the database instance

function openDatabase() {
  return new Promise((resolve, reject) =&gt; {
    if (database) return resolve(database); // Return existing database instance 

    const request = indexedDB.open("myDatabase", 1);

    request.onerror = (event) =&gt; {
      console.error("Database error:", event.target.error);
      reject(event.target.error); // Reject the promise on error
    };

    request.onupgradeneeded = (event) =&gt; {
        const db = event.target.result;
        // Create the "images" object store if it doesn't exist.
        if (!db.objectStoreNames.contains("images")) {
          db.createObjectStore("images", { keyPath: "id" });
        }
        console.log("Database setup complete.");
    };

    request.onsuccess = (event) =&gt; {
      database = event.target.result; // Store the database instance globally
      resolve(database); // Resolve the promise with the database instance
    };
  });
}
</code></pre>
</div>

<div class="partners__lead-place"></div>

<h3 id="storing-the-image-in-indexeddb">Storing The Image In IndexedDB</h3>

<p>With the <code>IndexedDB</code> store open, we can now store our images.</p>

<blockquote>Now, you may be wondering why an easier solution like <code>localStorage</code> wasn’t used for this purpose.<br /><br />The reason for that is that <code>IndexedDB</code> operates asynchronously and doesn’t block the main JavaScript thread, whereas <code>localStorage</code> runs synchronously and can block the JavaScript main thread if it is being used.</blockquote>

<p>Here’s how you can store the image in <code>IndexedDB</code>:</p>

<div class="break-out">
<pre><code class="language-javascript">async function storeImages(file) {
  // Open the IndexedDB database.
  const db = await openDatabase();
  // Create a transaction with read and write access.
  const transaction = db.transaction("images", "readwrite");
  // Access the "images" object store.
  const store = transaction.objectStore("images");
  // Define the image record to be stored.
  const imageRecord = {
    id: IMAGE&#95;ID,   // a unique ID
    image: file     // Store the image file (Blob)
  };
  // Add the image record to the store.
  const addRequest = store.add(imageRecord);
  // Handle successful addition.
  addRequest.onsuccess = () =&gt; console.log("Image added successfully!");
  // Handle errors during insertion.
  addRequest.onerror = (e) =&gt; console.error("Error storing image:", e.target.error);
}
</code></pre>
</div>

<p>With the images stored and the background sync set, the system is ready to upload the image whenever the network connection is restored.</p>

<h3 id="retrieving-and-uploading-the-images">Retrieving And Uploading The Images</h3>

<p>Once the network connection is restored, the sync event will fire, and the service worker will retrieve the image from <code>IndexedDB</code> and upload it.</p>

<div class="break-out">
<pre><code class="language-javascript">async function retrieveAndUploadImage(IMAGE&#95;ID) {
  try {
    const db = await openDatabase(); // Ensure the database is open
    const transaction = db.transaction("images", "readonly");
    const store = transaction.objectStore("images");
    const request = store.get(IMAGE&#95;ID);
    request.onsuccess = function (event) {
      const image = event.target.result;
      if (image) {
        // upload Image to server here
      } else {
        console.log("No image found with ID:", IMAGE&#95;ID);
      }
    };
    request.onerror = () =&gt; {
        console.error("Error retrieving image.");
    };
  } catch (error) {
    console.error("Failed to open database:", error);
  }
}
</code></pre>
</div>

<h3 id="deleting-the-indexeddb-database">Deleting The IndexedDB Database</h3>

<p>Once the image has been uploaded, the <code>IndexedDB</code> store is no longer needed. Therefore, it should be deleted along with its content to free up storage.</p>

<div class="break-out">
<pre><code class="language-javascript">function deleteDatabase() {
  // Check if there's an open connection to the database.
  if (database) {
    database.close(); // Close the database connection
    console.log("Database connection closed.");
  }

  // Request to delete the database named "myDatabase".
  const deleteRequest = indexedDB.deleteDatabase("myDatabase");

  // Handle successful deletion of the database.
  deleteRequest.onsuccess = function () {
    console.log("Database deleted successfully!");
  };

  // Handle errors that occur during the deletion process.
  deleteRequest.onerror = function (event) {
    console.error("Error deleting database:", event.target.error);
  };

  // Handle cases where the deletion is blocked (e.g., if there are still open connections).
  deleteRequest.onblocked = function () {
    console.warn("Database deletion blocked. Close open connections and try again.");
  };
}
</code></pre>
</div>
    

<p>With that, the entire process is complete!</p>

<div class="partners__lead-place"></div>

<h2 id="considerations-and-limitations">Considerations And Limitations</h2>

<p>While we’ve done a lot to help improve the experience by supporting offline uploads, the system is not without its limitations. I figured I would specifically call those out because it’s worth knowing where this solution might fall short of your needs.</p>

<ul>
<li><strong>No Reliable Internet Connectivity Detection</strong><br />
JavaScript does not provide a foolproof way to detect online status. For this reason, you need to come up with a custom solution for detecting online status.</li>
<li><strong>Chromium-Only Solution</strong><br />
The Background Sync API is currently <a href="https://developer.mozilla.org/en-US/docs/Web/API/Background_Synchronization_API#browser_compatibility">limited to Chromium-based browsers</a>. As such, this solution is only supported by Chromium browsers. That means you will need a more robust solution if you have the majority of your users on non-Chromium browsers.</li>
<li><strong><code>IndexedDB</code> Storage Policies</strong><br />
Browsers impose storage limitations and eviction policies for <code>IndexedDB</code>. For instance, in Safari, data stored in <code>IndexedDB</code> has a lifespan of seven days if the user doesn’t interact with the website. This is something you should bear in mind if you do come up with an alternative for the background sync API that supports Safari.</li>
</ul>

<h2 id="enhancing-the-user-experience">Enhancing The User Experience</h2>

<p>Since the entire process happens in the background, we need a way to inform the users when images are stored, waiting to be uploaded, or have been successfully uploaded. Implementing certain <strong>UI elements</strong> for this purpose will indeed enhance the experience for the users. These UI elements may include toast notifications, upload status indicators like spinners (to show active processes), progress bars (to show state progress), network status indicators, or buttons to provide retry and cancel options.</p>

<h2 id="wrapping-up">Wrapping Up</h2>

<p>Poor internet connectivity can disrupt the user experience of a web application. However, by leveraging PWA technologies such as <code>IndexedDB</code>, service workers, and the Background Sync API, developers can help improve the reliability of web applications for their users, especially those in areas with unreliable internet connectivity.</p>

<div class="signature">
  <img src="https://www.smashingmagazine.com/images/logo/logo--red.png" alt="Smashing Editorial" width="35" height="46" loading="lazy" decoding="async" />
  <span>(gg, yk)</span>
</div>


              </article>
            </body>
          </html>
        ]]></content:encoded></item><item><author>Amejimaobari Ollornwi</author><title>Creating An Effective Multistep Form For Better User Experience</title><link>https://www.smashingmagazine.com/2024/12/creating-effective-multistep-form-better-user-experience/</link><pubDate>Tue, 03 Dec 2024 10:00:00 +0000</pubDate><guid>https://www.smashingmagazine.com/2024/12/creating-effective-multistep-form-better-user-experience/</guid><description>Forms are already notoriously tough to customize and style &amp;mdash; to the extent that we’re already starting to see new ideas for more flexible control. But what we don’t often discuss is designing good-form experiences beyond validation. That’s what Jima Victor discusses in this article, focusing specifically on creating multi-step forms that involve navigation between sections.</description><content:encoded><![CDATA[
          <html>
            <head>
              <meta charset="utf-8">
              <link rel="canonical" href="https://www.smashingmagazine.com/2024/12/creating-effective-multistep-form-better-user-experience/" />
              <title>Creating An Effective Multistep Form For Better User Experience</title>
            </head>
            <body>
              <article>
                <header>
                  <h1>Creating An Effective Multistep Form For Better User Experience</h1>
                  
                    
                    <address>Amejimaobari Ollornwi</address>
                  
                  <time datetime="2024-12-03T10:00:00&#43;00:00" class="op-published">2024-12-03T10:00:00+00:00</time>
                  <time datetime="2024-12-03T10:00:00&#43;00:00" class="op-modified">2026-11-13T04:40:45+00:00</time>
                </header>
                
                

<p>For a multistep form, planning involves structuring questions logically across steps, grouping similar questions, and minimizing the number of steps and the amount of required information for each step. Whatever makes each step focused and manageable is what should be aimed for.</p>

<p>In this tutorial, we will create a multistep form for a job application. Here are the details we are going to be requesting from the applicant at each step:</p>

<ul>
<li><strong>Personal Information</strong><br />
Collects applicant’s name, email, and phone number.</li>
<li><strong>Work Experience</strong><br />
Collects the applicant’s most recent company, job title, and years of experience.</li>
<li><strong>Skills &amp; Qualifications</strong><br />
The applicant lists their skills and selects their highest degree.</li>
<li><strong>Review &amp; Submit</strong><br />
This step is not going to collect any information. Instead, it provides an opportunity for the applicant to go back and review the information entered in the previous steps of the form before submitting it.</li>
</ul>

<p>You can think of structuring these questions as a digital way of getting to know somebody. You can’t meet someone for the first time and ask them about their work experience without first asking for their name.</p>

<p>Based on the steps we have above, this is what the body of our HTML with our form should look like. First, the main <code>&lt;form&gt;</code> element:</p>

<pre><code class="language-html">&lt;form id="jobApplicationForm"&gt;
  &lt;!-- Step 1: Personal Information --&gt;
  &lt;!-- Step 2: Work Experience --&gt;
  &lt;!-- Step 3: Skills & Qualifications --&gt;
  &lt;!-- Step 4: Review & Submit --&gt;
&lt;/form&gt;
</code></pre>

<p><strong>Step 1</strong> is for filling in personal information, like the applicant’s name, email address, and phone number:</p>

<div class="break-out">
<pre><code class="language-javascript">&lt;form id="jobApplicationForm"&gt;
  &lt;!-- Step 1: Personal Information --&gt;
  &lt;fieldset class="step" id="step-1"&gt;
    &lt;legend id="step1Label"&gt;Step 1: Personal Information&lt;/legend&gt;
    &lt;label for="name"&gt;Full Name&lt;/label&gt;
    &lt;input type="text" id="name" name="name" required /&gt;
    &lt;label for="email"&gt;Email Address&lt;/label&gt;
    &lt;input type="email" id="email" name="email" required /&gt;
    &lt;label for="phone"&gt;Phone Number&lt;/label&gt;
    &lt;input type="tel" id="phone" name="phone" required /&gt;
  &lt;/fieldset&gt;

  &lt;!-- Step 2: Work Experience --&gt;
  &lt;!-- Step 3: Skills & Qualifications --&gt;
  &lt;!-- Step 4: Review & Submit --&gt;
&lt;/form&gt;
</code></pre>
</div>

<p>Once the applicant completes the first step, we’ll navigate them to <strong>Step 2</strong>, focusing on their work experience so that we can collect information like their most recent company, job title, and years of experience. We’ll tack on a new <code>&lt;fieldset&gt;</code> with those inputs:</p>

<div class="break-out">
<pre><code class="language-javascript">&lt;form id="jobApplicationForm"&gt;
  &lt;!-- Step 1: Personal Information --&gt;

  &lt;!-- Step 2: Work Experience --&gt;
  &lt;fieldset class="step" id="step-2" hidden&gt;
    &lt;legend id="step2Label"&gt;Step 2: Work Experience&lt;/legend&gt;
    &lt;label for="company"&gt;Most Recent Company&lt;/label&gt;
    &lt;input type="text" id="company" name="company" required /&gt;
    &lt;label for="jobTitle"&gt;Job Title&lt;/label&gt;
    &lt;input type="text" id="jobTitle" name="jobTitle" required /&gt;
    &lt;label for="yearsExperience"&gt;Years of Experience&lt;/label&gt;
    &lt;input
      type="number"
      id="yearsExperience"
      name="yearsExperience"
      min="0"
      required
    /&gt;
  &lt;/fieldset&gt;

  &lt;!-- Step 3: Skills & Qualifications --&gt;
  &lt;!-- Step 4: Review & Submit --&gt;
&lt;/form&gt;
</code></pre>
</div>

<p><strong>Step 3</strong> is all about the applicant listing their skills and qualifications for the job they’re applying for:</p>

<div class="break-out">
<pre><code class="language-javascript">&lt;form id="jobApplicationForm"&gt;
  &lt;!-- Step 1: Personal Information --&gt;
  &lt;!-- Step 2: Work Experience --&gt;

  &lt;!-- Step 3: Skills & Qualifications --&gt;
  &lt;fieldset class="step" id="step-3" hidden&gt;
    &lt;legend id="step3Label"&gt;Step 3: Skills & Qualifications&lt;/legend&gt;
    &lt;label for="skills"&gt;Skill(s)&lt;/label&gt;
    &lt;textarea id="skills" name="skills" rows="4" required&gt;&lt;/textarea&gt;
    &lt;label for="highestDegree"&gt;Degree Obtained (Highest)&lt;/label&gt;
    &lt;select id="highestDegree" name="highestDegree" required&gt;
      &lt;option value=""&gt;Select Degree&lt;/option&gt;
      &lt;option value="highschool"&gt;High School Diploma&lt;/option&gt;
      &lt;option value="bachelor"&gt;Bachelor's Degree&lt;/option&gt;
      &lt;option value="master"&gt;Master's Degree&lt;/option&gt;
      &lt;option value="phd"&gt;Ph.D.&lt;/option&gt;
    &lt;/select&gt;
  &lt;/fieldset&gt;
  &lt;!-- Step 4: Review & Submit --&gt;
  &lt;fieldset class="step" id="step-4" hidden&gt;
    &lt;legend id="step4Label"&gt;Step 4: Review & Submit&lt;/legend&gt;
    &lt;p&gt;Review your information before submitting the application.&lt;/p&gt;
    &lt;button type="submit"&gt;Submit Application&lt;/button&gt;
  &lt;/fieldset&gt;
&lt;/form&gt;
</code></pre>
</div>

<p>And, finally, we’ll allow the applicant to review their information before submitting it:</p>

<div class="break-out">
<pre><code class="language-javascript">&lt;form id="jobApplicationForm"&gt;
  &lt;!-- Step 1: Personal Information --&gt;
  &lt;!-- Step 2: Work Experience --&gt;
  &lt;!-- Step 3: Skills & Qualifications --&gt;

  &lt;!-- Step 4: Review & Submit --&gt;
  &lt;fieldset class="step" id="step-4" hidden&gt;
    &lt;legend id="step4Label"&gt;Step 4: Review & Submit&lt;/legend&gt;
    &lt;p&gt;Review your information before submitting the application.&lt;/p&gt;
    &lt;button type="submit"&gt;Submit Application&lt;/button&gt;
  &lt;/fieldset&gt;
&lt;/form&gt;
</code></pre>
</div>

<p><strong>Notice</strong>: We’ve added a <code>hidden</code> attribute to every <code>fieldset</code> element but the first one. This ensures that the user sees only the first step. Once they are done with the first step, they can proceed to fill out their work experience on the second step by clicking a navigational button. We’ll add this button later on.</p>

<div data-audience="non-subscriber" data-remove="true" class="feature-panel-container">

<aside class="feature-panel" style="">
<div class="feature-panel-left-col">

<div class="feature-panel-description"><p>Meet <strong><a data-instant href="https://www.smashingconf.com/online-workshops/">Smashing Workshops</a></strong> on <strong>front-end, design &amp; UX</strong>, with practical takeaways, live sessions, <strong>video recordings</strong> and a friendly Q&amp;A. With Brad Frost, Stéph Walter and <a href="https://smashingconf.com/online-workshops/workshops">so many others</a>.</p>
<a data-instant href="smashing-workshops" class="btn btn--green btn--large" style="">Jump to the workshops&nbsp;↬</a></div>
</div>
<div class="feature-panel-right-col"><a data-instant href="smashing-workshops" class="feature-panel-image-link">
<div class="feature-panel-image">
<img
    loading="lazy"
    decoding="async"
    class="feature-panel-image-img"
    src="/images/smashing-cat/cat-scubadiving-panel.svg"
    alt="Feature Panel"
    width="257"
    height="355"
/>

</div>
</a>
</div>
</aside>
</div>

<h2 id="adding-styles">Adding Styles</h2>

<p>To keep things focused, we’re not going to be emphasizing the styles in this tutorial. What we’ll do to keep things simple is leverage the <a href="https://simplecss.org">Simple.css style framework</a> to get the form in good shape for the rest of the tutorial.</p>

<p>If you’re following along, we can include Simple’s styles in the document <code>&lt;head&gt;</code>:</p>

<div class="break-out">
<pre><code class="language-javascript">&lt;link rel="stylesheet" href="https://cdn.simplecss.org/simple.min.css" /&gt;
</code></pre>
</div>

<p>And from there, go ahead and create a <code>style.css</code> file with the following styles that I’ve folded up.</p>

<pre><code class="language-css">&lt;details&gt;
  &lt;summary&gt;View CSS&lt;/summary&gt;
  body {
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  main {
    padding: 0 30px;
  }
  h1 {
    font-size: 1.8rem;
    text-align: center;
  }
  .stepper {
    display: flex;
    justify-content: flex-end;
    padding-right: 10px;
  }
  form {
    box-shadow: 0px 0px 6px 2px rgba(0, 0, 0, 0.2);
    padding: 12px;
  }
  input,
  textarea,
  select {
    outline: none;
  }
  input:valid,
  textarea:valid,
  select:valid,
  input:focus:valid,
  textarea:focus:valid,
  select:focus:valid {
    border-color: green;
  }
  input:focus:invalid,
  textarea:focus:invalid,
  select:focus:invalid {
    border: 1px solid red;
  }
&lt;/details&gt;
</code></pre>

<h2 id="form-navigation-and-validation">Form Navigation And Validation</h2>

<p>An easy way to ruin the user experience for a multi-step form is to wait until the user gets to the last step in the form before letting them know of any error they made along the way. Each step of the form should be validated for errors before moving on to the next step, and descriptive error messages should be displayed to enable users to understand what is wrong and how to fix it.</p>

<p>Now, the only part of our form that is visible is the first step. To complete the form, users need to be able to navigate to the other steps. We are going to use several buttons to pull this off. The first step is going to have a <kbd>Next</kbd> button. The second and third steps are going to have both a <kbd>Previous</kbd> and a <kbd>Next</kbd> button, and the fourth step is going to have a <kbd>Previous</kbd> and a <kbd>Submit</kbd> button.</p>

<div class="break-out">
<pre><code class="language-html">&lt;form id="jobApplicationForm"&gt;
  &lt;!-- Step 1: Personal Information --&gt;
  &lt;fieldset&gt;
    &lt;!-- ... --&gt;
    &lt;button type="button" class="next" onclick="nextStep()"&gt;Next&lt;/button&gt;
  &lt;/fieldset&gt;

  &lt;!-- Step 2: Work Experience --&gt;
  &lt;fieldset&gt;
    &lt;!-- ... --&gt;
    &lt;button type="button" class="previous" onclick="previousStep()"&gt;Previous&lt;/button&gt;
    &lt;button type="button" class="next" onclick="nextStep()"&gt;Next&lt;/button&gt;
  &lt;/fieldset&gt;

  &lt;!-- Step 3: Skills & Qualifications --&gt;
  &lt;fieldset&gt;
    &lt;!-- ... --&gt;
    &lt;button type="button" class="previous" onclick="previousStep()"&gt;Previous&lt;/button&gt;
    &lt;button type="button" class="next" onclick="nextStep()"&gt;Next&lt;/button&gt;
  &lt;/fieldset&gt;

  &lt;!-- Step 4: Review & Submit --&gt;
  &lt;fieldset&gt;
    &lt;!-- ... --&gt;
    &lt;button type="button" class="previous" onclick="previousStep()"&gt;Previous&lt;/button&gt;
    &lt;button type="submit"&gt;Submit Application&lt;/button&gt;
  &lt;/fieldset&gt;
&lt;/form&gt;
</code></pre>
</div>

<p><strong>Notice</strong>: We’ve added <code>onclick</code> attributes to the <kbd>Previous</kbd> and <kbd>Next</kbd> buttons to link them to their respective JavaScript functions: <code>previousStep()</code> and <code>nextStep()</code>.</p>

<div class="partners__lead-place"></div>

<h3 id="the-next-button">The “Next” Button</h3>

<p>The <code>nextStep()</code> function is linked to the Next button. Whenever the user clicks the Next button, the <code>nextStep()</code> function will first check to ensure that all the fields for whatever step the user is on have been filled out correctly before moving on to the next step. If the fields haven’t been filled correctly, it displays some error messages, letting the user know that they’ve done something wrong and informing them what to do to make the errors go away.</p>

<p>Before we go into the implementation of the <code>nextStep</code> function, there are certain variables we need to define because they will be needed in the function. First, we need the input fields from the DOM so we can run checks on them to make sure they are valid.</p>

<div class="break-out">
<pre><code class="language-javascript">// Step 1 fields
const name = document.getElementById("name");
const email = document.getElementById("email");
const phone = document.getElementById("phone");

// Step 2 fields
const company = document.getElementById("company");
const jobTitle = document.getElementById("jobTitle");
const yearsExperience = document.getElementById("yearsExperience");

// Step 3 fields
const skills = document.getElementById("skills");
const highestDegree = document.getElementById("highestDegree");
</code></pre>
</div>

<p>Then, we’re going to need an array to store our error messages.</p>

<pre><code class="language-javascript">let errorMsgs = [];
</code></pre>

<p>Also, we would need an element in the DOM where we can insert those error messages after they’ve been generated. This element should be placed in the HTML just below the last <code>fieldset</code> closing tag:</p>

<pre><code class="language-html">&lt;div id="errorMessages" style="color: rgb(253, 67, 67)"&gt;&lt;/div&gt;
</code></pre>

<p>Add the above <code>div</code> to the JavaScript code using the following line:</p>

<pre><code class="language-javascript">const errorMessagesDiv = document.getElementById("errorMessages");
</code></pre>

<p>And finally, we need a variable to keep track of the current step.</p>

<p><code class="language-javascript">let currentStep = 1;
</code></pre></p>

<p>Now that we have all our variables in place, here’s the implementation of the <code>nextstep()</code> function:</p>

<div class="break-out">
<pre><code class="language-javascript">function nextStep() {
  errorMsgs = [];
  errorMessagesDiv.innerText = "";

  switch (currentStep) {
    case 1:
      addValidationErrors(name, email, phone);
      validateStep(errorMsgs);
      break;

    case 2:
      addValidationErrors(company, jobTitle, yearsExperience);
      validateStep(errorMsgs);
      break;

    case 3:
      addValidationErrors(skills, highestDegree);
      validateStep(errorMsgs);
      break;
  }
}
</code></pre>
</div>

<p>The moment the <kbd>Next</kbd> button is pressed, our code first checks which step the user is currently on, and based on this information, it validates the data for that specific step by calling the <code>addValidationErrors()</code> function. If there are errors, we display them. Then, the form calls the <code>validateStep()</code> function to verify that there are no errors before moving on to the next step. If there are errors, it prevents the user from going on to the next step.</p>

<p>Whenever the <code>nextStep()</code> function runs, the error messages are cleared first to avoid appending errors from a different step to existing errors or re-adding existing error messages when the <code>addValidationErrors</code> function runs. The <code>addValidationErrors</code> function is called for each step using the fields for that step as arguments.</p>

<p>Here’s how the <code>addValidationErrors</code> function is implemented:</p>

<div class="break-out">
<pre><code class="language-javascript">function addValidationErrors(fieldOne, fieldTwo, fieldThree = undefined) {
  if (!fieldOne.checkValidity()) {
    const label = document.querySelector(`label[for="${fieldOne.id}"]`);
    errorMsgs.push(`Please Enter A Valid ${label.textContent}`);
  }

  if (!fieldTwo.checkValidity()) {
    const label = document.querySelector(`label[for="${fieldTwo.id}"]`);
    errorMsgs.push(`Please Enter A Valid ${label.textContent}`);
  }

  if (fieldThree && !fieldThree.checkValidity()) {
    const label = document.querySelector(`label[for="${fieldThree.id}"]`);
    errorMsgs.push(`Please Enter A Valid ${label.textContent}`);
  }

  if (errorMsgs.length &gt; 0) {
    errorMessagesDiv.innerText = errorMsgs.join("\n");
  }
}
</code></pre>
</div>

<p>This is how the <code>validateStep()</code> function is defined:</p>

<pre><code class="language-javascript">function validateStep(errorMsgs) {
  if (errorMsgs.length === 0) {
    showStep(currentStep + 1);
  }
}
</code></pre>

<p>The <code>validateStep()</code> function checks for errors. If there are none, it proceeds to the next step with the help of the <code>showStep()</code> function.</p>

<pre><code class="language-javascript">function showStep(step) {
  steps.forEach((el, index) =&gt; {
    el.hidden = index + 1 !== step;
  });
  currentStep = step;
}
</code></pre>

<p>The <code>showStep()</code> function requires the four fieldsets in the DOM. Add the following line to the top of the JavaScript code to make the fieldsets available:</p>

<pre><code class="language-javascript">const steps = document.querySelectorAll(".step");
</code></pre>

<p>What the <code>showStep()</code> function does is to go through all the <code>fieldsets</code> in our form and hide whatever <code>fieldset</code> is not equal to the one we’re navigating to. Then, it updates the <code>currentStep</code> variable to be equal to the step we’re navigating to.</p>

<h3 id="the-previous-button">The “Previous” Button</h3>

<p>The <code>previousStep()</code> function is linked to the <kbd>Previous</kbd> button. Whenever the previous button is clicked, similarly to the <code>nextStep</code> function, the error messages are also cleared from the page, and navigation is also handled by the <code>showStep</code> function.</p>

<pre><code class="language-javascript">function previousStep() {
  errorMessagesDiv.innerText = "";
  showStep(currentStep - 1);
}
</code></pre>

<p>Whenever the <code>showStep()</code> function is called with “<code>currentStep - 1</code>” as an argument (as in this case), we go back to the previous step, while moving to the next step happens by calling the <code>showStep()</code> function with “<code>currentStep + 1</code>&rdquo; as an argument (as in the case of the <code>validateStep()</code> function).</p>

<div class="partners__lead-place"></div>

<h2 id="improving-user-experience-with-visual-cues">Improving User Experience With Visual Cues</h2>

<p>One other way of improving the user experience for a multi-step form, is by integrating visual cues, things that will give users feedback on the process they are on. These things can include a progress indicator or a stepper to help the user know the exact step they are on.</p>

<h3 id="integrating-a-stepper">Integrating A Stepper</h3>

<p>To integrate a stepper into our form (sort of like <a href="https://m1.material.io/components/steppers.html#">this one</a> from Material Design), the first thing we need to do is add it to the HTML just below the opening <code>&lt;form&gt;</code> tag.</p>

<pre><code class="language-html">&lt;form id="jobApplicationForm"&gt;
  &lt;div class="stepper"&gt;
    &lt;span&gt;&lt;span class="currentStep"&gt;1&lt;/span&gt;/4&lt;/span&gt;
  &lt;/div&gt;
  &lt;!-- ... --&gt;
&lt;/form&gt;
</code></pre>

<p>Next, we need to query the part of the stepper that will represent the current step. This is the span tag with the class name of <code>currentStep</code>.</p>

<pre><code class="language-javascript">const currentStepDiv = document.querySelector(".currentStep");
</code></pre>

<p>Now, we need to update the stepper value whenever the previous or next buttons are clicked. To do this, we need to update the <code>showStep()</code> function by appending the following line to it:</p>

<pre><code class="language-javascript">currentStepDiv.innerText = currentStep;
</code></pre>

<p>This line is added to the <code>showStep()</code> function because the <code>showStep()</code> function is responsible for navigating between steps and updating the <code>currentStep</code> variable. So, whenever the <code>currentStep</code> variable is updated, the currentStepDiv should also be updated to reflect that change.</p>

<h3 id="storing-and-retrieving-user-data">Storing And Retrieving User Data</h3>

<p>One major way we can improve the form’s user experience is by storing user data in the browser. Multistep forms are usually long and require users to enter a lot of information about themselves. Imagine a user filling out 95% of a form, then accidentally hitting the <kbd>F5</kbd> button on their keyboard and losing all their progress. That would be a really bad experience for the user.</p>

<p>Using <code>localStorage</code>, we can store user information as soon as it is entered and retrieve it as soon as the DOM content is loaded, so users can always continue filling out their forms from wherever they left off. To add this feature to our forms, we can begin by saving the user’s information as soon as it is typed. This can be achieved using the <code>input</code> event.</p>

<p>Before adding the <code>input</code> event listener, get the form element from the DOM:</p>

<pre><code class="language-javascript">const form = document.getElementById("jobApplicationForm");
</code></pre>

<p>Now we can add the <code>input</code> event listener:</p>

<div class="break-out">
<pre><code class="language-javascript">// Save data on each input event
form.addEventListener("input", () =&gt; {
  const formData = {
    name: document.getElementById("name").value,
    email: document.getElementById("email").value,
    phone: document.getElementById("phone").value,
    company: document.getElementById("company").value,
    jobTitle: document.getElementById("jobTitle").value,
    yearsExperience: document.getElementById("yearsExperience").value,
    skills: document.getElementById("skills").value,
    highestDegree: document.getElementById("highestDegree").value,
  };
  localStorage.setItem("formData", JSON.stringify(formData));
});
</code></pre>
</div>

<p>Next, we need to add some code to help us retrieve the user data once the DOM content is loaded.</p>

<div class="break-out">
<pre><code class="language-javascript">window.addEventListener("DOMContentLoaded", () =&gt; {
  const savedData = JSON.parse(localStorage.getItem("formData"));
  if (savedData) {
    document.getElementById("name").value = savedData.name || "";
    document.getElementById("email").value = savedData.email || "";
    document.getElementById("phone").value = savedData.phone || "";
    document.getElementById("company").value = savedData.company || "";
    document.getElementById("jobTitle").value = savedData.jobTitle || "";
    document.getElementById("yearsExperience").value = savedData.yearsExperience || "";
    document.getElementById("skills").value = savedData.skills || "";
    document.getElementById("highestDegree").value = savedData.highestDegree || "";
  }
});
</code></pre>
</div>

<p>Lastly, it is good practice to remove data from <code>localStorage</code> as soon as it is no longer needed:</p>

<pre><code class="language-javascript">// Clear data on form submit
form.addEventListener('submit', () =&gt; {
  // Clear localStorage once the form is submitted
  localStorage.removeItem('formData');
}); 
</code></pre>

<h3 id="adding-the-current-step-value-to-localstorage">Adding The Current Step Value To <code>localStorage</code></h3>

<p>If the user accidentally closes their browser, they should be able to return to wherever they left off. This means that the current step value also has to be saved in <code>localStorage</code>.</p>

<p>To save this value, append the following line to the <code>showStep()</code> function:</p>

<pre><code class="language-javascript">localStorage.setItem("storedStep", currentStep);
</code></pre>

<p>Now we can retrieve the current step value and return users to wherever they left off whenever the DOM content loads. Add the following code to the <code>DOMContentLoaded</code> handler to do so:</p>

<pre><code class="language-javascript">const storedStep = localStorage.getItem("storedStep");

if (storedStep) {
    const storedStepInt = parseInt(storedStep);
    steps.forEach((el, index) =&gt; {
      el.hidden = index + 1 !== storedStepInt;
    });
    currentStep = storedStepInt;
    currentStepDiv.innerText = currentStep;
  }
</code></pre>

<p>Also, do not forget to clear the current step value from <code>localStorage</code> when the form is submitted.</p>

<pre><code class="language-javascript">localStorage.removeItem("storedStep");
</code></pre>

<p>The above line should be added to the submit handler.</p>

<h2 id="wrapping-up">Wrapping Up</h2>

<p>Creating multi-step forms can help improve user experience for complex data entry. By carefully planning out steps, implementing form validation at each step, and temporarily storing user data in the browser, you make it easier for users to complete long forms.</p>

<p>For the full implementation of this multi-step form, you can access the complete code on <a href="https://github.com/jimavictor/multistep-form">GitHub</a>.</p>

<div class="signature">
  <img src="https://www.smashingmagazine.com/images/logo/logo--red.png" alt="Smashing Editorial" width="35" height="46" loading="lazy" decoding="async" />
  <span>(gg, yk)</span>
</div>


              </article>
            </body>
          </html>
        ]]></content:encoded></item><item><author>Karin Hendrikse</author><title>Build A Static RSS Reader To Fight Your Inner FOMO</title><link>https://www.smashingmagazine.com/2024/10/build-static-rss-reader-fight-fomo/</link><pubDate>Mon, 07 Oct 2024 13:00:00 +0000</pubDate><guid>https://www.smashingmagazine.com/2024/10/build-static-rss-reader-fight-fomo/</guid><description>RSS is a classic technology that fetches content from websites and feeds it to anyone who subscribes to it with a URL. It’s based on XML, and we can use it to consume the feeds in our own apps. Karin Hendrikse demonstrates how to do exactly that with a static site you can use as your personal RSS reader.</description><content:encoded><![CDATA[
          <html>
            <head>
              <meta charset="utf-8">
              <link rel="canonical" href="https://www.smashingmagazine.com/2024/10/build-static-rss-reader-fight-fomo/" />
              <title>Build A Static RSS Reader To Fight Your Inner FOMO</title>
            </head>
            <body>
              <article>
                <header>
                  <h1>Build A Static RSS Reader To Fight Your Inner FOMO</h1>
                  
                    
                    <address>Karin Hendrikse</address>
                  
                  <time datetime="2024-10-07T13:00:00&#43;00:00" class="op-published">2024-10-07T13:00:00+00:00</time>
                  <time datetime="2024-10-07T13:00:00&#43;00:00" class="op-modified">2026-11-13T04:40:45+00:00</time>
                </header>
                
                

<p>In a fast-paced industry like tech, it can be hard to deal with the fear of missing out on important news. But, as many of us know, there’s an absolutely huge amount of information coming in daily, and finding the right time and balance to keep up can be difficult, if not stressful. A classic piece of technology like <strong>an RSS feed is a delightful way of taking back ownership of our own time</strong>. In this article, we will create a static Really Simple Syndication (RSS) reader that will bring you the latest curated news only once (yes: <em>once</em>) a day.</p>

<p>We’ll obviously work with RSS technology in the process, but we’re also going to combine it with some things that maybe you haven’t tried before, including <strong>Astro</strong> (the static site framework), <strong>TypeScript</strong> (for JavaScript goodies), a package called <strong>rss-parser</strong> (for connecting things together), as well as <strong>scheduled functions</strong> and <strong>build hooks</strong> provided by Netlify (although there are other services that do this).</p>

<p>I chose these technologies purely because I really, really enjoy them! There may be other solutions out there that are more performant, come with more features, or are simply more comfortable to you &mdash; and in those cases, I encourage you to swap in whatever you’d like. The most important thing is getting the end result!</p>

<h2 id="the-plan">The Plan</h2>

<p>Here’s how this will go. Astro generates the website. I made the intentional decision to use a static site because I want the different RSS feeds to be fetched only once during build time, and that’s something we can control each time the site is “rebuilt” and redeployed with updates. That’s where Netlify’s scheduled functions come into play, as they let us trigger rebuilds automatically at specific times. There is no need to manually check for updates and deploy them! Cron jobs can just as readily do this if you prefer a server-side solution.</p>

<p>During the triggered rebuild, we’ll let the rss-parser package do exactly what it says it does: parse a list of RSS feeds that are contained in an array. The package also allows us to set a filter for the fetched results so that we only get ones from the past day, week, and so on. Personally, I only render the news from the last seven days to prevent content overload. We’ll get there!</p>

<p>But first&hellip;</p>

<h2 id="what-is-rss">What Is RSS?</h2>

<p>RSS is a web feed technology that you can feed into a reader or news aggregator. Because RSS is standardized, you know what to expect when it comes to the feed’s format. That means we have a ton of fun possibilities when it comes to handling the data that the feed provides. Most news websites have their own RSS feed that you can subscribe to (this is <strong>Smashing Magazine’s RSS feed</strong>: <a href="https://www.smashingmagazine.com/feed/">https://www.smashingmagazine.com/feed/</a>). An RSS feed is capable of updating every time a site publishes new content, which means it can be a quick source of the latest news, but we can tailor that frequency as well.</p>

<p>RSS feeds are written in an Extensible Markup Language (XML) format and have specific elements that can be used within it. Instead of focusing too much on the technicalities here, I’ll give you a link to the <a href="https://www.rssboard.org/rss-specification">RSS specification</a>. Don’t worry; that page should be scannable enough for you to find the most pertinent information you need, like the kinds of elements that are supported and what they represent. For this tutorial, we’re only using the following elements: <strong><code>&lt;title&gt;</code></strong>, <strong><code>&lt;link&gt;</code></strong>, <strong><code>&lt;description&gt;</code></strong>, <strong><code>&lt;item&gt;</code></strong>, and <strong><code>&lt;pubDate&gt;</code></strong>. We’ll also let our RSS parser package do some of the work for us.</p>

<div data-audience="non-subscriber" data-remove="true" class="feature-panel-container">

<aside class="feature-panel" style="">
<div class="feature-panel-left-col">

<div class="feature-panel-description"><p>Meet <strong><a data-instant href="/printed-books/image-optimization/">Image Optimization</a></strong>, Addy Osmani’s new practical guide to optimizing and delivering <strong>high-quality images</strong> on the web. Everything in one single <strong>528-pages</strong> book.</p>
<a data-instant href="https://www.smashingmagazine.com/printed-books/image-optimization/" class="btn btn--green btn--large" style="">Jump to table of contents&nbsp;↬</a></div>
</div>
<div class="feature-panel-right-col"><a data-instant href="https://www.smashingmagazine.com/printed-books/image-optimization/" class="feature-panel-image-link">
<div class="feature-panel-image"><picture><source type="image/avif" srcSet="https://archive.smashing.media/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/2c669cf1-c6ef-4c87-9901-018b04f7871f/image-optimization-shop-cover-opt.avif" />
<img
    loading="lazy"
    decoding="async"
    class="feature-panel-image-img"
    src="https://archive.smashing.media/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/87fd0cfa-692e-459c-b2f3-15209a1f6aa7/image-optimization-shop-cover-opt.png"
    alt="Feature Panel"
    width="480"
    height="697"
/>
</picture>
</div>
</a>
</div>
</aside>
</div>

<h2 id="creating-the-state-site">Creating The State Site</h2>

<p>We’ll start by creating our Astro site! In your terminal run <code>pnpm create astro@latest</code>. You can use any package manager you want &mdash; I’m simply trying out <a href="https://pnpm.io">pnpm</a> for myself.</p>

<p>After running the command, Astro’s chat-based helper, Houston, walks through some setup questions to get things started.</p>

<pre><code class="language-bash"> astro   Launch sequence initiated.

   dir   Where should we create your new project?
         ./rss-buddy

  tmpl   How would you like to start your new project?
         Include sample files

    ts   Do you plan to write TypeScript?
         Yes

   use   How strict should TypeScript be?
         Strict

  deps   Install dependencies?
         Yes

   git   Initialize a new git repository?
         Yes
</code></pre>

<p>I like to use Astro’s sample files so I can get started quickly, but we’re going to clean them up a bit in the process. Let’s clean up the <code>src/pages/index.astro</code> file by removing everything inside of the <code>&lt;main&gt;&lt;/main&gt;</code> tags. Then we’re good to go!</p>

<p>From there, we can spin things by running <code>pnpm start</code>. Your terminal will tell you which localhost address you can find your site at.</p>

<div class="partners__lead-place"></div>

<h2 id="pulling-information-from-rss-feeds">Pulling Information From RSS feeds</h2>

<p>The <code>src/pages/index.astro</code> file is where we will make an array of RSS feeds we want to follow. We will be using <a href="https://docs.astro.build/en/basics/astro-syntax/">Astro’s template syntax</a>, so between the two code fences (&mdash;), create an array of <code>feedSources</code> and add some feeds. If you need inspiration, you can copy this:</p>

<pre><code class="language-javascript">const feedSources = [
  'https://www.smashingmagazine.com/feed/',
  'https://developer.mozilla.org/en-US/blog/rss.xml',
  // etc.
]
</code></pre>

<p>Now we’ll install the <a href="https://github.com/rbren/rss-parser">rss-parser package</a> in our project by running <code>pnpm install rss-parser</code>. This package is a small library that turns the XML that we get from fetching an RSS feed into JavaScript objects. This makes it easy for us to read our RSS feeds and manipulate the data any way we want.</p>

<p>Once the package is installed, open the <code>src/pages/index.astro</code> file, and at the top, we’ll import the rss-parser and instantiate the <code>Partner</code> class.</p>

<pre><code class="language-javascript">import Parser from 'rss-parser';
const parser = new Parser();
</code></pre>

<p>We use this parser to read our RSS feeds and (surprise!) <em>parse</em> them to JavaScript. We’re going to be dealing with a list of promises here. Normally, I would probably use <code>Promise.all()</code>, but the thing is, this is supposed to be a complicated experience. If one of the feeds doesn’t work for some reason, I’d prefer to simply ignore it.</p>

<p>Why? Well, because <code>Promise.all()</code> rejects everything even if only one of its promises is rejected. That might mean that if one feed doesn’t behave the way I’d expect it to, my entire page would be blank when I grab my hot beverage to read the news in the morning. I do not want to start my day confronted by an error.</p>

<p>Instead, I’ll opt to use <code>Promise.allSettled()</code>. This method will actually let all promises complete even if one of them fails. In our case, this means any feed that errors will just be ignored, which is perfect.</p>

<p>Let’s add this to the <code>src/pages/index.astro</code> file:</p>

<div class="break-out">
<pre><code class="language-typescript">interface FeedItem {
  feed?: string;
  title?: string;
  link?: string;
  date?: Date;
}

const feedItems: FeedItem[] = [];

await Promise.allSettled(
  feedSources.map(async (source) =&gt; {
    try {
      const feed = await parser.parseURL(source);
      feed.items.forEach((item) =&gt; {
        const date = item.pubDate ? new Date(item.pubDate) : undefined;
        
          feedItems.push({
            feed: feed.title,
            title: item.title,
            link: item.link,
            date,
          });
      });
    } catch (error) {
      console.error(`Error fetching feed from ${source}:`, error);
    }
  })
);
</code></pre>
</div>

<p>This creates an array (or more) named <code>feedItems</code>. For each URL in the <code>feedSources</code> array we created earlier, the rss-parser retrieves the items and, yes, parses them into JavaScript. Then, we return whatever data we want! We’ll keep it simple for now and only return the following:</p>

<ul>
<li>The feed title,</li>
<li>The title of the feed item,</li>
<li>The link to the item,</li>
<li>And the item’s published date.</li>
</ul>

<p>The next step is to ensure that all items are sorted by date so we’ll truly get the “latest” news. Add this small piece of code to our work:</p>

<div class="break-out">
<pre><code class="language-typescript">const sortedFeedItems = feedItems.sort((a, b) =&gt; (b.date ?? new Date()).getTime() - (a.date ?? new Date()).getTime());
</code></pre>
</div>

<p>Oh, and&hellip; remember when I said I didn’t want this RSS reader to render anything older than seven days? Let’s tackle that right now since we’re already in this code.</p>

<p>We’ll make a new variable called <code>sevenDaysAgo</code> and assign it a date. We’ll then set that date to seven days ago and use that logic before we add a new item to our <code>feedItems</code> array.</p>

<p>This is what the <code>src/pages/index.astro</code> file should now look like at this point:</p>

<div class="break-out">
<pre><code class="language-typescript">---
import Layout from '../layouts/Layout.astro';
import Parser from 'rss-parser';
const parser = new Parser();

const sevenDaysAgo = new Date();
sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);

const feedSources = [
  'https://www.smashingmagazine.com/feed/',
  'https://developer.mozilla.org/en-US/blog/rss.xml',
]

interface FeedItem {
  feed?: string;
  title?: string;
  link?: string;
  date?: Date;
}

const feedItems: FeedItem[] = [];

await Promise.allSettled(
  feedSources.map(async (source) =&gt; {
    try {
      const feed = await parser.parseURL(source);
      feed.items.forEach((item) =&gt; {
        const date = item.pubDate ? new Date(item.pubDate) : undefined;
        if (date && date &gt;= sevenDaysAgo) {
          feedItems.push({
            feed: feed.title,
            title: item.title,
            link: item.link,
            date,
          });
        }
      });
    } catch (error) {
      console.error(`Error fetching feed from ${source}:`, error);
    }
  })
);

const sortedFeedItems = feedItems.sort((a, b) =&gt; (b.date ?? new Date()).getTime() - (a.date ?? new Date()).getTime());

---

&lt;Layout title="Welcome to Astro."&gt;
  &lt;main&gt;
  &lt;/main&gt;
&lt;/Layout&gt;
</code></pre>
</div>

<div class="partners__lead-place"></div>

<h2 id="rendering-xml-data">Rendering XML Data</h2>

<p>It’s time to show our news articles on the Astro site! To keep this simple, we’ll format the items in an unordered list rather than some other fancy layout.</p>

<p>All we need to do is update the <code>&lt;Layout&gt;</code> element in the file with the XML objects sprinkled in for a feed item’s title, URL, and publish date.</p>

<pre><code class="language-html">&lt;Layout title="Welcome to Astro."&gt;
  &lt;main&gt;
  {sortedFeedItems.map(item =&gt; (
    &lt;ul&gt;
      &lt;li&gt;
        &lt;a href={item.link}&gt;{item.title}&lt;/a&gt;
        &lt;p&gt;{item.feed}&lt;/p&gt;
        &lt;p&gt;{item.date}&lt;/p&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  ))}
  &lt;/main&gt;
&lt;/Layout&gt;
</code></pre>

<p>Go ahead and run <code>pnpm start</code> from the terminal. The page should display an unordered list of feed items. Of course, everything is styled at the moment, but luckily for you, you can make it look exactly like you want with CSS!</p>

<p>And remember that there are even <strong>more fields available in the XML for each item</strong> if you want to display more information. If you run the following snippet in your DevTools console, you’ll see all of the fields you have at your disposal:</p>

<pre><code class="language-javascript">feed.items.forEach(item =&gt; {}
</code></pre>

<h2 id="scheduling-daily-static-site-builds">Scheduling Daily Static Site Builds</h2>

<p>We’re nearly done! The feeds are being fetched, and they are returning data back to us in JavaScript for use in our Astro page template. Since feeds are updated whenever new content is published, we need a way to fetch the latest items from it.</p>

<p>We want to avoid doing any of this manually. So, let’s set this site on Netlify to gain access to their scheduled functions that trigger a rebuild and their build hooks that do the building. Again, other services do this, and you’re welcome to roll this work with another provider &mdash; I’m just partial to Netlify since I work there. In any case, you can follow Netlify’s documentation for <a href="https://docs.netlify.com/welcome/add-new-site/#import-from-an-existing-repository">setting up a new site</a>.</p>

<p>Once your site is hosted and live, you are ready to schedule your rebuilds. A <a href="https://docs.netlify.com/configure-builds/build-hooks/">build hook</a> gives you a URL to use to trigger the new build, looking something like this:</p>

<pre><code class="language-html">https://api.netlify.com/build_hooks/your-build-hook-id
</code></pre>

<p>Let’s trigger builds every day at midnight. We’ll use Netlify’s <a href="https://docs.netlify.com/functions/scheduled-functions/">scheduled functions</a>. That’s really why I’m using Netlify to host this in the first place. Having them at the ready via the host greatly simplifies things since there’s no server work or complicated configurations to get this going. Set it and forget it!</p>

<p>We’ll install <code>@netlify/functions</code> (<a href="https://docs.netlify.com/functions/get-started/">instructions</a>) to the project and then create the following file in the project’s root directory: <code>netlify/functions/deploy.ts</code>.</p>

<p>This is what we want to add to that file:</p>

<div class="break-out">
<pre><code class="language-typescript">// netlify/functions/deploy.ts

import type { Config } from '@netlify/functions';

const BUILD_HOOK =
  'https://api.netlify.com/build_hooks/your-build-hook-id'; // replace me!

export default async (req: Request) =&gt; {
  await fetch(BUILD&#95;HOOK, {
    method: 'POST',
  })
};

export const config: Config = {
  schedule: '0 0 &#42; &#42; &#42;',
};
</code></pre>
</div>

<p>If you commit your code and push it, your site should re-deploy automatically. From that point on, it follows a schedule that rebuilds the site every day at midnight, ready for you to take your morning brew and catch up on everything that <em>you</em> think is important.</p>

<div class="signature">
  <img src="https://www.smashingmagazine.com/images/logo/logo--red.png" alt="Smashing Editorial" width="35" height="46" loading="lazy" decoding="async" />
  <span>(gg, yk)</span>
</div>


              </article>
            </body>
          </html>
        ]]></content:encoded></item><item><author>Amejimaobari Ollornwi</author><title>Generating Unique Random Numbers In JavaScript Using Sets</title><link>https://www.smashingmagazine.com/2024/08/generating-unique-random-numbers-javascript-using-sets/</link><pubDate>Mon, 26 Aug 2024 15:00:00 +0000</pubDate><guid>https://www.smashingmagazine.com/2024/08/generating-unique-random-numbers-javascript-using-sets/</guid><description>Want to create more randomized effects in your JavaScript code? The &lt;code>Math.random()&lt;/code> method alone, with its limitations, won’t cut it for generating unique random numbers. Amejimaobari Ollornwi explains how to generate a series of unique random numbers using the &lt;code>Set&lt;/code> object, how to use these random numbers as indexes for arrays, and explores some practical applications of randomization.</description><content:encoded><![CDATA[
          <html>
            <head>
              <meta charset="utf-8">
              <link rel="canonical" href="https://www.smashingmagazine.com/2024/08/generating-unique-random-numbers-javascript-using-sets/" />
              <title>Generating Unique Random Numbers In JavaScript Using Sets</title>
            </head>
            <body>
              <article>
                <header>
                  <h1>Generating Unique Random Numbers In JavaScript Using Sets</h1>
                  
                    
                    <address>Amejimaobari Ollornwi</address>
                  
                  <time datetime="2024-08-26T15:00:00&#43;00:00" class="op-published">2024-08-26T15:00:00+00:00</time>
                  <time datetime="2024-08-26T15:00:00&#43;00:00" class="op-modified">2026-11-13T04:40:45+00:00</time>
                </header>
                
                

<p>JavaScript comes with a lot of built-in functions that allow you to carry out so many different operations. One of these built-in functions is the <code>Math.random()</code> method, which generates a random floating-point number that can then be manipulated into integers.</p>

<p>However, if you wish to generate a series of unique random numbers and create more random effects in your code, you will need to come up with a custom solution for yourself because the <code>Math.random()</code> method on its own cannot do that for you.</p>

<p>In this article, we’re going to be learning how to circumvent this issue and generate a series of unique random numbers using the <code>Set</code> object in JavaScript, which we can then use to create more randomized effects in our code.</p>

<p><strong>Note</strong>: <em>This article assumes that you know how to generate random numbers in JavaScript, as well as how to work with sets and arrays.</em></p>

<div data-audience="non-subscriber" data-remove="true" class="feature-panel-container">

<aside class="feature-panel" style="">
<div class="feature-panel-left-col">

<div class="feature-panel-description"><p>Meet <strong><a data-instant href="/printed-books/touch-design-for-mobile-interfaces/">Touch Design for Mobile Interfaces</a></strong>, Steven Hoober’s brand-new guide on <strong>designing for mobile</strong> with proven, universal, human-centric guidelines. <strong>400 pages</strong>, jam-packed with in-depth user research and <strong>best practices</strong>.</p>
<a data-instant href="https://www.smashingmagazine.com/printed-books/touch-design-for-mobile-interfaces/" class="btn btn--green btn--large" style="">Jump to table of contents&nbsp;↬</a></div>
</div>
<div class="feature-panel-right-col"><a data-instant href="https://www.smashingmagazine.com/printed-books/touch-design-for-mobile-interfaces/" class="feature-panel-image-link">
<div class="feature-panel-image"><picture><source type="image/avif" srcSet="https://archive.smashing.media/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/14bcab88-b622-47f6-a51d-76b0aa003597/touch-design-book-shop-opt.avif" />
<img
    loading="lazy"
    decoding="async"
    class="feature-panel-image-img"
    src="https://archive.smashing.media/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/b14658fc-bb2d-41a6-8d1a-70eaaf1b8ec8/touch-design-book-shop-opt.png"
    alt="Feature Panel"
    width="480"
    height="697"
/>
</picture>
</div>
</a>
</div>
</aside>
</div>

<h2 id="generating-a-unique-series-of-random-numbers">Generating a Unique Series of Random Numbers</h2>

<p>One of the ways to generate a unique series of random numbers in JavaScript is by using <code>Set</code> objects. The reason why we’re making use of sets is because the elements of a set are unique. We can iteratively generate and insert random integers into sets until we get the number of integers we want.</p>

<p>And since sets do not allow duplicate elements, they are going to serve as a filter to remove all of the duplicate numbers that are generated and inserted into them so that we get a set of unique integers.</p>

<p>Here’s how we are going to approach the work:</p>

<ol>
<li>Create a <code>Set</code> object.</li>
<li>Define how many random numbers to produce and what range of numbers to use.</li>
<li>Generate each random number and immediately insert the numbers into the <code>Set</code> until the <code>Set</code> is filled with a certain number of them.</li>
</ol>

<p>The following is a quick example of how the code comes together:</p>

<div class="break-out">
<pre><code class="language-javascript">function generateRandomNumbers(count, min, max) {
  // 1: Create a `Set` object
  let uniqueNumbers = new Set();
  while (uniqueNumbers.size &lt; count) {
    // 2: Generate each random number
    uniqueNumbers.add(Math.floor(Math.random() &#42; (max - min + 1)) + min);
  }
  // 3: Immediately insert them numbers into the Set...
  return Array.from(uniqueNumbers);
}
// ...set how many numbers to generate from a given range
console.log(generateRandomNumbers(5, 5, 10));
</code></pre>
</div>

<p>What the code does is create a new <code>Set</code> object and then generate and add the random numbers to the set until our desired number of integers has been included in the set. The reason why we’re returning an array is because they are easier to work with.</p>

<p>One thing to note, however, is that the number of integers you want to generate (represented by <code>count</code> in the code) should be less than the upper limit of your range plus one (represented by <code>max + 1</code> in the code). Otherwise, the code will run forever. You can add an <code>if statement</code> to the code to ensure that this is always the case:</p>

<div class="break-out">
<pre><code class="language-javascript">function generateRandomNumbers(count, min, max) {
  // if statement checks that `count` is less than `max + 1`
  if (count &gt; max + 1) {
    return "count cannot be greater than the upper limit of range";
  } else {
    let uniqueNumbers = new Set();
    while (uniqueNumbers.size &lt; count) {
      uniqueNumbers.add(Math.floor(Math.random() &#42; (max - min + 1)) + min);
    }
    return Array.from(uniqueNumbers);
  }
}
console.log(generateRandomNumbers(5, 5, 10));
</code></pre>
</div>

<div class="partners__lead-place"></div>

<h2 id="using-the-series-of-unique-random-numbers-as-array-indexes">Using the Series of Unique Random Numbers as Array Indexes</h2>

<p>It is one thing to generate a series of random numbers. It’s another thing to use them.</p>

<p>Being able to use a series of random numbers with arrays unlocks so many possibilities: you can use them in shuffling playlists in a music app, randomly sampling data for analysis, or, as I did, <a href="https://github.com/jimavictor/remoji">shuffling the tiles in a memory game</a>.</p>

<p>Let’s take the code from the last example and work off of it to return random letters of the alphabet. First, we’ll construct an array of letters:</p>

<div class="break-out">
<pre><code class="language-javascript">const englishAlphabets = [
  'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 
  'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
];

// rest of code
</code></pre>
</div>

<p>Then we <code>map</code> the letters in the range of numbers:</p>

<div class="break-out">
<pre><code class="language-javascript">const englishAlphabets = [
  'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 
  'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
];

// generateRandomNumbers()

const randomAlphabets = randomIndexes.map((index) =&gt; englishAlphabets[index]);
</code></pre>
</div>

<p>In the original code, the <code>generateRandomNumbers()</code> function is logged to the console. This time, we’ll construct a new variable that calls the function so it can be consumed by <code>randomAlphabets</code>:</p>

<div class="break-out">
<pre><code class="language-javascript">const englishAlphabets = [
  'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 
  'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
];

// generateRandomNumbers()

const randomIndexes = generateRandomNumbers(5, 0, 25);
const randomAlphabets = randomIndexes.map((index) =&gt; englishAlphabets[index]);
</code></pre>
</div>

<p>Now we can log the output to the console like we did before to see the results:</p>

<div class="break-out">
<pre><code class="language-javascript">const englishAlphabets = [
  'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 
  'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
];

// generateRandomNumbers()

const randomIndexes = generateRandomNumbers(5, 0, 25);
const randomAlphabets = randomIndexes.map((index) =&gt; englishAlphabets[index]);
console.log(randomAlphabets);
</code></pre>
</div>

<p>And, when we put the <code>generateRandomNumbers</code><code>()</code> function definition back in, we get the final code:</p>

<div class="break-out">
<pre><code class="language-javascript">const englishAlphabets = [
  'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 
  'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
];
function generateRandomNumbers(count, min, max) {
  if (count &gt; max + 1) {
    return "count cannot be greater than the upper limit of range";
  } else {
    let uniqueNumbers = new Set();
    while (uniqueNumbers.size &lt; count) {
      uniqueNumbers.add(Math.floor(Math.random() &#42; (max - min + 1)) + min);
    }
    return Array.from(uniqueNumbers);
  }
}
const randomIndexes = generateRandomNumbers(5, 0, 25);
const randomAlphabets = randomIndexes.map((index) =&gt; englishAlphabets[index]);
console.log(randomAlphabets);
</code></pre>
</div>

<p>So, in this example, we created a new array of alphabets by randomly selecting some letters in our <code>englishAlphabets</code> array.</p>

<p>You can pass in a count argument of <code>englishAlphabets.length</code> to the <code>generateRandomNumbers</code> function if you desire to shuffle the elements in the <code>englishAlphabets</code> array instead. This is what I mean:</p>

<pre><code class="language-javascript">generateRandomNumbers(englishAlphabets.length, 0, 25);
</code></pre>

<div class="partners__lead-place"></div>

<h2 id="wrapping-up">Wrapping Up</h2>

<p>In this article, we’ve discussed how to create randomization in JavaScript by covering how to generate a series of unique random numbers, how to use these random numbers as indexes for arrays, and also some practical applications of randomization.</p>

<p>The best way to learn anything in software development is by consuming content and reinforcing whatever knowledge you’ve gotten from that content by practicing. So, don’t stop here. Run the examples in this tutorial (if you haven’t done so), play around with them, come up with your own unique solutions, and also don’t forget to share your good work. Ciao!</p>

<div class="signature">
  <img src="https://www.smashingmagazine.com/images/logo/logo--red.png" alt="Smashing Editorial" width="35" height="46" loading="lazy" decoding="async" />
  <span>(yk)</span>
</div>


              </article>
            </body>
          </html>
        ]]></content:encoded></item><item><author>Steven Levithan</author><title>Regexes Got Good: The History And Future Of Regular Expressions In JavaScript</title><link>https://www.smashingmagazine.com/2024/08/history-future-regular-expressions-javascript/</link><pubDate>Tue, 20 Aug 2024 15:00:00 +0000</pubDate><guid>https://www.smashingmagazine.com/2024/08/history-future-regular-expressions-javascript/</guid><description>Although JavaScript regexes used to be underpowered compared to other modern flavors, numerous improvements in recent years mean that’s no longer true. Steven Levithan evaluates the history and present state of regular expressions in JavaScript with tips to make your regexes more readable, maintainable, and resilient.</description><content:encoded><![CDATA[
          <html>
            <head>
              <meta charset="utf-8">
              <link rel="canonical" href="https://www.smashingmagazine.com/2024/08/history-future-regular-expressions-javascript/" />
              <title>Regexes Got Good: The History And Future Of Regular Expressions In JavaScript</title>
            </head>
            <body>
              <article>
                <header>
                  <h1>Regexes Got Good: The History And Future Of Regular Expressions In JavaScript</h1>
                  
                    
                    <address>Steven Levithan</address>
                  
                  <time datetime="2024-08-20T15:00:00&#43;00:00" class="op-published">2024-08-20T15:00:00+00:00</time>
                  <time datetime="2024-08-20T15:00:00&#43;00:00" class="op-modified">2026-11-13T04:40:45+00:00</time>
                </header>
                
                

<p>Modern JavaScript regular expressions have come a long way compared to what you might be familiar with. Regexes can be <strong>an amazing tool for searching and replacing text</strong>, but they have a longstanding reputation (perhaps outdated, as I’ll show) for being difficult to write and understand.</p>

<p>This is especially true in JavaScript-land, where regexes languished for many years, comparatively underpowered compared to their more modern counterparts in PCRE, Perl, .NET, Java, Ruby, C++, and Python. Those days are over.</p>

<p>In this article, I’ll recount the history of improvements to JavaScript regexes (spoiler: ES2018 and ES2024 changed the game), show examples of modern regex features in action, introduce you to a lightweight <a href="https://github.com/slevithan/regex">JavaScript library</a> that makes JavaScript stand alongside or surpass other modern regex flavors, and end with a preview of active proposals that will continue to improve regexes in future versions of JavaScript (with some of them already working in your browser today).</p>

<h2 id="the-history-of-regular-expressions-in-javascript">The History of Regular Expressions in JavaScript</h2>

<p>ECMAScript 3, standardized in 1999, introduced Perl-inspired regular expressions to the JavaScript language. Although it got enough things right to make regexes pretty useful (and mostly compatible with other Perl-inspired flavors), there were some big omissions, even then. And while JavaScript waited 10 years for its next standardized version with ES5, other programming languages and regex implementations added useful new features that made their regexes more powerful and readable.</p>

<p>But that was then.</p>

<blockquote>Did you know that nearly every new version of JavaScript has made at least minor improvements to regular expressions?</blockquote>

<p>Let’s take a look at them.</p>

<p>Don’t worry if it’s hard to understand what some of the following features mean &mdash; we’ll look more closely at several of the key features afterward.</p>

<ul>
<li>ES5 (2009) fixed unintuitive behavior by creating a new object every time regex literals are evaluated and allowed regex literals to use unescaped forward slashes within character classes (<code>/[/]/</code>).</li>
<li>ES6/ES2015 added two new regex flags: <code>y</code> (<code>sticky</code>), which made it easier to use regexes in parsers, and <code>u</code> (<code>unicode</code>), which added several significant Unicode-related improvements along with strict errors. It also added the <code>RegExp.prototype.flags</code> getter, support for subclassing <code>RegExp</code>, and the ability to copy a regex while changing its flags.</li>
<li>ES2018 was the edition that finally made JavaScript regexes pretty good. It added the <code>s</code> (<code>dotAll</code>) flag, lookbehind, named capture, and Unicode properties (via <code>\p{...}</code> and <code>\P{...}</code>, which require ES6’s flag <code>u</code>). All of these are extremely useful features, as we’ll see.</li>
<li>ES2020 added the string method <code>matchAll</code>, which we’ll also see more of shortly.</li>
<li>ES2022 added flag <code>d</code> (<code>hasIndices</code>), which provides start and end indices for matched substrings.</li>
<li>And finally, ES2024 added flag <code>v</code> (<code>unicodeSets</code>) as an upgrade to ES6’s flag <code>u</code>. The <code>v</code> flag adds a set of multicharacter “properties of strings” to <code>\p{...}</code>, multicharacter elements within character classes via <code>\p{...}</code> and <code>\q{...}</code>, nested character classes, set subtraction <code>[A--B]</code> and intersection <code>[A&amp;&amp;B]</code>, and different escaping rules within character classes. It also fixed case-insensitive matching for Unicode properties within negated sets <code>[^...]</code>.</li>
</ul>

<p class="c-pre-sidenote--left">As for whether you can safely use these features in your code today, the answer is yes! The latest of these features, flag <code>v</code>, is supported in Node.js 20 and <a href="https://caniuse.com/mdn-javascript_builtins_regexp_unicodesets">2023-era</a> browsers. The rest are supported in 2021-era browsers or earlier.</p>
<p class="c-sidenote c-sidenote--right">Each edition from ES2019 to ES2023 also added additional Unicode properties that can be used via <code>\p{...}</code> and <code>\P{...}</code>. And to be a completionist, ES2021 added string method <code>replaceAll</code> &mdash; although, when given a regex, the only difference from ES3’s <code>replace</code> is that it throws if not using flag <code>g</code>.</p>

<h3 id="aside-what-makes-a-regex-flavor-good">Aside: What Makes a Regex Flavor Good?</h3>

<p>With all of these changes, how do JavaScript regular expressions now stack up against other flavors? There are multiple ways to think about this, but here are a few key aspects:</p>

<ul>
<li><strong>Performance.</strong><br />
This is an important aspect but probably not the main one since mature regex implementations are generally pretty fast. JavaScript is strong on regex performance (at least considering V8’s Irregexp engine, used by Node.js, Chromium-based browsers, and <a href="https://hacks.mozilla.org/2020/06/a-new-regexp-engine-in-spidermonkey/">even Firefox</a>; and JavaScriptCore, used by Safari), but it uses a backtracking engine that is missing any syntax for backtracking control &mdash; a major limitation that makes ReDoS vulnerability more common.</li>
<li><strong>Support for advanced features</strong> that handle common or important use cases.<br />
Here, JavaScript stepped up its game with ES2018 and ES2024. JavaScript is now best in class for some features like lookbehind (with its infinite-length support) and Unicode properties (with multicharacter “properties of strings,” set subtraction and intersection, and script extensions). These features are either not supported or not as robust in many other flavors.</li>
<li><strong>Ability to write readable and maintainable patterns.</strong><br />
Here, native JavaScript has long been the worst of the major flavors since it lacks the <code>x</code> (“extended”) flag that allows insignificant whitespace and comments. Additionally, it lacks regex subroutines and subroutine definition groups (from PCRE and Perl), a powerful set of features that enable writing grammatical regexes that build up complex patterns via composition.</li>
</ul>

<p>So, it’s a bit of a mixed bag.</p>

<blockquote class="pull-quote">
  <p>
    <a class="pull-quote__link" aria-label="Share on Twitter" href="https://twitter.com/share?text=%0aJavaScript%20regexes%20have%20become%20exceptionally%20powerful,%20but%20they%e2%80%99re%20still%20missing%20key%20features%20that%20could%20make%20regexes%20safer,%20more%20readable,%20and%20more%20maintainable%20%28all%20of%20which%20hold%20some%20people%20back%20from%20using%20this%20power%29.%0a&url=https://smashingmagazine.com%2f2024%2f08%2fhistory-future-regular-expressions-javascript%2f">
      
JavaScript regexes have become exceptionally powerful, but they’re still missing key features that could make regexes safer, more readable, and more maintainable (all of which hold some people back from using this power).

    </a>
  </p>
  <div class="pull-quote__quotation">
    <div class="pull-quote__bg">
      <span class="pull-quote__symbol">“</span></div>
  </div>
</blockquote>

<p>The good news is that all of these holes can be filled by a JavaScript library, which we’ll see later in this article.</p>

<div data-audience="non-subscriber" data-remove="true" class="feature-panel-container">

<aside class="feature-panel" style="">
<div class="feature-panel-left-col">

<div class="feature-panel-description"><p>Roll up your sleeves and <strong>boost your UX skills</strong>! Meet <strong><a data-instant href="https://smart-interface-design-patterns.com/">Smart Interface Design Patterns</a></strong>&nbsp;🍣, a 10h video library by Vitaly Friedman. <strong>100s of real-life examples</strong> and live UX training. <a href="https://www.youtube.com/watch?v=3mwZztmGgbE">Free preview</a>.</p>
<a data-instant href="https://smart-interface-design-patterns.com/" class="btn btn--green btn--large" style="">Jump to table of contents&nbsp;↬</a></div>
</div>
<div class="feature-panel-right-col"><a data-instant href="https://smart-interface-design-patterns.com/" class="feature-panel-image-link">
<div class="feature-panel-image"><picture><source type="image/avif" srcSet="https://archive.smashing.media/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/3155f571-450d-42f9-81b4-494aa9b52841/video-course-smart-interface-design-patterns-vitaly-friedman.avif" />
<img
    loading="lazy"
    decoding="async"
    class="feature-panel-image-img"
    src="https://archive.smashing.media/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/8c98e7f9-8e62-4c43-b833-fc6bf9fea0a9/video-course-smart-interface-design-patterns-vitaly-friedman.jpg"
    alt="Feature Panel"
    width="690"
    height="790"
/>
</picture>
</div>
</a>
</div>
</aside>
</div>

<h2 id="using-javascript-s-modern-regex-features">Using JavaScript’s Modern Regex Features</h2>

<p>Let’s look at a few of the more useful modern regex features that you might be less familiar with. You should know in advance that this is <strong>a moderately advanced guide</strong>. If you’re relatively new to regex, here are some excellent tutorials you might want to start with:</p>

<ul>
<li><a href="https://regexlearn.com/">RegexLearn</a> and <a href="https://regexone.com/">RegexOne</a> are interactive tutorials that include practice problems.</li>
<li>JavaScript.info’s <a href="https://javascript.info/regular-expressions">regular expressions</a> chapter is a detailed and JavaScript-specific guide.</li>
<li><a href="https://www.youtube.com/watch?v=M7vDtxaD7ZU">Demystifying Regular Expressions</a> (video) is an excellent presentation for beginners by Lea Verou at HolyJS 2017.</li>
<li><a href="https://www.youtube.com/watch?v=rhzKDrUiJVk">Learn Regular Expressions In 20 Minutes</a> (video) is a live syntax walkthrough in a regex tester.</li>
</ul>

<h3 id="named-capture">Named Capture</h3>

<p>Often, you want to do more than just check whether a regex matches &mdash; you want to extract substrings from the match and do something with them in your code. Named capturing groups allow you to do this in a way that makes your regexes and code <strong>more readable</strong> and <strong>self-documenting</strong>.</p>

<p>The following example matches a record with two date fields and captures the values:</p>

<div class="break-out">
<pre><code class="language-javascript">const record = 'Admitted: 2024-01-01\nReleased: 2024-01-03';
const re = /^Admitted: (?&lt;admitted&gt;\d{4}-\d{2}-\d{2})\nReleased: (?&lt;released&gt;\d{4}-\d{2}-\d{2})$/;
const match = record.match(re);
console.log(match.groups);
/&#42; → {
  admitted: '2024-01-01',
  released: '2024-01-03'
} &#42;/
</code></pre>
</div>

<p>Don’t worry &mdash; although this regex might be challenging to understand, later, we’ll look at a way to make it much more readable. The key things here are that named capturing groups use the syntax <code>(?&lt;name&gt;...)</code>, and their results are stored on the <code>groups</code> object of matches.</p>

<p>You can also use named backreferences to rematch whatever a named capturing group matched via <code>\k&lt;name&gt;</code>, and you can use the values within search and replace as follows:</p>

<pre><code class="language-javascript">// Change 'FirstName LastName' to 'LastName, FirstName'
const name = 'Shaquille Oatmeal';
name.replace(/(?&lt;first&gt;\w+) (?&lt;last&gt;\w+)/, '$&lt;last&gt;, $&lt;first&gt;');
// → 'Oatmeal, Shaquille'
</code></pre>

<p>For advanced regexers who want to use named backreferences within a replacement callback function, the <code>groups</code> object is provided as the last argument. Here’s a fancy example:</p>

<pre><code class="language-javascript">function fahrenheitToCelsius(str) {
  const re = /(?&lt;degrees&gt;-?\d+(\.\d+)?)F\b/g;
  return str.replace(re, (...args) =&gt; {
    const groups = args.at(-1);
    return Math.round((groups.degrees - 32) &#42; 5/9) + 'C';
  });
}
fahrenheitToCelsius('98.6F');
// → '37C'
fahrenheitToCelsius('May 9 high is 40F and low is 21F');
// → 'May 9 high is 4C and low is -6C'
</code></pre>

<h3 id="lookbehind">Lookbehind</h3>

<p>Lookbehind (introduced in ES2018) is the complement to <em>lookahead</em>, which has always been supported by JavaScript regexes. Lookahead and lookbehind are <em>assertions</em> (similar to <code>^</code> for the start of a string or <code>\b</code> for word boundaries) that don’t consume any characters as part of the match. Lookbehinds succeed or fail based on whether their subpattern can be found immediately before the current match position.</p>

<p>For example, the following regex uses a lookbehind <code>(?&lt;=...)</code> to match the word “cat” (<em>only</em> the word “cat”) if it’s preceded by “fat ”:</p>

<pre><code class="language-javascript">const re = /(?&lt;=fat )cat/g;
'cat, fat cat, brat cat'.replace(re, 'pigeon');
// → 'cat, fat pigeon, brat cat'
</code></pre>

<p>You can also use <em>negative</em> lookbehind &mdash; written as <code>(?&lt;!...)</code> &mdash; to invert the assertion. That would make the regex match any instance of “cat” that’s <em>not</em> preceded by “fat ”.</p>

<pre><code class="language-javascript">const re = /(?&lt;!fat )cat/g;
'cat, fat cat, brat cat'.replace(re, 'pigeon');
// → 'pigeon, fat cat, brat pigeon'
</code></pre>

<p>JavaScript’s implementation of lookbehind is one of the very best (matched only by .NET). Whereas other regex flavors have inconsistent and complex rules for when and whether they allow variable-length patterns inside lookbehind, JavaScript allows you to look behind for any subpattern.</p>

<h3 id="the-matchall-method">The <code>matchAll</code> Method</h3>

<p>JavaScript’s <code>String.prototype.matchAll</code> was added in ES2020 and makes it easier to operate on regex matches in a loop when you need extended match details. Although other solutions were possible before, <code>matchAll</code> is often easier, and it avoids gotchas, such as the need to guard against infinite loops when looping over the results of regexes that might return zero-length matches.</p>

<p>Since <code>matchAll</code> returns an iterator (rather than an array), it’s easy to use it in a <code>for...of</code> loop.</p>

<div class="break-out">
<pre><code class="language-javascript">const re = /(?&lt;char1&gt;\w)(?&lt;char2&gt;\w)/g;
for (const match of str.matchAll(re)) {
  const {char1, char2} = match.groups;
  // Print each complete match and matched subpatterns
  console.log(`Matched "${match[0]}" with "${char1}" and "${char2}"`);
}
</code></pre>
</div>

<p><strong>Note</strong>: <em><code>matchAll</code> requires its regexes to use flag <code>g</code> (<code>global</code>). Also, as with other iterators, you can get all of its results as an array using <code>Array.from</code> or array spreading.</em></p>

<pre><code class="language-javascript">const matches = [...str.matchAll(/./g)];
</code></pre>

<h3 id="unicode-properties">Unicode Properties</h3>

<p>Unicode properties (added in ES2018) give you powerful control over multilingual text, using the syntax <code>\p{...}</code> and its negated version <code>\P{...}</code>. There are hundreds of different properties you can match, which cover a wide variety of Unicode categories, scripts, script extensions, and binary properties.</p>

<p><strong>Note</strong>: <em>For more details, check out the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape">documentation on MDN</a>.</em></p>

<p>Unicode properties require using the flag <code>u</code> (<code>unicode</code>) or <code>v</code> (<code>unicodeSets</code>).</p>

<h3 id="flag-v">Flag <code>v</code></h3>

<p>Flag <code>v</code> (<code>unicodeSets</code>) was added in ES2024 and is an upgrade to flag <code>u</code> &mdash; you can’t use both at the same time. It’s a best practice to always use one of these flags to avoid silently introducing bugs via the default Unicode-unaware mode. The decision on which to use is fairly straightforward. If you’re okay with only supporting environments with flag <code>v</code> (Node.js 20 and 2023-era browsers), then use flag <code>v</code>; otherwise, use flag <code>u</code>.</p>

<p>Flag <code>v</code> adds support for several new regex features, with the coolest probably being set subtraction and intersection. This allows using <code>A--B</code> (within character classes) to match strings in <em>A</em> but not in <em>B</em> or using <code>A&amp;&amp;B</code> to match strings in both <em>A</em> and <em>B</em>. For example:</p>

<pre><code class="language-javascript">// Matches all Greek symbols except the letter 'π'
/[\p{Script&#95;Extensions=Greek}--π]/v

// Matches only Greek letters
/[\p{Script&#95;Extensions=Greek}&&\p{Letter}]/v
</code></pre>

<p>For more details about flag <code>v</code>, including its other new features, check out this <a href="https://v8.dev/features/regexp-v-flag">explainer</a> from the Google Chrome team.</p>

<h4 id="a-word-on-matching-emoji">A Word on Matching Emoji</h4>

<p>Emoji are 🤩🔥😎👌, but how emoji get encoded in text is complicated. If you’re trying to match them with a regex, it’s important to be aware that <strong>a single emoji can be composed of one or many individual Unicode code points</strong>. Many people (and libraries!) who roll their own emoji regexes miss this point (or implement it poorly) and end up with bugs.</p>

<p>The following details for the emoji “👩🏻‍🏫” (<em>Woman Teacher: Light Skin Tone</em>) show just how complicated emoji can be:</p>

<div class="break-out">
<pre><code class="language-javascript">// Code unit length
'👩🏻‍🏫'.length;
// → 7
// Each astral code point (above \uFFFF) is divided into high and low surrogates

// Code point length
[...'👩🏻‍🏫'].length;
// → 4
// These four code points are: \u{1F469} \u{1F3FB} \u{200D} \u{1F3EB}
// \u{1F469} combined with \u{1F3FB} is '👩🏻'
// \u{200D} is a Zero-Width Joiner
// \u{1F3EB} is '🏫'

// Grapheme cluster length (user-perceived characters)
[...new Intl.Segmenter().segment('👩🏻‍🏫')].length;
// → 1
</code></pre>
</div>

<p>Fortunately, JavaScript added an easy way to match any individual, complete emoji via <code>\p{RGI_Emoji}</code>. Since this is a fancy “property of strings” that can match more than one code point at a time, it requires ES2024’s flag <code>v</code>.</p>

<p>If you want to match emojis in environments without <code>v</code> support, check out the excellent libraries <a href="https://github.com/mathiasbynens/emoji-regex">emoji-regex</a> and <a href="https://github.com/slevithan/emoji-regex-xs">emoji-regex-xs</a>.</p>

<div class="partners__lead-place"></div>

<h2 id="making-your-regexes-more-readable-maintainable-and-resilient">Making Your Regexes More Readable, Maintainable, and Resilient</h2>

<p>Despite the improvements to regex features over the years, native JavaScript regexes of sufficient complexity can still be outrageously hard to read and maintain.</p>

<p><blockquote class="twitter-tweet"><p lang="en" dir="ltr">Regular Expressions are SO EASY!!!! <a href="https://t.co/q4GSpbJRbZ">pic.twitter.com/q4GSpbJRbZ</a></p>&mdash; Garabato Kid (@garabatokid) <a href="https://twitter.com/garabatokid/status/1147063121678389253?ref_src=twsrc%5Etfw">July 5, 2019</a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script></p>

<p><br/>
ES2018’s named capture was a great addition that made regexes more self-documenting, and ES6’s <code>String.raw</code> tag allows you to avoid escaping all your backslashes when using the <code>RegExp</code> constructor. But for the most part, that’s it in terms of readability.</p>

<p class="c-pre-sidenote--left">However, there’s a lightweight and high-performance <a href="https://github.com/slevithan/regex">JavaScript library</a> named <code>regex</code> (by yours truly) that makes regexes dramatically more readable. It does this by adding key missing features from Perl-Compatible Regular Expressions (PCRE) and outputting native JavaScript regexes. You can also use it as a Babel plugin, which means that <code>regex</code> calls are transpiled at build time, so you get a better developer experience without users paying any runtime cost.</p>
<p class="c-sidenote c-sidenote--right"><a href="https://github.com/PCRE2Project/pcre2">PCRE</a> is a popular C library used by PHP for its regex support, and it’s available in countless other programming languages and tools.</p>

<p>Let’s briefly look at some of the ways the <code>regex</code> library, which provides a template tag named <code>regex</code>, can help you write complex regexes that are actually understandable and maintainable by mortals. Note that all of the new syntax described below works identically in PCRE.</p>

<h3 id="insignificant-whitespace-and-comments">Insignificant Whitespace and Comments</h3>

<p>By default, <code>regex</code> allows you to freely add whitespace and line comments (starting with <code>#</code>) to your regexes for readability.</p>

<pre><code class="language-javascript">import {regex} from 'regex';
const date = regex`
  &#35; Match a date in YYYY-MM-DD format
  (?&lt;year&gt;  \d{4}) - &#35; Year part
  (?&lt;month&gt; \d{2}) - &#35; Month part
  (?&lt;day&gt;   \d{2})   &#35; Day part
`;
</code></pre>
  

<p>This is equivalent to using PCRE’s <code>xx</code> flag.</p>

<h3 id="subroutines-and-subroutine-definition-groups">Subroutines and Subroutine Definition Groups</h3>

<p>Subroutines are written as <code>\g&lt;name&gt;</code> (where <em>name</em> refers to a named group), and they treat the referenced group as an independent subpattern that they try to match at the current position. This enables subpattern composition and reuse, which improves readability and maintainability.</p>

<p>For example, the following regex matches an IPv4 address such as “192.168.12.123”:</p>

<pre><code class="language-javascript">import {regex} from 'regex';
const ipv4 = regex`\b
  (?&lt;byte&gt; 25[0-5] | 2[0-4]\d | 1\d\d | [1-9]?\d)
  &#35; Match the remaining 3 dot-separated bytes
  (\. \g&lt;byte&gt;){3}
\b`;
</code></pre>

<p>You can take this even further by defining subpatterns for use by reference only via subroutine definition groups. Here’s an example that improves the regex for admittance records that we saw earlier in this article:</p>

<pre><code class="language-javascript">const record = 'Admitted: 2024-01-01\nReleased: 2024-01-03';
const re = regex`
  ^ Admitted:\ (?&lt;admitted&gt; \g&lt;date&gt;) \n
    Released:\ (?&lt;released&gt; \g&lt;date&gt;) $

  (?(DEFINE)
    (?&lt;date&gt;  \g&lt;year&gt;-\g&lt;month&gt;-\g&lt;day&gt;)
    (?&lt;year&gt;  \d{4})
    (?&lt;month&gt; \d{2})
    (?&lt;day&gt;   \d{2})
  )
`;
const match = record.match(re);
console.log(match.groups);
/&#42; → {
  admitted: '2024-01-01',
  released: '2024-01-03'
} &#42;/
</code></pre>

<h3 id="a-modern-regex-baseline">A Modern Regex Baseline</h3>

<p><code>regex</code> includes the <code>v</code> flag by default, so you never forget to turn it on. And in environments without native <code>v</code>, it automatically switches to flag <code>u</code> while applying <code>v</code>’s escaping rules, so your regexes are forward and backward-compatible.</p>

<p>It also implicitly enables the emulated flags <code>x</code> (insignificant whitespace and comments) and <code>n</code> (“named capture only” mode) by default, so you don’t have to continually opt into their superior modes. And since it’s a raw string template tag, you don’t have to escape your backslashes <code>\\\\</code> like with the <code>RegExp</code> constructor.</p>

<h3 id="atomic-groups-and-possessive-quantifiers-can-prevent-catastrophic-backtracking">Atomic Groups and Possessive Quantifiers Can Prevent Catastrophic Backtracking</h3>

<p>Atomic groups and possessive quantifiers are another powerful set of features added by the <code>regex</code> library. Although they’re primarily about performance and resilience against catastrophic backtracking (also known as ReDoS or “regular expression denial of service,” a serious issue where certain regexes can take forever when searching particular, not-quite-matching strings), they can also help with readability by allowing you to write simpler patterns.</p>

<p><strong>Note</strong>: <em>You can learn more in the <code>regex</code> <a href="https://github.com/slevithan/regex#atomic-groups">documentation</a>.</em></p>

<div class="partners__lead-place"></div>

<h2 id="what-s-next-upcoming-javascript-regex-improvements">What’s Next? Upcoming JavaScript Regex Improvements</h2>

<p>There are a variety of active proposals for improving regexes in JavaScript. Below, we’ll look at the three that are well on their way to being included in future editions of the language.</p>

<h3 id="duplicate-named-capturing-groups">Duplicate Named Capturing Groups</h3>

<p>This is a Stage 3 (nearly finalized) <a href="https://github.com/tc39/proposal-duplicate-named-capturing-groups">proposal</a>. Even better is that, as of recently, it works in all major browsers.</p>

<p>When named capturing was first introduced, it required that all <code>(?&lt;name&gt;...)</code> captures use unique names. However, there are cases when you have multiple alternate paths through a regex, and it would simplify your code to reuse the same group names in each alternative.</p>

<p>For example:</p>

<pre><code class="language-javascript">/(?&lt;year&gt;\d{4})-\d\d|\d\d-(?&lt;year&gt;\d{4})/
</code></pre>

<p>This proposal enables exactly this, preventing a “duplicate capture group name” error with this example. Note that names must still be unique <em>within</em> each alternative path.</p>

<h3 id="pattern-modifiers-aka-flag-groups">Pattern Modifiers (aka Flag Groups)</h3>

<p>This is another Stage 3 <a href="https://github.com/tc39/proposal-regexp-modifiers">proposal</a>. It’s already supported in Chrome/Edge 125 and Opera 111, and it’s coming <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1899813">soon</a> for Firefox. No word <a href="https://bugs.webkit.org/show_bug.cgi?id=275672">yet</a> on Safari.</p>

<p>Pattern modifiers use <code>(?ims:...)</code>, <code>(?-ims:...)</code>, or <code>(?im-s:...)</code> to turn the flags <code>i</code>, <code>m</code>, and <code>s</code> on or off for only certain parts of a regex.</p>

<p>For example:</p>

<pre><code class="language-javascript">/hello-(?i:world)/
// Matches 'hello-WORLD' but not 'HELLO-WORLD'
</code></pre>

<h3 id="escape-regex-special-characters-with-regexp-escape">Escape Regex Special Characters with <code>RegExp.escape</code></h3>

<p>This <a href="https://github.com/tc39/proposal-regex-escaping">proposal</a> recently reached Stage 3 and has been a long time coming. It isn’t yet supported in any major browsers. The proposal does what it says on the tin, providing the function <code>RegExp.escape(str)</code>, which returns the string with all regex special characters escaped so you can match them literally.</p>

<p>If you need this functionality today, the most widely-used package (with more than 500 million monthly npm downloads) is <a href="https://github.com/sindresorhus/escape-string-regexp">escape-string-regexp</a>, an ultra-lightweight, single-purpose utility that does minimal escaping. That’s great for most cases, but if you need assurance that your escaped string can safely be used at any arbitrary position within a regex, <code>escape-string-regexp</code> recommends the <code>regex</code> library that we’ve already looked at in this article. The <code>regex</code> library uses interpolation to escape embedded strings in a <a href="https://github.com/slevithan/regex#interpolating-escaped-strings">context-aware way</a>.</p>

<h2 id="conclusion">Conclusion</h2>

<p>So there you have it: the past, present, and future of JavaScript regular expressions.</p>

<p>If you want to journey even deeper into the lands of regex, check out <a href="https://github.com/slevithan/awesome-regex">Awesome Regex</a> for a list of the best regex testers, tutorials, libraries, and other resources. And for a fun regex crossword puzzle, try your hand at <a href="https://regexle.com/">regexle</a>.</p>

<p>May your parsing be prosperous and your regexes be readable.</p>

<div class="signature">
  <img src="https://www.smashingmagazine.com/images/logo/logo--red.png" alt="Smashing Editorial" width="35" height="46" loading="lazy" decoding="async" />
  <span>(gg, yk)</span>
</div>


              </article>
            </body>
          </html>
        ]]></content:encoded></item><item><author>Tim Benniks</author><title>How To Build A Multilingual Website With Nuxt.js</title><link>https://www.smashingmagazine.com/2024/08/how-build-multilingual-website-nuxt-i18n/</link><pubDate>Thu, 01 Aug 2024 15:00:00 +0000</pubDate><guid>https://www.smashingmagazine.com/2024/08/how-build-multilingual-website-nuxt-i18n/</guid><description>Handling translations for multilingual websites is famously difficult and, yet, crucial for many companies and organizations that serve a global audience. Thankfully, modern tooling abstracts away a great deal of the work, allowing for seamless translations that dynamically update the rendered content on a page, as demonstrated in this step-by-step tutorial.</description><content:encoded><![CDATA[
          <html>
            <head>
              <meta charset="utf-8">
              <link rel="canonical" href="https://www.smashingmagazine.com/2024/08/how-build-multilingual-website-nuxt-i18n/" />
              <title>How To Build A Multilingual Website With Nuxt.js</title>
            </head>
            <body>
              <article>
                <header>
                  <h1>How To Build A Multilingual Website With Nuxt.js</h1>
                  
                    
                    <address>Tim Benniks</address>
                  
                  <time datetime="2024-08-01T15:00:00&#43;00:00" class="op-published">2024-08-01T15:00:00+00:00</time>
                  <time datetime="2024-08-01T15:00:00&#43;00:00" class="op-modified">2026-11-13T04:40:45+00:00</time>
                </header>
                <p>This article is sponsored by <b>Hygraph</b></p>
                

<p>Internationalization, often abbreviated as i18n, is the process of designing and developing software applications in a way that they can be easily adapted to various spoken languages like English, German, French, and more without requiring substantial changes to the codebase. It involves <strong>moving away from hardcoded strings and techniques</strong> for translating text, formatting dates and numbers, and handling different character encodings, among other tasks.</p>

<p>Internationalization can <strong>give users the choice</strong> to access a given website or application in their native language, which can have a positive impression on them, making it crucial for reaching a global audience.</p>

<h2 id="what-we-re-making">What We’re Making</h2>

<p>In this tutorial, we’re making a website that puts these i18n pieces together using a combination of libraries and a UI framework. You’ll want to have intermediate proficiency with JavaScript, Vue, and Nuxt to follow along. Throughout this article, we will <strong>learn by examples</strong> and incrementally <strong>build a multilingual Nuxt website</strong>. Together, we will learn how to provide i18n support for different languages, lazy-load locale messages, and switch locale on runtime.</p>

<p>After that, we will explore features like interpolation, pluralization, and date/time translations.</p>

<p>And finally, we will fetch dynamic localized content from an API server using Hygraph as our API server to get localized content. If you do not have a Hygraph account <a href="https://hygraph.com/">please create one for free</a> before jumping in.</p>

<p>As a final detail, we will use <a href="https://vuetifyjs.com/en/">Vuetify</a> as our UI framework, but please feel free to use another framework if you want. The final code for what we’re building is published in a <a href="https://github.com/hygraph/hygraph-examples/tree/master/with-nuxtjs-i18n">GitHub repository</a> for reference. And finally, you can also take a look at the final result <a href="https://nuxtjs-i18n.withheadlesscms.com/">in a live demo</a>.</p>

<h2 id="the-nuxt-i18n-library">The <code>nuxt-i18n</code> Library</h2>

<p><a href="https://i18n.nuxtjs.org/"><code>nuxt-i18n</code></a> is a library for implementing internationalization in Nuxt.js applications, and it’s what we will be using in this tutorial. The library is built on top of <a href="https://vue-i18n.intlify.dev/">Vue I18n</a>, which, again, is the de facto standard library for implementing i18n in Vue applications.</p>

<p>What makes <code>nuxt-i18n</code> ideal for our work is that it provides the comprehensive set of features included in Vue I18n while adding more functionalities that are specific to Nuxt, like lazy loading locale messages, route generation and redirection for different locales, SEO metadata per locale, locale-specific domains, and more.</p>

<h2 id="initial-setup">Initial Setup</h2>

<p>Start a new Nuxt.js project and set it up with a UI framework of your choice. Again, I will be using Vue to establish the interface for this tutorial.</p>

<p>Let us add a basic layout for our website and set up some sample Vue templates.</p>

<p>First, a “Blog” page:</p>

<pre><code class="language-html">&lt;!-- pages/blog.vue --&gt;
&lt;template&gt;
  &lt;div&gt;
    &lt;v-card color="cardBackground"&gt;
      &lt;v-card-title class="text-overline"&gt;
        Home
      &lt;/v-card-title&gt;
      &lt;v-card-text&gt;
        This is the home page description
      &lt;/v-card-text&gt;
    &lt;/v-card&gt;
  &lt;/div&gt;
&lt;/template&gt;
</code></pre>

<p>Next, an “About” page:</p>

<pre><code class="language-html">&lt;!-- pages/about.vue --&gt;
&lt;template&gt;
  &lt;div&gt;
    &lt;v-card color="cardBackground"&gt;
      &lt;v-card-title class="text-overline"&gt;
        About
      &lt;/v-card-title&gt;
      &lt;v-card-text&gt;
        This is the about page description
      &lt;/v-card-text&gt;
    &lt;/v-card&gt;
  &lt;/div&gt;
&lt;/template&gt;
</code></pre>

<p>This gives us a bit of a boilerplate that we can integrate our i18n work into.</p>

<h2 id="translating-plain-text">Translating Plain Text</h2>

<p>The page templates look good, but notice how the text is hardcoded. As far as i18n goes, hardcoded content is difficult to translate into different locales. That is where the <code>nuxt-i18n</code> library comes in, providing the language-specific strings we need for the Vue components in the templates.</p>

<p>We’ll start by installing the library via the command line:</p>

<pre><code class="language-bash">npx nuxi@latest module add i18n
</code></pre>

<p>Inside the <code>nuxt.config.ts</code> file, we need to ensure that we have <code>@nuxtjs/i18n</code> inside the <code>modules</code> array. We can use the <code>i18n</code> property to provide module-specific configurations.</p>

<pre><code class="language-javascript">// nuxt.config.ts
export default defineNuxtConfig({
  // ...
  modules: [
    ...
    "@nuxtjs/i18n",
    // ...
  ],
  i18n: {
    // nuxt-i18n module configurations here
  }
  // ...
});
</code></pre>

<p>Since the <code>nuxt-i18n</code> library is built on top of the Vue I18n library, we can utilize its features in our Nuxt application as well. Let us create a new file, <code>i18n.config.ts</code>, which we will use to provide all <code>vue-i18n</code> configurations.</p>

<pre><code class="language-javascript">// i18n.config.ts
export default defineI18nConfig(() =&gt; ({
  legacy: false,
  locale: "en",
  messages: {
    en: {
      homePage: {
        title: "Home",
        description: "This is the home page description."
      },
      aboutPage: {
        title: "About",
        description: "This is the about page description."
      },
    },
  },
}));
</code></pre>

<p>Here, we have specified internationalization configurations, like using the <code>en</code> locale, and added messages for the <code>en</code> locale. These messages can be used inside the markup in the templates we made with the help of a <code>$t</code> function from Vue I18n.</p>

<p>Next, we need to link the <code>i18n.config.ts</code> configurations in our Nuxt config file.</p>

<pre><code class="language-javascript">// nuxt.config.ts
export default defineNuxtConfig({
  ...
  i18n: {
    vueI18n: "./i18n.config.ts"
  }
  ...
});
</code></pre>

<p>Now, we can use the <code>$t</code> function in our components &mdash; as shown below &mdash; to parse strings from our internationalization configurations.</p>

<p><strong>Note</strong>: <em>There’s no need to import <code>$t</code> since we have Nuxt’s default auto-import functionality.</em></p>

<pre><code class="language-html">&lt;!-- i18n.config.ts --&gt;
&lt;template&gt;
  &lt;div&gt;
    &lt;v-card color="cardBackground"&gt;
      &lt;v-card-title class="text-overline"&gt;
        {{ $t("homePage.title") }}
      &lt;/v-card-title&gt;
      &lt;v-card-text&gt;
        {{ $t("homePage.description") }}
      &lt;/v-card-text&gt;
    &lt;/v-card&gt;
  &lt;/div&gt;
&lt;/template&gt;
</code></pre>














<figure class="
  
    break-out article__image
  
  
  ">
  
    <a href="https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/1-home-page.png">
    
    <img
      loading="lazy"
      decoding="async"
      fetchpriority="low"
			width="800"
			height="316"
			
			srcset="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/1-home-page.png 400w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_800/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/1-home-page.png 800w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1200/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/1-home-page.png 1200w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1600/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/1-home-page.png 1600w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_2000/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/1-home-page.png 2000w"
			src="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/1-home-page.png"
			
			sizes="100vw"
			alt="Page with a title and description"
		/>
    
    </a>
  

  
    <figcaption class="op-vertical-bottom">
      (<a href='https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/1-home-page.png'>Large preview</a>)
    </figcaption>
  
</figure>

<h2 id="lazy-loading-translations">Lazy Loading Translations</h2>

<p>We have the title and description served from the configurations. Next, we can add more languages to the same config. For example, here’s how we can establish translations for English (<code>en</code>), French (<code>fr</code>) and Spanish (<code>es</code>):</p>

<pre><code class="language-javascript">// i18n.config.ts
export default defineI18nConfig(() =&gt; ({
  legacy: false,
  locale: "en",
  messages: {
    en: {
      // English
    },
    fr: {
      // French
    },
    es: {
      // Spanish
    }
  },
}));
</code></pre>

<p>For a production website with a lot of content that needs translating, it would be unwise to bundle all of the messages from different locales in the main bundle. Instead, we should use the <code>nuxt-i18</code> lazy loading feature asynchronously load only the required language rather than all of them at once. Also, having messages for all locales in a single configuration file can become difficult to manage over time, and breaking them up like this makes things easier to find.</p>

<p>Let’s set up the lazy loading feature in <code>nuxt.config.ts</code>:</p>

<pre><code class="language-javascript">// etc.
  i18n: {
    vueI18n: "./i18n.config.ts",
    lazy: true,
    langDir: "locales",
    locales: [
      {
        code: "en",
        file: "en.json",
        name: "English",
      },
      {
        code: "es",
        file: "es.json",
        name: "Spanish",
      },
      {
        code: "fr",
        file: "fr.json",
        name: "French",
      },
    ],
    defaultLocale: "en",
    strategy: "no_prefix",
  },

// etc.
</code></pre>

<p>This enables lazy loading and specifies the <code>locales</code> directory that will contain our locale files. The <code>locales</code> array configuration specifies from which files Nuxt.js should pick up messages for a specific language.</p>

<p>Now, we can create individual files for each language. I’ll drop all three of them right here:</p>

<pre><code class="language-javascript">
// locales/en.json
{
  "homePage": {
    "title": "Home",
    "description": "This is the home page description."
  },
  "aboutPage": {
    "title": "About",
    "description": "This is the about page description."
  },
  "selectLocale": {
    "label": "Select Locale"
  },
  "navbar": {
    "homeButton": "Home",
    "aboutButton": "About"
  }
}
</code></pre>

<div class="break-out">
<pre><code class="language-javascript">// locales/fr.json
{
  "homePage": {
    "title": "Bienvenue sur la page d'accueil",
    "description": "Ceci est la description de la page d'accueil."
  },
  "aboutPage": {
    "title": "À propos de nous",
    "description": "Ceci est la description de la page à propos de nous."
  },
  "selectLocale": {
    "label": "Sélectionner la langue"
  },
  "navbar": {
    "homeButton": "Accueil",
    "aboutButton": "À propos"
  }
}
</code></pre>
</div>

<div class="break-out">
<pre><code class="language-javascript">// locales/es.json
{
  "homePage": {
    "title": "Bienvenido a la página de inicio",
    "description": "Esta es la descripción de la página de inicio."
  },
  "aboutPage": {
    "title": "Sobre nosotros",
    "description": "Esta es la descripción de la página sobre nosotros."
  },
  "selectLocale": {
    "label": "Seleccione el idioma"
  },
  "navbar": {
    "homeButton": "Inicio",
    "aboutButton": "Acerca de"
  }
}
</code></pre>
</div>

<p>We have set up lazy loading, added multiple languages to our application, and moved our locale messages to separate files. The user gets the right locale for the right message, and the locale messages are kept in a maintainable manner inside the code base.</p>

<h2 id="switching-between-languages">Switching Between Languages</h2>

<p>We have different locales, but to see them in action, we will build a component that can be used to switch between the available locales.</p>

<pre><code class="language-html">&lt;!-- components/select-locale.vue --&gt;
&lt;script setup&gt;
const { locale, locales, setLocale } = useI18n();

const language = computed({
  get: () =&gt; locale.value,
  set: (value) =&gt; setLocale(value),
});
&lt;/script&gt;

&lt;template&gt;
  &lt;v-select
    :label="$t('selectLocale.label')"
    variant="outlined"
    color="primary"
    density="compact"    
    :items="locales"
    item-title="name"
    item-value="code"
    v-model="language"
  &gt;&lt;/v-select&gt;
&lt;/template&gt;
</code></pre>

<p>This component uses the <code>useI18n</code> hook provided by the Vue I18n library and a computed property <code>language</code> to get and set the global locale from a <code>&lt;select&gt;</code> input. To make this even more like a real-world website, we’ll include a small navigation bar that links up all of the website’s pages.</p>

<pre><code class="language-html">&lt;!-- components/select-locale.vue --&gt;
&lt;template&gt;
  &lt;v-app-bar app :elevation="2" class="px-2"&gt;
    &lt;div&gt;
      &lt;v-btn color="button" to="/"&gt;
        {{ $t("navbar.homeButton") }}
      &lt;/v-btn&gt;
      &lt;v-btn color="button" to="/about"&gt;
        {{ $t("navbar.aboutButton") }}
      &lt;/v-btn&gt;
    &lt;/div&gt;
    &lt;v-spacer /&gt;
    &lt;div class="mr-4 mt-6"&gt;
      &lt;SelectLocale /&gt;
    &lt;/div&gt;
  &lt;/v-app-bar&gt;
&lt;/template&gt;
</code></pre>

<p>That’s it! Now, we can switch between languages on the fly.</p>














<figure class="
  
    break-out article__image
  
  
  ">
  
    <a href="https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/2-current-state-homepage.png">
    
    <img
      loading="lazy"
      decoding="async"
      fetchpriority="low"
			width="800"
			height="338"
			
			srcset="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/2-current-state-homepage.png 400w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_800/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/2-current-state-homepage.png 800w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1200/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/2-current-state-homepage.png 1200w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1600/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/2-current-state-homepage.png 1600w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_2000/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/2-current-state-homepage.png 2000w"
			src="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/2-current-state-homepage.png"
			
			sizes="100vw"
			alt="Showing the current state of the homepage."
		/>
    
    </a>
  

  
    <figcaption class="op-vertical-bottom">
      Showing the current state of the homepage. (<a href='https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/2-current-state-homepage.png'>Large preview</a>)
    </figcaption>
  
</figure>














<figure class="
  
    break-out article__image
  
  
  ">
  
    <a href="https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/3-homepage-french-translation.png">
    
    <img
      loading="lazy"
      decoding="async"
      fetchpriority="low"
			width="800"
			height="362"
			
			srcset="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/3-homepage-french-translation.png 400w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_800/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/3-homepage-french-translation.png 800w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1200/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/3-homepage-french-translation.png 1200w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1600/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/3-homepage-french-translation.png 1600w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_2000/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/3-homepage-french-translation.png 2000w"
			src="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/3-homepage-french-translation.png"
			
			sizes="100vw"
			alt="Homepage showing a French translation."
		/>
    
    </a>
  

  
    <figcaption class="op-vertical-bottom">
      Showing a French translation. (<a href='https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/3-homepage-french-translation.png'>Large preview</a>)
    </figcaption>
  
</figure>

<p>We have a basic layout, but I thought we’d take this a step further and build a playground page we can use to explore more i18n features that are pretty useful when building a multilingual website.</p>

<h2 id="interpolation-and-pluralization">Interpolation and Pluralization</h2>

<p>Interpolation and pluralization are internationalization techniques for handling dynamic content and grammatical variations across different languages. <strong>Interpolation</strong> allows developers to insert dynamic variables or expressions into translated strings. <strong>Pluralization</strong> addresses the complexities of plural forms in languages by selecting the appropriate grammatical form based on numeric values. With the help of interpolation and pluralization, we can create more natural and accurate translations.</p>

<p>To use pluralization in our Nuxt app, we’ll first add a configuration to the English locale file.</p>

<pre><code class="language-javascript">// locales/en.json
{
  // etc.
  "playgroundPage": {
    "pluralization": {
      "title": "Pluralization",
      "apple": "No Apple | One Apple | {count} Apples",
      "addApple": "Add"
    }
  }
  // etc.
}
</code></pre>

<p>The pluralization configuration set up for the key <code>apple</code> defines an output &mdash; <code>No Apple</code> &mdash; if a count of 0 is passed to it, a second output &mdash; <code>One Apple</code> &mdash; if a count of 1 is passed, and a third &mdash; <code>2 Apples</code>, <code>3 Apples</code>, and so on &mdash; if the count passed in is greater than 1.</p>

<p>Here is how we can use it in your component: Whenever you click on the add button, you will see pluralization in action, changing the strings.</p>

<div class="break-out">
<pre><code class="language-html">&lt;!-- pages/playground.vue --&gt;
&lt;script setup&gt;
let appleCount = ref(0);
const addApple = () =&gt; {
  appleCount.value += 1;
};
&lt;/script&gt;
&lt;template&gt;
  &lt;v-container fluid&gt;
    &lt;!-- PLURALIZATION EXAMPLE  --&gt;
    &lt;v-card color="cardBackground"&gt;
      &lt;v-card-title class="text-overline"&gt;
        {{ $t("playgroundPage.pluralization.title") }}
      &lt;/v-card-title&gt;

      &lt;v-card-text&gt;
        {{ $t("playgroundPage.pluralization.apple", { count: appleCount }) }}
      &lt;/v-card-text&gt;
      &lt;v-card-actions&gt;
        &lt;v-btn
          @click="addApple"
          color="primary"
          variant="outlined"
          density="comfortable"
          &gt;{{ $t("playgroundPage.pluralization.addApple") }}&lt;/v-btn
        &gt;
      &lt;/v-card-actions&gt;
    &lt;/v-card&gt;
  &lt;/v-container&gt;
&lt;/template&gt;
</code></pre>
</div>

<p>To use interpolation in our Nuxt app, first, add a configuration in the English locale file:</p>

<div class="break-out">
<pre><code class="language-javascript">// locales/en.json
{
  ...
  "playgroundPage": {
    ... 
    "interpolation": {
      "title": "Interpolation",
      "sayHello": "Hello, {name}",
      "hobby": "My favourite hobby is {0}.",
      "email": "You can reach out to me at {account}{'@'}{domain}.com"
    },
    // etc. 
  }
  // etc.
}
</code></pre>
</div>

<p>The message for <code>sayHello</code> expects an object passed to it having a key <code>name</code> when invoked &mdash; a process known as <a href="https://vue-i18n.intlify.dev/guide/essentials/syntax#named-interpolation">named interpolation</a>.</p>

<p>The message <code>hobby</code> expects an array to be passed to it and will pick up the 0<sup>th</sup> element, which is known as <a href="https://vue-i18n.intlify.dev/guide/essentials/syntax#list-interpolation">list interpolation</a>.</p>

<p>The message <code>email</code> expects an object with keys <code>account</code>, and <code>domain</code> and joins both with a literal string <code>&quot;@&quot;</code>. This is known as <a href="https://vue-i18n.intlify.dev/guide/essentials/syntax#literal-interpolation">literal interpolation</a>.</p>

<p>Below is an example of how to use it in the Vue components:</p>

<div class="break-out">
<pre><code class="language-html">&lt;!-- pages/playground.vue --&gt;
&lt;template&gt;
  &lt;v-container fluid&gt;
    &lt;!-- INTERPOLATION EXAMPLE  --&gt;
    &lt;v-card color="cardBackground"&gt;
      &lt;v-card-title class="text-overline"&gt;
        {{ $t("playgroundPage.interpolation.title") }}
      &lt;/v-card-title&gt;
      &lt;v-card-text&gt;
        &lt;p&gt;
          {{
            $t("playgroundPage.interpolation.sayHello", {
              name: "Jane",
            })
          }}
        &lt;/p&gt;
        &lt;p&gt;
          {{
            $t("playgroundPage.interpolation.hobby", ["Football", "Cricket"])
          }}
        &lt;/p&gt;
        &lt;p&gt;
          {{
            $t("playgroundPage.interpolation.email", {
              account: "johndoe",
              domain: "hygraph",
            })
          }}
        &lt;/p&gt;
      &lt;/v-card-text&gt;
    &lt;/v-card&gt;
  &lt;/v-container&gt;
&lt;/template&gt;
</code></pre>
</div>














<figure class="
  
    break-out article__image
  
  
  ">
  
    <a href="https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/4-pluralization-interpolation.png">
    
    <img
      loading="lazy"
      decoding="async"
      fetchpriority="low"
			width="800"
			height="501"
			
			srcset="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/4-pluralization-interpolation.png 400w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_800/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/4-pluralization-interpolation.png 800w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1200/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/4-pluralization-interpolation.png 1200w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1600/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/4-pluralization-interpolation.png 1600w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_2000/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/4-pluralization-interpolation.png 2000w"
			src="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/4-pluralization-interpolation.png"
			
			sizes="100vw"
			alt="Exampe of pluralization and interpolation"
		/>
    
    </a>
  

  
    <figcaption class="op-vertical-bottom">
      (<a href='https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/4-pluralization-interpolation.png'>Large preview</a>)
    </figcaption>
  
</figure>

<h2 id="date-time-translations">Date &amp; Time Translations</h2>

<p>Translating dates and times involves translating date and time formats according to the conventions of different locales. We can use Vue I18n’s features for formatting date strings, handling time zones, and translating day and month names for managing date time translations. We can give the configuration for the same using the <code>datetimeFormats</code> key inside the <code>vue-i18n</code> config object.</p>

<pre><code class="language-javascript">// i18n.config.ts
export default defineI18nConfig(() =&gt; ({
  fallbackLocale: "en",
  datetimeFormats: {
    en: {
      short: {
        year: "numeric",
        month: "short",
        day: "numeric",
      },
      long: {
        year: "numeric",
        month: "short",
        day: "numeric",
        weekday: "short",
        hour: "numeric",
        minute: "numeric",
        hour12: false,
      },
    },
    fr: {
      short: {
        year: "numeric",
        month: "short",
        day: "numeric",
      },
      long: {
        year: "numeric",
        month: "short",
        day: "numeric",
        weekday: "long",
        hour: "numeric",
        minute: "numeric",
        hour12: true,
      },
    },
    es: {
      short: {
        year: "numeric",
        month: "short",
        day: "numeric",
      },
      long: {
        year: "2-digit",
        month: "short",
        day: "numeric",
        weekday: "long",
        hour: "numeric",
        minute: "numeric",
        hour12: true,
      },
    },
  },
}));
</code></pre>

<p>Here, we have set up <code>short</code> and <code>long</code> formats for all three languages. If you are coding along, you will be able to see available configurations for fields, like month and year, thanks to TypeScript and Intellisense features provided by your code editor. To display the translated dates and times in components, we should use the <code>$d</code> function and pass the format to it.</p>

<div class="break-out">
<pre><code class="language-html">&lt;!-- pages.playground.vue --&gt;
&lt;template&gt;
  &lt;v-container fluid&gt;
    &lt;!-- DATE TIME TRANSLATIONS EXAMPLE  --&gt;
    &lt;v-card color="cardBackground"&gt;
      &lt;v-card-title class="text-overline"&gt;
        {{ $t("playgroundPage.dateTime.title") }}
      &lt;/v-card-title&gt;
      &lt;v-card-text&gt;
        &lt;p&gt;Short: {{ (new Date(), $d(new Date(), "short")) }}&lt;/p&gt;
        &lt;p&gt;Long: {{ (new Date(), $d(new Date(), "long")) }}&lt;/p&gt;
      &lt;/v-card-text&gt;
    &lt;/v-card&gt;
  &lt;/v-container&gt;
&lt;/template&gt;
</code></pre>
</div>














<figure class="
  
    break-out article__image
  
  
  ">
  
    <a href="https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/5-default-date-time.png">
    
    <img
      loading="lazy"
      decoding="async"
      fetchpriority="low"
			width="800"
			height="337"
			
			srcset="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/5-default-date-time.png 400w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_800/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/5-default-date-time.png 800w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1200/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/5-default-date-time.png 1200w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1600/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/5-default-date-time.png 1600w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_2000/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/5-default-date-time.png 2000w"
			src="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/5-default-date-time.png"
			
			sizes="100vw"
			alt="Showing a default date and time."
		/>
    
    </a>
  

  
    <figcaption class="op-vertical-bottom">
      Showing a default date and time. (<a href='https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/5-default-date-time.png'>Large preview</a>)
    </figcaption>
  
</figure>














<figure class="
  
    break-out article__image
  
  
  ">
  
    <a href="https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/6-date-time-translated-spanish.png">
    
    <img
      loading="lazy"
      decoding="async"
      fetchpriority="low"
			width="800"
			height="338"
			
			srcset="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/6-date-time-translated-spanish.png 400w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_800/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/6-date-time-translated-spanish.png 800w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1200/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/6-date-time-translated-spanish.png 1200w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1600/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/6-date-time-translated-spanish.png 1600w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_2000/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/6-date-time-translated-spanish.png 2000w"
			src="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/6-date-time-translated-spanish.png"
			
			sizes="100vw"
			alt="Showing the date and time translated in Spanish."
		/>
    
    </a>
  

  
    <figcaption class="op-vertical-bottom">
      Showing the date and time translated in Spanish. (<a href='https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/6-date-time-translated-spanish.png'>Large preview</a>)
    </figcaption>
  
</figure>

<h2 id="localization-on-the-hygraph-side">Localization On the Hygraph Side</h2>

<p>We saw how to implement localization with static content. Now, we’ll attempt to understand how to fetch dynamic localized content in Nuxt.</p>

<p>We can build a blog page in our Nuxt App that fetches data from a server. The server API should accept a locale and return data in that specific locale.</p>

<p>Hygraph has a flexible localization API that allows you to publish and query localized content. If you haven’t created a free Hygraph account yet, <a href="https://hygraph.com/">you can do that on the Hygraph website</a> to continue following along.</p>

<p>Go to <strong>Project Settings</strong> &rarr; <strong>Locales</strong> and add locales for the API.</p>














<figure class="
  
    break-out article__image
  
  
  ">
  
    <a href="https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/7-hygraph-studio-locales.png">
    
    <img
      loading="lazy"
      decoding="async"
      fetchpriority="low"
			width="800"
			height="409"
			
			srcset="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/7-hygraph-studio-locales.png 400w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_800/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/7-hygraph-studio-locales.png 800w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1200/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/7-hygraph-studio-locales.png 1200w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1600/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/7-hygraph-studio-locales.png 1600w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_2000/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/7-hygraph-studio-locales.png 2000w"
			src="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/7-hygraph-studio-locales.png"
			
			sizes="100vw"
			alt="Showing Locales on the Hygraph website"
		/>
    
    </a>
  

  
    <figcaption class="op-vertical-bottom">
      (<a href='https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/7-hygraph-studio-locales.png'>Large preview</a>)
    </figcaption>
  
</figure>

<p>We have added two locales: English and French. Now we need aq <code>localized_post</code> model in our schema that only two fields: <code>title</code> and <code>body.</code> Ensure to make these “Localized” fields while creating them.</p>














<figure class="
  
    break-out article__image
  
  
  ">
  
    <a href="https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/8-hygraph-studio-schema.png">
    
    <img
      loading="lazy"
      decoding="async"
      fetchpriority="low"
			width="800"
			height="331"
			
			srcset="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/8-hygraph-studio-schema.png 400w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_800/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/8-hygraph-studio-schema.png 800w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1200/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/8-hygraph-studio-schema.png 1200w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1600/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/8-hygraph-studio-schema.png 1600w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_2000/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/8-hygraph-studio-schema.png 2000w"
			src="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/8-hygraph-studio-schema.png"
			
			sizes="100vw"
			alt="Showing Schema, which has title and body fields, on the Htygraph website"
		/>
    
    </a>
  

  
    <figcaption class="op-vertical-bottom">
      (<a href='https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/8-hygraph-studio-schema.png'>Large preview</a>)
    </figcaption>
  
</figure>

<p>Add permissions to consume the localized content, go to <strong>Project settings</strong> &rarr; <strong>Access</strong> &rarr; <strong>API Access</strong> &rarr; <strong>Public Content API</strong>, and assign <strong>Read</strong> permissions to the <code>localized_post</code> model.</p>














<figure class="
  
    break-out article__image
  
  
  ">
  
    <a href="https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/9-hygraph-studio-permissions.png">
    
    <img
      loading="lazy"
      decoding="async"
      fetchpriority="low"
			width="800"
			height="394"
			
			srcset="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/9-hygraph-studio-permissions.png 400w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_800/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/9-hygraph-studio-permissions.png 800w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1200/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/9-hygraph-studio-permissions.png 1200w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1600/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/9-hygraph-studio-permissions.png 1600w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_2000/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/9-hygraph-studio-permissions.png 2000w"
			src="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/9-hygraph-studio-permissions.png"
			
			sizes="100vw"
			alt="Project settings on the Htygraph website with Public Content API and an assigned Read permission"
		/>
    
    </a>
  

  
    <figcaption class="op-vertical-bottom">
      (<a href='https://files.smashing.media/articles/how-build-multilingual-website-nuxtjs/9-hygraph-studio-permissions.png'>Large preview</a>)
    </figcaption>
  
</figure>

<p>Now, we can go to the <a href="https://hygraph.com/docs/api-reference/basics/api-playground">Hygrapgh API playground</a> and add some localized data to the database with the help of GraphQL mutations. To limit the scope of this example, I am simply adding data from the Hygraph API playground. In an ideal world, a create/update mutation would be triggered from the front end after receiving user input.</p>

<p>Run this mutation in the Hygraph API playground:</p>

<div class="break-out">
<pre><code class="language-javascript">mutation createLocalizedPost {
  createLocalizedPost(
    data: {
      title: "A Journey Through the Alps", 
      body: "Exploring the majestic mountains of the Alps offers a thrilling experience. The stunning landscapes, diverse wildlife, and pristine environment make it a perfect destination for nature lovers.", 
      localizations: {
        create: [
          {locale: fr, data: {title: "Un voyage à travers les Alpes", body: "Explorer les majestueuses montagnes des Alpes offre une expérience palpitante. Les paysages époustouflants, la faune diversifiée et l'environnement immaculé en font une destination parfaite pour les amoureux de la nature."}}
        ]
      }
    }
  ) {
    id
  }
}
</code></pre>
</div>

<p>The mutation above creates a post with the <code>en</code> locale and includes a <code>fr</code> version of the same post. Feel free to add more data to your model if you want to see things work from a broader set of data.</p>

<h2 id="putting-things-together">Putting Things Together</h2>

<p>Now that we have Hygraph API content ready for consumption let’s take a moment to understand how it’s consumed inside the Nuxt app.</p>

<p>To do this, we’ll install <a href="https://nuxt.com/modules/graphql-client">nuxt-graphql-client</a> to serve as the app’s GraphQL client. This is a minimal GraphQL client for performing GraphQL operations without having to worry about complex configurations, code generation, typing, and other setup tasks.</p>

<pre><code class="language-bash">npx nuxi@latest module add graphql-client
</code></pre>

<pre><code class="language-javascript">// nuxt.config.ts
export default defineNuxtConfig({
  modules: [
    // ...
    "nuxt-graphql-client"
    // ...
  ],
  runtimeConfig: {
    public: {
      GQL_HOST: 'ADD&#95;YOUR&#95;GQL&#95;HOST&#95;URL&#95;HERE&#95;OR&#95;IN&#95;.env'
    }
  },
});
</code></pre>

<p>Next, let&rsquo;s add our GraphQL queries in <code>graphql/queries.graphql</code>.</p>

<pre><code class="language-javascript">query getPosts($locale: [Locale!]!) {
  localizedPosts(locales: $locale) {
    title
    body
  }
}
</code></pre>

<p>The GraphQL client will automatically scan <code>.graphql</code> and <code>.gql</code> files and generate client-side code and typings in the <code>.nuxt/gql</code> folder. All we need to do is stop and restart the Nuxt application. After restarting the app, the GraphQL client will allow us to use a <code>GqlGetPosts</code> function to trigger the query.</p>

<p>Now, we will build the Blog page where by querying the Hygraph server and showing the dynamic data.</p>

<pre><code class="language-javascript">// pages/blog.vue
&lt;script lang="ts" setup&gt;
  import type { GetPostsQueryVariables } from "#gql";
  import type { PostItem, Locale } from "../types/types";

  const { locale } = useI18n();
  const posts = ref&lt;PostItem[]&gt;([]);
  const isLoading = ref(false);
  const isError = ref(false);

  const fetchPosts = async (localeValue: Locale) =&gt; {
    try {
      isLoading.value = true;
      const variables: GetPostsQueryVariables = {
        locale: [localeValue],
      };
      const data = await GqlGetPosts(variables);
      posts.value = data?.localizedPosts ?? [];
    } catch (err) {
      console.log("Fetch Error, Something went wrong", err);
      isError.value = true;
    } finally {
      isLoading.value = false;
    }
  };

  // Fetch posts on component mount
  onMounted(() =&gt; {
    fetchPosts(locale.value as Locale);
  });

  // Watch for locale changes
  watch(locale, (newLocale) =&gt; {
    fetchPosts(newLocale as Locale);
  });
&lt;/script&gt;
</code></pre>

<p>This code fetches only the current locale from the <code>useI18n</code> hook and sends it to the <code>fetchPosts</code> function when the Vue component is mounted. The <code>fetchPosts</code> function will pass the locale to the GraphQL query as a variable and obtain localized data from the Hygraph server. We also have a watcher on the <code>locale</code> so that whenever the global locale is changed by the user we make an API call to the server again and fetch posts in that locale.</p>

<p>And, finally, let’s add markup for viewing our fetched data!</p>

<div class="break-out">
<pre><code class="language-html">&lt;!-- pages/blog.vue --&gt;
&lt;template&gt;
  &lt;v-container fluid&gt;
    &lt;v-card-title class="text-overline"&gt;Blogs&lt;/v-card-title&gt;
    &lt;div v-if="isLoading"&gt;
      &lt;v-skeleton-loader type="card" v-for="n in 2" :key="n" class="mb-4" /&gt;
    &lt;/div&gt;
    &lt;div v-else-if="isError"&gt;
      &lt;p&gt;Something went wrong while getting blogs please check the logs.&lt;/p&gt;
    &lt;/div&gt;
    &lt;div v-else&gt;
      &lt;div
        v-for="(post, index) in posts"
        :key="post.title || index"
        class="mb-4"
      &gt;
        &lt;v-card color="cardBackground"&gt;
          &lt;v-card-title class="text-h6"&gt;{{ post.title }}&lt;/v-card-title&gt;
          &lt;v-card-text&gt;{{ post.body }}&lt;/v-card-text&gt;
        &lt;/v-card&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/v-container&gt;
&lt;/template&gt;
</code></pre>
</div>

<p>Awesome! If all goes according to plan, then your app should look something like the one in the following video.</p>


<figure class="video-embed-container break-out">
  <div class="video-embed-container--wrapper"
	
  >
    <iframe class="video-embed-container--wrapper-iframe" src="https://player.vimeo.com/video/992462029"
        frameborder="0"
        allow="autoplay; fullscreen; picture-in-picture"
        allowfullscreen>
    </iframe>
	</div>
	
</figure>

<h2 id="wrapping-up">Wrapping Up</h2>

<p>Check that out &mdash; we just made the <strong>functionality for translating content for a multilingual website</strong>! Now, a user can select a locale from a list of options, and the app fetches content for the selected locale and automatically updates the displayed content.</p>

<p>Did you think that translations would require more difficult steps? It’s pretty amazing that we’re able to cobble together a couple of libraries, hook them up to an API, and wire everything up to render on a page.</p>

<p>Of course, there are other libraries and resources for handling internationalization in a multilingual context. The exact tooling is less the point than it is seeing what pieces are needed to handle dynamic translations and how they come together.</p>

<div class="signature">
  <img src="https://www.smashingmagazine.com/images/logo/logo--red.png" alt="Smashing Editorial" width="35" height="46" loading="lazy" decoding="async" />
  <span>(gg, yk)</span>
</div>


              </article>
            </body>
          </html>
        ]]></content:encoded></item><item><author>Juan Diego Rodríguez</author><title>Uniting Web And Native Apps With 4 Unknown JavaScript APIs</title><link>https://www.smashingmagazine.com/2024/06/uniting-web-native-apps-unknown-javascript-apis/</link><pubDate>Thu, 20 Jun 2024 18:00:00 +0000</pubDate><guid>https://www.smashingmagazine.com/2024/06/uniting-web-native-apps-unknown-javascript-apis/</guid><description>Have you heard of the Screen Orientation API? What about the Device Orientation API, Vibration API, or the Contact Picker API? Juan Diego Rodriguez is interested in these under-the-radar web features and discusses how they can be used to create more usable and robust progressive web apps if and when they gain broader support.</description><content:encoded><![CDATA[
          <html>
            <head>
              <meta charset="utf-8">
              <link rel="canonical" href="https://www.smashingmagazine.com/2024/06/uniting-web-native-apps-unknown-javascript-apis/" />
              <title>Uniting Web And Native Apps With 4 Unknown JavaScript APIs</title>
            </head>
            <body>
              <article>
                <header>
                  <h1>Uniting Web And Native Apps With 4 Unknown JavaScript APIs</h1>
                  
                    
                    <address>Juan Diego Rodríguez</address>
                  
                  <time datetime="2024-06-20T18:00:00&#43;00:00" class="op-published">2024-06-20T18:00:00+00:00</time>
                  <time datetime="2024-06-20T18:00:00&#43;00:00" class="op-modified">2026-11-13T04:40:45+00:00</time>
                </header>
                
                

<p>A couple of years ago, <a href="https://www.smashingmagazine.com/2022/09/javascript-api-guide/">four JavaScript APIs that landed at the bottom of awareness in the State of JavaScript survey</a>. I took an interest in those APIs because they have so much potential to be useful but don’t get the credit they deserve. Even after a quick search, I was amazed at how many new web APIs have been added to the ECMAScript specification that aren’t getting their dues and with a lack of awareness and browser support in browsers.</p>

<p>That situation can be a “catch-22”:</p>

<blockquote class="pull-quote">
  <p>
    <a class="pull-quote__link" aria-label="Share on Twitter" href="https://twitter.com/share?text=%0aAn%20API%20is%20interesting%20but%20lacks%20awareness%20due%20to%20incomplete%20support,%20and%20there%20is%20no%20immediate%20need%20to%20support%20it%20due%20to%20low%20awareness.%0a&url=https://smashingmagazine.com%2f2024%2f06%2funiting-web-native-apps-unknown-javascript-apis%2f">
      
An API is interesting but lacks awareness due to incomplete support, and there is no immediate need to support it due to low awareness.

    </a>
  </p>
  <div class="pull-quote__quotation">
    <div class="pull-quote__bg">
      <span class="pull-quote__symbol">“</span></div>
  </div>
</blockquote>

<p>Most of these APIs are designed to power progressive web apps (PWA) and close the gap between web and native apps. Bear in mind that creating a PWA involves more than just adding a <a href="https://css-tricks.com/how-to-transition-to-manifest-v3-for-chrome-extensions/">manifest file</a>. Sure, it’s a PWA by definition, but it functions like a bookmark on your home screen in practice. In reality, we need several APIs to achieve a fully native app experience on the web. And the four APIs I’d like to shed light on are part of that PWA puzzle that brings to the web what we once thought was only possible in native apps.</p>

<p>You can see all these <a href="https://monknow.github.io/pwa-features-demo/">APIs in action in this demo</a> as we go along.</p>

<h2 id="1-screen-orientation-api">1. Screen Orientation API</h2>

<p>The <a href="https://www.w3.org/TR/screen-orientation/">Screen Orientation API</a> can be used to sniff out the device’s current orientation. Once we know whether a user is browsing in a portrait or landscape orientation, we can use it to <strong>enhance the UX for mobile devices</strong> by changing the UI accordingly. We can also use it to <strong>lock the screen in a certain position</strong>, which is useful for displaying videos and other full-screen elements that benefit from a wider viewport.</p>

<p>Using the global <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/screen"><code>screen</code></a> object, you can access various properties the screen uses to render a page, including the <code>screen.orientation</code> object. It has two properties:</p>

<ul>
<li><strong><code>type</code>:</strong> The current screen orientation. It can be: <code>&quot;portrait-primary&quot;</code>, <code>&quot;portrait-secondary&quot;</code>, <code>&quot;landscape-primary&quot;</code>, or <code>&quot;landscape-secondary&quot;</code>.</li>
<li><strong><code>angle</code>:</strong> The current screen orientation angle. It can be any number from 0 to 360 degrees, but it’s normally set in multiples of 90 degrees (e.g., <code>0</code>, <code>90</code>, <code>180</code>, or <code>270</code>).</li>
</ul>

<p>On mobile devices, if the <code>angle</code> is <code>0</code> degrees, the <code>type</code> is most often going to evaluate to <code>&quot;portrait&quot;</code> (vertical), but on desktop devices, it is typically <code>&quot;landscape&quot;</code> (horizontal). This makes the <code>type</code> property precise for knowing a device’s true position.</p>

<p>The <code>screen.orientation</code> object also has two methods:</p>

<ul>
<li><strong><code>.lock()</code>:</strong> This is an async method that takes a <code>type</code> value as an argument to lock the screen.</li>
<li><strong><code>.unlock()</code>:</strong> This method unlocks the screen to its default orientation.</li>
</ul>

<p>And lastly, <code>screen.orientation</code> counts with an <code>&quot;orientationchange&quot;</code> event to know when the orientation has changed.</p>

<div data-audience="non-subscriber" data-remove="true" class="feature-panel-container">

<aside class="feature-panel" style="">
<div class="feature-panel-left-col">

<div class="feature-panel-description"><p>Roll up your sleeves and <strong>boost your UX skills</strong>! Meet <strong><a data-instant href="https://smart-interface-design-patterns.com/">Smart Interface Design Patterns</a></strong>&nbsp;🍣, a 10h video library by Vitaly Friedman. <strong>100s of real-life examples</strong> and live UX training. <a href="https://www.youtube.com/watch?v=3mwZztmGgbE">Free preview</a>.</p>
<a data-instant href="https://smart-interface-design-patterns.com/" class="btn btn--green btn--large" style="">Jump to table of contents&nbsp;↬</a></div>
</div>
<div class="feature-panel-right-col"><a data-instant href="https://smart-interface-design-patterns.com/" class="feature-panel-image-link">
<div class="feature-panel-image"><picture><source type="image/avif" srcSet="https://archive.smashing.media/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/3155f571-450d-42f9-81b4-494aa9b52841/video-course-smart-interface-design-patterns-vitaly-friedman.avif" />
<img
    loading="lazy"
    decoding="async"
    class="feature-panel-image-img"
    src="https://archive.smashing.media/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/8c98e7f9-8e62-4c43-b833-fc6bf9fea0a9/video-course-smart-interface-design-patterns-vitaly-friedman.jpg"
    alt="Feature Panel"
    width="690"
    height="790"
/>
</picture>
</div>
</a>
</div>
</aside>
</div>

<h3 id="browser-support">Browser Support</h3>














<figure class="
  
    break-out article__image
  
  
  ">
  
    <a href="https://caniuse.com/screen-orientation">
    
    <img
      loading="lazy"
      decoding="async"
      fetchpriority="low"
			width="800"
			height="289"
			
			srcset="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/screen-orientation-api-support.jpg 400w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_800/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/screen-orientation-api-support.jpg 800w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1200/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/screen-orientation-api-support.jpg 1200w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1600/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/screen-orientation-api-support.jpg 1600w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_2000/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/screen-orientation-api-support.jpg 2000w"
			src="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/screen-orientation-api-support.jpg"
			
			sizes="100vw"
			alt="Browser Support on Screen Orientation API"
		/>
    
    </a>
  

  
    <figcaption class="op-vertical-bottom">
      Source: <a href='https://caniuse.com/screen-orientation'>Caniuse</a>. (<a href='https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/screen-orientation-api-support.jpg'>Large preview</a>)
    </figcaption>
  
</figure>

<h3 id="finding-and-locking-screen-orientation">Finding And Locking Screen Orientation</h3>

<p>Let’s code a short demo using the Screen Orientation API to know the device’s orientation and lock it in its current position.</p>

<p>This can be our HTML boilerplate:</p>

<div class="break-out">
<pre><code class="language-html">&lt;main&gt;
  &lt;p&gt;
    Orientation Type: &lt;span class="orientation-type"&gt;&lt;/span&gt;
    &lt;br /&gt;
    Orientation Angle: &lt;span class="orientation-angle"&gt;&lt;/span&gt;
  &lt;/p&gt;

  &lt;button type="button" class="lock-button"&gt;Lock Screen&lt;/button&gt;

  &lt;button type="button" class="unlock-button"&gt;Unlock Screen&lt;/button&gt;

  &lt;button type="button" class="fullscreen-button"&gt;Go Full Screen&lt;/button&gt;
&lt;/main&gt;
</code></pre>
</div>

<p>On the JavaScript side, we inject the screen orientation <code>type</code> and <code>angle</code> properties into our HTML.</p>

<div class="break-out">
<pre><code class="language-javascript">let currentOrientationType = document.querySelector(".orientation-type");
let currentOrientationAngle = document.querySelector(".orientation-angle");

currentOrientationType.textContent = screen.orientation.type;
currentOrientationAngle.textContent = screen.orientation.angle;
</code></pre>
</div>

<p>Now, we can see the device’s orientation and angle properties. On my laptop, they are <code>&quot;landscape-primary&quot;</code> and <code>0°</code>.</p>














<figure class="
  
    break-out article__image
  
  
  ">
  
    <a href="https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/screen-orientation-1.png">
    
    <img
      loading="lazy"
      decoding="async"
      fetchpriority="low"
			width="800"
			height="367"
			
			srcset="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/screen-orientation-1.png 400w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_800/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/screen-orientation-1.png 800w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1200/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/screen-orientation-1.png 1200w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1600/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/screen-orientation-1.png 1600w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_2000/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/screen-orientation-1.png 2000w"
			src="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/screen-orientation-1.png"
			
			sizes="100vw"
			alt="Screen Orientation type and angle being displayed"
		/>
    
    </a>
  

  
    <figcaption class="op-vertical-bottom">
      (<a href='https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/screen-orientation-1.png'>Large preview</a>)
    </figcaption>
  
</figure>

<p>If we listen to the window’s <code>orientationchange</code> event, we can see how the values are updated each time the screen rotates.</p>

<pre><code class="language-javascript">window.addEventListener("orientationchange", () =&gt; {
  currentOrientationType.textContent = screen.orientation.type;
  currentOrientationAngle.textContent = screen.orientation.angle;
});
</code></pre>














<figure class="
  
  
  ">
  
    <a href="https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/screen-orientation-2.png">
    
    <img
      loading="lazy"
      decoding="async"
      fetchpriority="low"
			width="800"
			height="679"
			
			srcset="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/screen-orientation-2.png 400w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_800/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/screen-orientation-2.png 800w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1200/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/screen-orientation-2.png 1200w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1600/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/screen-orientation-2.png 1600w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_2000/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/screen-orientation-2.png 2000w"
			src="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/screen-orientation-2.png"
			
			sizes="100vw"
			alt="Screen Orientation type and angle are displayed in portrait mode"
		/>
    
    </a>
  

  
    <figcaption class="op-vertical-bottom">
      (<a href='https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/screen-orientation-2.png'>Large preview</a>)
    </figcaption>
  
</figure>

<p>To lock the screen, we need to first be in full-screen mode, so we will use another extremely useful feature: the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API"><strong>Fullscreen API</strong></a>. Nobody wants a webpage to pop into full-screen mode without their consent, so we need <a href="https://developer.mozilla.org/en-US/docs/Web/Security/User_activation#transient_activation">transient activation</a> (i.e., a user click) from a DOM element to work.</p>

<p>The Fullscreen API has two methods:</p>

<ol>
<li><code>Document.exitFullscreen()</code> is used from the global document object,</li>
<li><code>Element.requestFullscreen()</code> makes the specified element and its descendants go full-screen.</li>
</ol>

<p>We want the entire page to be full-screen so we can invoke the method from the root element at the <code>document.documentElement</code> object:</p>

<div class="break-out">
<pre><code class="language-javascript">const fullscreenButton = document.querySelector(".fullscreen-button");

fullscreenButton.addEventListener("click", async () =&gt; {
  // If it is already in full-screen, exit to normal view
  if (document.fullscreenElement) {
    await document.exitFullscreen();
  } else {
    await document.documentElement.requestFullscreen();
  }
});
</code></pre>
</div>

<p>Next, we can lock the screen in its current orientation:</p>

<pre><code class="language-javascript">const lockButton = document.querySelector(".lock-button");

lockButton.addEventListener("click", async () =&gt; {
  try {
    await screen.orientation.lock(screen.orientation.type);
  } catch (error) {
    console.error(error);
  }
});
</code></pre>

<p>And do the opposite with the unlock button:</p>

<pre><code class="language-javascript">const unlockButton = document.querySelector(".unlock-button");

unlockButton.addEventListener("click", () =&gt; {
  screen.orientation.unlock();
});
</code></pre>

<h3 id="can-t-we-check-orientation-with-a-media-query">Can’t We Check Orientation With a Media Query?</h3>

<p>Yes! We can indeed check page orientation via the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/@media/orientation"><code>orientation</code> media feature</a> in a CSS media query. However, media queries compute the current orientation by checking if the width is “bigger than the height” for landscape or “smaller” for portrait. By contrast,</p>

<blockquote class="pull-quote">
  <p>
    <a class="pull-quote__link" aria-label="Share on Twitter" href="https://twitter.com/share?text=%0aThe%20Screen%20Orientation%20API%20checks%20for%20the%20screen%20rendering%20the%20page%20regardless%20of%20the%20viewport%20dimensions,%20making%20it%20resistant%20to%20inconsistencies%20that%20may%20crop%20up%20with%20page%20resizing.%0a&url=https://smashingmagazine.com%2f2024%2f06%2funiting-web-native-apps-unknown-javascript-apis%2f">
      
The Screen Orientation API checks for the screen rendering the page regardless of the viewport dimensions, making it resistant to inconsistencies that may crop up with page resizing.

    </a>
  </p>
  <div class="pull-quote__quotation">
    <div class="pull-quote__bg">
      <span class="pull-quote__symbol">“</span></div>
  </div>
</blockquote>

<p>You may have noticed how PWAs like Instagram and X force the screen to be in portrait mode even when the native system orientation is unlocked. It is important to notice that this behavior isn’t achieved through the Screen Orientation API, but by setting the <code>orientation</code> property on the <code>manifest.json</code> file to the desired orientation type.</p>

<h2 id="2-device-orientation-api">2. Device Orientation API</h2>

<p>Another API I’d like to poke at is the Device Orientation API. It provides access to a device’s gyroscope sensors to read the device’s orientation in space; something used all the time in mobile apps, mainly games. The API makes this happen with a <code>deviceorientation</code> event that triggers each time the device moves. It has the following properties:</p>

<ul>
<li><strong><code>event.alpha</code>:</strong> Orientation along the Z-axis, ranging from 0 to 360 degrees.</li>
<li><strong><code>event.beta</code>:</strong> Orientation along the X-axis, ranging from -180 to 180 degrees.</li>
<li><strong><code>event.gamma</code>:</strong> Orientation along the Y-axis, ranging from -90 to 90 degrees.</li>
</ul>

<h3 id="browser-support-1">Browser Support</h3>














<figure class="
  
    break-out article__image
  
  
  ">
  
    <a href="https://caniuse.com/deviceorientation">
    
    <img
      loading="lazy"
      decoding="async"
      fetchpriority="low"
			width="800"
			height="293"
			
			srcset="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/device-orientation-api-support.jpg 400w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_800/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/device-orientation-api-support.jpg 800w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1200/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/device-orientation-api-support.jpg 1200w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1600/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/device-orientation-api-support.jpg 1600w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_2000/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/device-orientation-api-support.jpg 2000w"
			src="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/device-orientation-api-support.jpg"
			
			sizes="100vw"
			alt="Browser Support on Device Orientation API"
		/>
    
    </a>
  

  
    <figcaption class="op-vertical-bottom">
      Source: <a href='https://caniuse.com/deviceorientation'>Caniuse</a>. (<a href='https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/device-orientation-api-support.jpg'>Large preview</a>)
    </figcaption>
  
</figure>

<h3 id="moving-elements-with-your-device">Moving Elements With Your Device</h3>

<p>In this case, we will make a 3D cube with CSS that can be rotated with your device! The full instructions I used to make the initial CSS cube are credited to <a href="https://desandro.com">David DeSandro</a> and can be <a href="https://3dtransforms.desandro.com/cube">found in his introduction to 3D transforms</a>.</p>

<figure class="break-out">
	<p data-height="480"
	data-theme-id="light"
	data-slug-hash="vYwdMNJ"
	data-user="smashingmag"
	data-default-tab="result"
	class="codepen">See the Pen [Rotate cube [forked]](https://codepen.io/smashingmag/pen/vYwdMNJ) by <a href="https://codepen.io/desandro">Dave DeSandro</a>.</p>
	<figcaption>See the Pen <a href="https://codepen.io/smashingmag/pen/vYwdMNJ">Rotate cube [forked]</a> by <a href="https://codepen.io/desandro">Dave DeSandro</a>.</figcaption>
</figure>

<p>You can see raw full HTML in the demo, but let’s print it here for posterity:</p>

<pre><code class="language-html">&lt;main&gt;
  &lt;div class="scene"&gt;
    &lt;div class="cube"&gt;
      &lt;div class="cube&#95;&#95;face cube&#95;&#95;face--front"&gt;1&lt;/div&gt;
      &lt;div class="cube&#95;&#95;face cube&#95;&#95;face--back"&gt;2&lt;/div&gt;
      &lt;div class="cube&#95;&#95;face cube&#95;&#95;face--right"&gt;3&lt;/div&gt;
      &lt;div class="cube&#95;&#95;face cube&#95;&#95;face--left"&gt;4&lt;/div&gt;
      &lt;div class="cube&#95;&#95;face cube&#95;&#95;face--top"&gt;5&lt;/div&gt;
      &lt;div class="cube&#95;&#95;face cube&#95;&#95;face--bottom"&gt;6&lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  &lt;h1&gt;Device Orientation API&lt;/h1&gt;
  &lt;p&gt;
    Alpha: &lt;span class="currentAlpha"&gt;&lt;/span&gt;
    &lt;br /&gt;
    Beta: &lt;span class="currentBeta"&gt;&lt;/span&gt;
    &lt;br /&gt;
    Gamma: &lt;span class="currentGamma"&gt;&lt;/span&gt;
  &lt;/p&gt;
&lt;/main&gt;
</code></pre>

<p>To keep this brief, I won’t explain the CSS code here. Just keep in mind that it provides the necessary styles for the 3D cube, and it can be rotated through all axes using the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/rotate">CSS <code>rotate()</code> function</a>.</p>

<p>Now, with JavaScript, we listen to the window’s <code>deviceorientation</code> event and access the event orientation data:</p>

<pre><code class="language-javascript">const currentAlpha = document.querySelector(".currentAlpha");
const currentBeta = document.querySelector(".currentBeta");
const currentGamma = document.querySelector(".currentGamma");

window.addEventListener("deviceorientation", (event) =&gt; {
  currentAlpha.textContent = event.alpha;
  currentBeta.textContent = event.beta;
  currentGamma.textContent = event.gamma;
});
</code></pre>

<p>To see how the data changes on a desktop device, we can open Chrome’s DevTools and access the Sensors Panel to emulate a rotating device.</p>














<figure class="
  
    break-out article__image
  
  
  ">
  
    <a href="https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/device-motion-1.png">
    
    <img
      loading="lazy"
      decoding="async"
      fetchpriority="low"
			width="800"
			height="601"
			
			srcset="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/device-motion-1.png 400w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_800/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/device-motion-1.png 800w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1200/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/device-motion-1.png 1200w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1600/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/device-motion-1.png 1600w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_2000/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/device-motion-1.png 2000w"
			src="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/device-motion-1.png"
			
			sizes="100vw"
			alt="Emulating a device rotating on the Chrome DevTools Sensor Panel"
		/>
    
    </a>
  

  
    <figcaption class="op-vertical-bottom">
      (<a href='https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/device-motion-1.png'>Large preview</a>)
    </figcaption>
  
</figure>

<p>To rotate the cube, we change its CSS <code>transform</code> properties according to the device orientation data:</p>

<div class="break-out">
<pre><code class="language-javascript">const currentAlpha = document.querySelector(".currentAlpha");
const currentBeta = document.querySelector(".currentBeta");
const currentGamma = document.querySelector(".currentGamma");

const cube = document.querySelector(".cube");

window.addEventListener("deviceorientation", (event) =&gt; {
  currentAlpha.textContent = event.alpha;
  currentBeta.textContent = event.beta;
  currentGamma.textContent = event.gamma;

  cube.style.transform = `rotateX(${event.beta}deg) rotateY(${event.gamma}deg) rotateZ(${event.alpha}deg)`;
});
</code></pre>
</div>

<p>This is the result:</p>














<figure class="
  
    break-out article__image
  
  
  ">
  
    <a href="https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/device-motion-2.jpg">
    
    <img
      loading="lazy"
      decoding="async"
      fetchpriority="low"
			width="800"
			height="392"
			
			srcset="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/device-motion-2.jpg 400w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_800/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/device-motion-2.jpg 800w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1200/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/device-motion-2.jpg 1200w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1600/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/device-motion-2.jpg 1600w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_2000/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/device-motion-2.jpg 2000w"
			src="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/device-motion-2.jpg"
			
			sizes="100vw"
			alt="Cube rotated according to emulated device orientation"
		/>
    
    </a>
  

  
    <figcaption class="op-vertical-bottom">
      (<a href='https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/device-motion-2.jpg'>Large preview</a>)
    </figcaption>
  
</figure>

<h2 id="3-vibration-api">3. Vibration API</h2>

<p>Let’s turn our attention to the Vibration API, which, unsurprisingly, allows access to a device’s vibrating mechanism. This comes in handy when we need to alert users with in-app notifications, like when a process is finished or a message is received. That said, we have to use it sparingly; no one wants their phone blowing up with notifications.</p>

<p>There’s just one method that the Vibration API gives us, and it’s all we need: <code>navigator.vibrate()</code>.</p>

<p><code>vibrate()</code> is available globally from the <code>navigator</code> object and takes an argument for how long a vibration lasts in milliseconds. It can be either a number or an array of numbers representing a patron of vibrations and pauses.</p>

<div class="break-out">
<pre><code class="language-javascript">navigator.vibrate(200); // vibrate 200ms
navigator.vibrate([200, 100, 200]); // vibrate 200ms, wait 100, and vibrate 200ms.
</code></pre>
</div>

<h3 id="browser-support-2">Browser Support</h3>














<figure class="
  
    break-out article__image
  
  
  ">
  
    <a href="https://caniuse.com/vibration">
    
    <img
      loading="lazy"
      decoding="async"
      fetchpriority="low"
			width="800"
			height="290"
			
			srcset="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/vibration-api-support.jpg 400w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_800/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/vibration-api-support.jpg 800w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1200/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/vibration-api-support.jpg 1200w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1600/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/vibration-api-support.jpg 1600w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_2000/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/vibration-api-support.jpg 2000w"
			src="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/vibration-api-support.jpg"
			
			sizes="100vw"
			alt="Browser Support on Vibration API"
		/>
    
    </a>
  

  
    <figcaption class="op-vertical-bottom">
      Source: <a href='https://caniuse.com/vibration'>Caniuse</a>. (<a href='https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/vibration-api-support.jpg'>Large preview</a>)
    </figcaption>
  
</figure>

<h3 id="vibration-api-demo">Vibration API Demo</h3>

<p>Let’s make a quick demo where the user inputs how many milliseconds they want their device to vibrate and buttons to start and stop the vibration, starting with the markup:</p>

<pre><code class="language-html">&lt;main&gt;
  &lt;form&gt;
    &lt;label for="milliseconds-input"&gt;Milliseconds:&lt;/label&gt;
    &lt;input type="number" id="milliseconds-input" value="0" /&gt;
  &lt;/form&gt;

  &lt;button class="vibrate-button"&gt;Vibrate&lt;/button&gt;
  &lt;button class="stop-vibrate-button"&gt;Stop&lt;/button&gt;
&lt;/main&gt;
</code></pre>

<p>We’ll add an event listener for a click and invoke the <code>vibrate()</code> method:</p>

<div class="break-out">
<pre><code class="language-javascript">const vibrateButton = document.querySelector(".vibrate-button");
const millisecondsInput = document.querySelector("#milliseconds-input");

vibrateButton.addEventListener("click", () =&gt; {
  navigator.vibrate(millisecondsInput.value);
});
</code></pre>
</div>

<p>To stop vibrating, we override the current vibration with a zero-millisecond vibration.</p>

<div class="break-out">
<pre><code class="language-javascript">const stopVibrateButton = document.querySelector(".stop-vibrate-button");

stopVibrateButton.addEventListener("click", () =&gt; {
  navigator.vibrate(0);
});
</code></pre>
</div>

<div class="partners__lead-place"></div>

<h2 id="4-contact-picker-api">4. Contact Picker API</h2>

<p>In the past, it used to be that only native apps could connect to a device’s “contacts”. But now we have the fourth and final API I want to look at: the <a href="https://w3c.github.io/contact-picker/"><strong>Contact Picker API</strong></a>.</p>

<p>The API grants web apps access to the device’s contact lists. Specifically, we get the <code>contacts.select()</code> async method available through the <code>navigator</code> object, which takes the following two arguments:</p>

<ul>
<li><strong><code>properties</code>:</strong> This is an array containing the information we want to fetch from a contact card, e.g., <code>&quot;name&quot;</code>, <code>&quot;address&quot;</code>, <code>&quot;email&quot;</code>, <code>&quot;tel&quot;</code>, and <code>&quot;icon&quot;</code>.</li>
<li><strong><code>options</code>:</strong> This is an object that can only contain the <code>multiple</code> boolean property to define whether or not the user can select one or multiple contacts at a time.</li>
</ul>

<h3 id="browser-support-3">Browser Support</h3>

<p>I’m afraid that browser support is next to zilch on this one, limited to Chrome Android, Samsung Internet, and Android’s native web browser at the time I’m writing this.</p>














<figure class="
  
    break-out article__image
  
  
  ">
  
    <a href="https://caniuse.com/mdn-api_contactsmanager">
    
    <img
      loading="lazy"
      decoding="async"
      fetchpriority="low"
			width="800"
			height="301"
			
			srcset="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/contacts-manager-api-support.jpg 400w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_800/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/contacts-manager-api-support.jpg 800w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1200/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/contacts-manager-api-support.jpg 1200w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1600/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/contacts-manager-api-support.jpg 1600w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_2000/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/contacts-manager-api-support.jpg 2000w"
			src="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/contacts-manager-api-support.jpg"
			
			sizes="100vw"
			alt="Browser Support on Contacts Manager API"
		/>
    
    </a>
  

  
    <figcaption class="op-vertical-bottom">
      Source: <a href='https://caniuse.com/mdn-api_contactsmanager'>Caniuse</a>. (<a href='https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/contacts-manager-api-support.jpg'>Large preview</a>)
    </figcaption>
  
</figure>

<h3 id="selecting-user-s-contacts">Selecting User’s Contacts</h3>

<p>We will make another demo to select and display the user’s contacts on the page. Again, starting with the HTML:</p>

<pre><code class="language-html">&lt;main&gt;
  &lt;button class="get-contacts"&gt;Get Contacts&lt;/button&gt;
  &lt;p&gt;Contacts:&lt;/p&gt;
  &lt;ul class="contact-list"&gt;
    &lt;!-- We’ll inject a list of contacts --&gt;
  &lt;/ul&gt;
&lt;/main&gt;
</code></pre>

<p>Then, in JavaScript, we first construct our elements from the DOM and choose which properties we want to pick from the contacts.</p>

<div class="break-out">
<pre><code class="language-javascript">const getContactsButton = document.querySelector(".get-contacts");
const contactList = document.querySelector(".contact-list");

const props = ["name", "tel", "icon"];
const options = {multiple: true};
</code></pre>
</div>

<p>Now, we asynchronously pick the contacts when the user clicks the <code>getContactsButton</code>.</p>

<div class="break-out">
<pre><code class="language-javascript">
const getContacts = async () =&gt; {
  try {
    const contacts = await navigator.contacts.select(props, options);
  } catch (error) {
    console.error(error);
  }
};

getContactsButton.addEventListener("click", getContacts);
</code></pre>
</div>

<p>Using DOM manipulation, we can then append a list item to each contact and an icon to the <code>contactList</code> element.</p>

<div class="break-out">
<pre><code class="language-javascript">const appendContacts = (contacts) =&gt; {
  contacts.forEach(({name, tel, icon}) =&gt; {
    const contactElement = document.createElement("li");

    contactElement.innerText = `${name}: ${tel}`;
    contactList.appendChild(contactElement);
  });
};

const getContacts = async () =&gt; {
  try {
    const contacts = await navigator.contacts.select(props, options);
    appendContacts(contacts);
  } catch (error) {
    console.error(error);
  }
};

getContactsButton.addEventListener("click", getContacts);
</code></pre>
</div>

<p>Appending an image is a little tricky since we will need to convert it into a URL and append it for each item in the list.</p>

<div class="break-out">
<pre><code class="language-javascript">const getIcon = (icon) =&gt; {
  if (icon.length &gt; 0) {
    const imageUrl = URL.createObjectURL(icon[0]);
    const imageElement = document.createElement("img");
    imageElement.src = imageUrl;

    return imageElement;
  }
};

const appendContacts = (contacts) =&gt; {
  contacts.forEach(({name, tel, icon}) =&gt; {
    const contactElement = document.createElement("li");

    contactElement.innerText = `${name}: ${tel}`;
    contactList.appendChild(contactElement);

    const imageElement = getIcon(icon);
    contactElement.appendChild(imageElement);
  });
};

const getContacts = async () =&gt; {
  try {
    const contacts = await navigator.contacts.select(props, options);
    appendContacts(contacts);
  } catch (error) {
    console.error(error);
  }
};

getContactsButton.addEventListener("click", getContacts);
</code></pre>
</div>

<p>And here’s the outcome:</p>














<figure class="
  
  
  ">
  
    <a href="https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/contact-picker-1.png">
    
    <img
      loading="lazy"
      decoding="async"
      fetchpriority="low"
			width="800"
			height="780"
			
			srcset="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/contact-picker-1.png 400w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_800/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/contact-picker-1.png 800w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1200/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/contact-picker-1.png 1200w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_1600/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/contact-picker-1.png 1600w,
			        https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_2000/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/contact-picker-1.png 2000w"
			src="https://res.cloudinary.com/indysigner/image/fetch/f_auto,q_80/w_400/https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/contact-picker-1.png"
			
			sizes="100vw"
			alt="Contact Picker showing three mock contacts"
		/>
    
    </a>
  

  
    <figcaption class="op-vertical-bottom">
      (<a href='https://files.smashing.media/articles/uniting-web-native-apps-unknown-javascript-apis/contact-picker-1.png'>Large preview</a>)
    </figcaption>
  
</figure>

<p><strong>Note</strong>: <strong><em>The Contact Picker API will only work if the context is secure</em></strong>, <em>i.e., the page is served over <code>https://</code> or <code>wss://</code> URLs.</em></p>

<h2 id="conclusion">Conclusion</h2>

<p>There we go, four web APIs that I believe would empower us to <strong>build more useful and robust PWAs</strong> but have slipped under the radar for many of us. This is, of course, due to inconsistent browser support, so I hope this article can bring awareness to new APIs so we have a better chance to see them in future browser updates.</p>

<p>Aren’t they interesting? We saw how much control we have with the orientation of a device and its screen as well as the level of access we get to access a device’s hardware features, i.e. vibration, and information from other apps to use in our own UI.</p>

<p>But as I said much earlier, there’s a sort of infinite loop where <strong>a lack of awareness begets a lack of browser support</strong>. So, while the four APIs we covered are super interesting, your mileage will inevitably vary when it comes to using them in a production environment. Please tread cautiously and refer to <a href="https://caniuse.com">Caniuse</a> for the latest support information, or check for your own devices using <a href="https://webapicheck.com/">WebAPI Check</a>.</p>

<div class="signature">
  <img src="https://www.smashingmagazine.com/images/logo/logo--red.png" alt="Smashing Editorial" width="35" height="46" loading="lazy" decoding="async" />
  <span>(gg, yk)</span>
</div>


              </article>
            </body>
          </html>
        ]]></content:encoded></item></channel></rss>