JavaScript Example Index

All JavaScript Snippets

Browse every JavaScript snippet on DuskTools in one place, from fetch patterns and debounce helpers to CSV conversion, localStorage, UUID generation, and regular expression usage. This page is built for discovery, letting search engines and developers reach the full library from a single hub.

Each snippet page includes copy-ready code, an explanation of what each part does, expected output, and related DuskTools links so you can move from learning to shipping without leaving the site.

Snippet pages

20

Snippet categories

9

Related hubs

6

Useful Companion Hubs

HTTP & Async

Useful fetch and promise patterns for network-heavy app code.

3 snippets
Fetch GET Request

Make a GET request using the Fetch API.

HTTP & Async
const response = await fetch("https://api.example.com/users");
const data = await response.json();

if (!response.ok) {
  throw new Error(`HTTP ${response.status}`);
}
console.log(data);
Fetch POST with JSON Body

Send a POST request with a JSON payload.

HTTP & Async
const response = await fetch("https://api.example.com/users", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "Alice", age: 30 })
});

const data = await response.json();
console.log(data);
Promise.all Patterns

Run multiple promises in parallel and handle results.

HTTP & Async
// Wait for all
const [a, b, c] = await Promise.all([
  fetch("/api/a").then((r) => r.json()),
  fetch("/api/b").then((r) => r.json()),
  fetch("/api/c").then((r) => r.json())
]);

// Fail if any fails
Promise.all([p1, p2]).catch((err) => console.error(err));

// All settled (never rejects)
const results = await Promise.allSettled([p1, p2]);
results.forEach((r) => {
  if (r.status === "fulfilled") console.log(r.value);
  else console.error(r.reason);
});

Functions & Events

Timing, delegation, and handler patterns that appear in real UIs.

3 snippets
Debounce Implementation

Delay function execution until after a pause in calls.

Functions & Events
function debounce(fn, delay) {
  let timeoutId;
  return function (...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => fn.apply(this, args), delay);
  };
}

const debouncedSearch = debounce((q) => console.log("Search:", q), 300);
debouncedSearch("a");
debouncedSearch("ab");
debouncedSearch("abc");  // Only this runs after 300ms
Throttle Implementation

Limit function execution to once per time interval.

Functions & Events
function throttle(fn, limit) {
  let inThrottle;
  return function (...args) {
    if (!inThrottle) {
      fn.apply(this, args);
      inThrottle = true;
      setTimeout(() => (inThrottle = false), limit);
    }
  };
}

const throttledScroll = throttle(() => console.log("scroll"), 1000);
Event Delegation

Use a single listener for dynamic child elements.

Functions & Events
document.getElementById("list").addEventListener("click", (e) => {
  const item = e.target.closest("[data-id]");
  if (!item) return;
  console.log("Clicked:", item.dataset.id);
});

// HTML: <ul id="list">
//   <li data-id="1">Item 1</li>
//   <li data-id="2">Item 2</li>
// </ul>

Objects & Data

Practical object manipulation snippets for copying and transforming data.

1 snippets
Deep Clone Object

Create a deep copy using structuredClone or JSON.

Objects & Data
// Modern: structuredClone (Node 17+, browsers)
const cloned = structuredClone(obj);

// Fallback: JSON (loses functions, undefined, Date)
const cloned2 = JSON.parse(JSON.stringify(obj));

// Shallow clone
const shallow = { ...obj };

Arrays & Collections

Array helpers you can paste into dashboards, scripts, and utilities.

4 snippets
Flatten Array

Flatten nested arrays using flat() or recursion.

Arrays & Collections
// One level: flat()
const arr = [1, [2, 3], [4, 5]];
console.log(arr.flat());  // [1, 2, 3, 4, 5]

// Any depth: flat(Infinity)
const nested = [1, [2, [3, [4]]]];
console.log(nested.flat(Infinity));  // [1, 2, 3, 4]

// Recursive
function flatten(arr) {
  return arr.reduce((acc, x) =>
    Array.isArray(x) ? acc.concat(flatten(x)) : acc.concat(x), []);
}
Remove Duplicates with Set

Deduplicate an array using Set.

Arrays & Collections
const arr = [1, 2, 2, 3, 1, 4, 3];

// Simple (order may change for primitives)
const unique = [...new Set(arr)];
console.log(unique);  // [1, 2, 3, 4]

// Preserve order for objects (by key)
const seen = new Set();
const filtered = arr.filter((x) => {
  const key = JSON.stringify(x);
  if (seen.has(key)) return false;
  seen.add(key);
  return true;
});
Sort Array of Objects

Sort an array by object properties with Array.sort().

Arrays & Collections
const users = [
  { name: "Alice", age: 30 },
  { name: "Bob", age: 25 },
  { name: "Carol", age: 35 }
];

// By age ascending
users.sort((a, b) => a.age - b.age);

// By name (string)
users.sort((a, b) => a.name.localeCompare(b.name));

