Block-scoped constant
Variables · Pattern / syntaxconst x = 10 Search code, tasks or categories in English or Spanish. Each entry has a link to save or share it.
Showing 79 of 79 snippets
Modern JavaScript. Patterns need your application variables; DOM needs a browser and import/export a module. Complete examples include their own data.
const x = 10 let y = 20 typeof x const { a, b } = obj const [a, b] = arr const merged = { ...obj1, ...obj2 } const copy = [...arr] x ?? fallback obj?.prop?.nested [1, 2, 3] arr.push(item) arr.pop() arr.shift();
arr.unshift(item); Two separate operations; both mutate arr.
arr.map(x => x * 2) arr.filter(x => x > 0) arr.reduce((acc, x) => acc + x, 0) arr.find(x => x.id === 1) arr.findIndex(x => x > 5) arr.some(x => x > 0) arr.every(x => x > 0) arr.includes(item) arr.flat(Infinity) const numbers = [10, 2, 1];
const sorted = [...numbers].sort((a, b) => a - b);
console.log(sorted); // [1, 2, 10]
console.log(numbers); // [10, 2, 1] sort() mutates its receiver. Copy first to preserve the input; without a comparator, sorting uses strings.
Documentationarr.slice(1, 3) arr.splice(1, 2, ...items) [...new Set(arr)] Array.from({ length: 5 }, (_, i) => i) const obj = { key: "value" } Object.keys(obj) Object.values(obj) Object.entries(obj) Object.assign({}, obj1, obj2) structuredClone(obj) Supports structured-cloneable values, not functions or DOM nodes; unsupported values throw DataCloneError.
DocumentationObject.freeze(obj) "key" in obj delete obj.key const { unwanted, ...rest } = obj function fn(x) { return x } const fn = (x) => x * 2 const fn = (x = 10) => x const fn = (...args) => args fn(1, ...arr) setTimeout(fn, 1000) setInterval(fn, 1000) function* gen() { yield 1 } async function fetchJson(url) {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
} Pass a JSON endpoint and handle rejection at the call site. Browser requests must satisfy CORS.
Documentationfetch(url)
.then(r => {
if (!r.ok) throw new Error(`HTTP ${r.status}`);
return r.json();
})
.then(console.log)
.catch(console.error); Promise.all([p1, p2]) Promise.race([p1, p2]) Promise.allSettled([p1, p2]) const promise = new Promise(resolve => {
setTimeout(() => resolve(42), 100);
});
promise.then(console.log); // 42 try {
await fn();
} catch (e) {
console.error(e);
} `Hello ${name}` s.includes("sub") s.startsWith("pre");
s.endsWith("suf"); Each expression returns its own boolean.
s.split(",") s.trim() s.replace(/regex/g, "new") s.padStart(5, "0") s.repeat(3) s.match(/pattern/g) s.at(-1) document.querySelector(".class") document.querySelectorAll("div") el.addEventListener("click", fn) el.classList.add("active") el.classList.toggle("hidden") el.textContent = "text" el.setAttribute("data-id", "5") el.style.color = "red" el.remove() const m = new Map() const s = new Set([1, 2, 3]) for (const [k, v] of map) {} for (const item of iterable) {} Symbol("desc") import { fn } from "./module.js" export default fn const proxy = new Proxy(target, handler) Find JavaScript syntax for arrays, objects, functions, promises, strings and the DOM. Search categories in English or Spanish, copy code or link directly to an entry. Complete examples include data; patterns need variables from your application.
Numeric sorting needs a comparator. sort() changes the array it is called on; the complete example copies the input first. fetch() can fulfill on an HTTP error, so check response.ok before reading JSON. DOM snippets run in a browser, while import and export require a module. Spread and Object.assign make shallow copies.
Free. No signup. Your inputs stay in your browser. Ads via Google AdSense (consent required).
By Marco B. ·