Make a GET request using the Fetch API.
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);JavaScript Example Index
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 fetch and promise patterns for network-heavy app code.
Make a GET request using the Fetch API.
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);Send a POST request with a JSON payload.
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);Run multiple promises in parallel and handle results.
// 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);
});Timing, delegation, and handler patterns that appear in real UIs.
Delay function execution until after a pause in calls.
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 300msLimit function execution to once per time interval.
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);Use a single listener for dynamic child elements.
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>Practical object manipulation snippets for copying and transforming data.
Create a deep copy using structuredClone or JSON.
// 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 };Array helpers you can paste into dashboards, scripts, and utilities.
Flatten nested arrays using flat() or recursion.
// 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), []);
}Deduplicate an array using Set.
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 an array by object properties with Array.sort().
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 array items by a key using Object.groupBy or reduce.
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;
}, {});Snippets that work directly with built-in browser capabilities.
Parse and manipulate URL query parameters.
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" }Persist data in the browser with localStorage.
// 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);Load content when it enters the viewport.
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));Formatting and identifier helpers for everyday app plumbing.
Format dates for different locales and styles.
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"Create a UUID v4 using the Web Crypto API.
// 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);
});
}Common text transformation utilities that pair well with developer tools.
Encode and decode strings with btoa/atob.
// 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)));Text extraction and parsing examples where regex and strings overlap.
Match and extract text with regular expressions.
const text = "Contact: [email protected] or [email protected]"; const pattern = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g; const matches = text.match(pattern); console.log(matches); // ["[email protected]", "[email protected]"] // With exec const re = new RegExp(pattern); let m; while ((m = re.exec(text)) !== null) { console.log(m[0], m.index); }
Short conversion patterns for CSV and JSON workflow tasks.
Convert a CSV string to an array of objects.
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 an array of objects to a CSV string.
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));Keep moving through the content graph with related hub pages for regex, CSS, references, and the complete DuskTools directory.