home blog portfolio Ian Fisher

JavaScript cheatsheet

See also: ref/typescript

Variadic function

function (...args) {
    // ...
}

Clone an object

// 2022 or later
structuredClone(obj)

Number of keys in an object

Object.keys(obj).length

URL query params

const params = new URLSearchParams(window.location.search);
if (params.get("whatever") != null) {
    // ...
}

Spread syntax

[1, 2, 3, ...theRest]

Datetime

const today = new Date();
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);

// WARNING: toISOString() converts from local time to UTC
function iso8601(d) {
    const mm = (d.getMonth() + 1 + "").padStart(2, "0");
    const dd = (d.getDate() + "").padStart(2, "0");
    return `${d.getFullYear()}-${mm}-${dd}`;
}

Regex

See: ref/regex

See also