// Immutable sort (new array)
const sorted = [...users].sort((a, b) => a.age - b.age);
Group By

Group array items by a key using Object.groupBy or reduce.

Arrays & Collections
const items = [
  { type: "fruit", name: "apple" },
  { type: "veg", name: "carrot" },
  { type: "fruit", name: "banana" }
];

// Object.groupBy (ES2024)
const byType = Object.groupBy(items, (i) => i.type);

// Reduce (universal)
const byType2 = items.reduce((acc, item) => {
  const key = item.type;
  if (!acc[key]) acc[key] = [];
  acc[key].push(item);
  return acc;
}, {});

Browser APIs

Snippets that work directly with built-in browser capabilities.

3 snippets
Parse Query String with URLSearchParams

Parse and manipulate URL query parameters.

Browser APIs
const url = new URL("https://example.com?foo=bar&baz=qux");
const params = url.searchParams;

console.log(params.get("foo"));     // "bar"
console.log(params.getAll("tag"));   // ["a", "b"] if ?tag=a&tag=b
params.append("new", "value");
console.log(params.toString());     // "foo=bar&baz=qux&new=value"

// From string only
const p = new URLSearchParams("?a=1&b=2");
console.log(Object.fromEntries(p));  // { a: "1", b: "2" }
localStorage Get/Set/Remove

Persist data in the browser with localStorage.

Browser APIs
// Set
localStorage.setItem("user", JSON.stringify({ name: "Alice" }));

// Get
const user = JSON.parse(localStorage.getItem("user") ?? "{}");
console.log(user.name);

// Remove
localStorage.removeItem("user");

// Clear all
localStorage.clear();

// Key and length
console.log(localStorage.key(0), localStorage.length);
Lazy Loading with IntersectionObserver

Load content when it enters the viewport.

Browser APIs
const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      const img = entry.target;
      img.src = img.dataset.src || img.src;
      observer.unobserve(img);
    }
  });
}, { rootMargin: "50px" });

document.querySelectorAll("img[data-src]").forEach((el) => observer.observe(el));

Dates & Identifiers

Formatting and identifier helpers for everyday app plumbing.

2 snippets
Format Date with Intl.DateTimeFormat

Format dates for different locales and styles.

Dates & Identifiers
const date = new Date("2024-03-07");

// Locale-aware
console.log(new Intl.DateTimeFormat("en-US").format(date));
// "3/7/2024"

console.log(new Intl.DateTimeFormat("en-GB", {
  dateStyle: "full",
  timeStyle: "short"
}).format(date));
// "Thursday, 7 March 2024 at 00:00"
Generate UUID with crypto.randomUUID

Create a UUID v4 using the Web Crypto API.

Dates & Identifiers
// Modern (Node 19+, browsers)
const uuid = crypto.randomUUID();
console.log(uuid);  // "550e8400-e29b-41d4-a716-446655440000"

// Fallback
function uuidFallback() {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
    const r = (Math.random() * 16) | 0;
    const v = c === "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

Strings & Encoding

Common text transformation utilities that pair well with developer tools.

1 snippets
Base64 Encode/Decode

Encode and decode strings with btoa/atob.

Strings & Encoding
// Encode
const encoded = btoa("Hello, World!");
console.log(encoded);  // "SGVsbG8sIFdvcmxkIQ=="

// Decode
const decoded = atob(encoded);
console.log(decoded);  // "Hello, World!"

// Unicode: use TextEncoder/TextDecoder
const enc = btoa(unescape(encodeURIComponent("日本語")));
const dec = decodeURIComponent(escape(atob(enc)));

Strings & Parsing

Text extraction and parsing examples where regex and strings overlap.

1 snippets

Data Conversion

Short conversion patterns for CSV and JSON workflow tasks.

2 snippets
Parse CSV String

Convert a CSV string to an array of objects.

Data Conversion
function csvToJson(csv) {
  const lines = csv.trim().split("\n");
  const headers = lines[0].split(",");
  return lines.slice(1).map((line) => {
    const values = line.split(",");
    return headers.reduce((obj, h, i) => {
      obj[h.trim()] = values[i]?.trim() ?? "";
      return obj;
    }, {});
  });
}

const csv = "name,age\nAlice,30\nBob,25";
console.log(csvToJson(csv));
Convert JSON Array to CSV

Convert an array of objects to a CSV string.

Data Conversion
function jsonToCsv(arr) {
  if (arr.length === 0) return "";
  const headers = Object.keys(arr[0]);
  const rows = arr.map((obj) =>
    headers.map((h) => `"${String(obj[h] ?? "").replace(/"/g, '""')}"`).join(",")
  );
  return [headers.join(","), ...rows].join("\n");
}

const data = [{ name: "Alice", age: 30 }, { name: "Bob", age: 25 }];
console.log(jsonToCsv(data));

Continue Exploring

Keep moving through the content graph with related hub pages for regex, CSS, references, and the complete DuskTools directory.