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]

Sorting

// sort numbers ascending
array.sort((a, b) => a - b);

// sort strings ascending
array.sort((a, b) => {
    if (a < b) {
        return -1;
    }

    if (a > b) {
        return 1;
    }

    return 0;
});

Maps

const map = new Map();
map.set(key, value);
map.get(value); // undefined if not found
const entries = Array.from(map.entries());

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