JavaScript code examples
18 short, tested snippets. Pick one to see the code with notes, or search Zest for something specific, such as “javascript fetch json (get)”.
- Fetch JSON (GET)const res = await fetch("https://api.example.com/items?q=zest");
- POST JSON with fetchconst res = await fetch("/api/items", {
- map, filter and reduceconst nums = [1, 2, 3, 4];
- Promise.allconst [users, posts] = await Promise.all([
- Destructuring and spreadconst { name, age = 18, ...rest } = person;
- Remove duplicates from an arrayconst unique = [...new Set([3, 1, 3, 2, 1])]; // [3, 1, 2]
- Sort an arraynums.sort((a, b) => a - b); // ascending numbers
- Debounce a functionfunction debounce(fn, ms = 300) {
- Format a dateconst d = new Date();
- Loop over object keys and valuesconst obj = { a: 1, b: 2 };
- Add an event listenerconst btn = document.querySelector("#save");
- localStoragelocalStorage.setItem("theme", "dark");
- Read a file in Node.jsimport { readFile, writeFile } from "node:fs/promises";
- Express hello world serverimport express from "express";
- Optional chaining and nullish coalescingconst city = user?.address?.city ?? "Unknown";
- Copy text to the clipboardawait navigator.clipboard.writeText("copied");
- setTimeout and setIntervalconst t = setTimeout(() => console.log("later"), 1000);
- Hello worldconsole.log("Hello, World!");