All cheat sheets

JavaScript Cheat Sheet

Modern JavaScript quick reference: types, arrays, objects, destructuring, promises, and common idioms.

Languages
javascript
js
language

JavaScript is a high-level, dynamic, multi-paradigm language standardized as ECMAScript. The cheat sheet below targets modern JavaScript (ES2020+) — what runs natively in current browsers and Node.js, with no transpilation needed.

Primitive and reference types

Table
Typetypeof resultExampleNotes
undefined"undefined"let x;Default for uninitialized variables.
null"object"let x = null;Historical quirk; check with === null.
boolean"boolean"true, false
number"number"42, 3.14, NaNIEEE-754 double precision.
bigint"bigint"42nArbitrary precision integer.
string"string""hi", 'hi'UTF-16 sequence; immutable.
symbol"symbol"Symbol("id")Unique, immutable key.
object"object"{}, [], new Date()Reference type. Arrays and functions are objects too.
function"function"function f(){}Callable object.

Variable declarations

Table
KeywordScopeHoistingReassignRedeclare
varFunctionYes, initialized to undefinedYesYes
letBlockYes, but TDZ until declarationYesNo
constBlockYes, but TDZ until declarationNoNo
javascript
const PI = 3.14;          // prefer const by default
let count = 0;            // use let when reassignment is needed
// var is legacy; avoid in new code

Template literals

Backtick-delimited strings with embedded expressions and multi-line support:

javascript
const name = "Ada";
const greeting = `Hello, ${name}!`;
const sql = `
  SELECT *
  FROM users
  WHERE active = ${active}
`;

Tagged templates let you parse the literal:

javascript
const html = String.raw`<a href="${url}">link</a>`; // no escape interpretation

Array methods

Most used on arrays. All return a new array unless noted.

Table
MethodReturnsMutates?One-line behavior
map(fn)new arrayNoTransform each element.
filter(fn)new arrayNoKeep elements where fn returns truthy.
reduce(fn, init)single valueNoAccumulate to a single result.
find(fn)first matchNoFirst element matching predicate (or undefined).
findIndex(fn)numberNoIndex of first match (or -1).
some(fn)booleanNoAt least one element matches.
every(fn)booleanNoAll elements match.
forEach(fn)undefinedNoIterate; cannot break or return early.
sort(fn)same arrayYesIn-place sort; default is lexicographic.
slice(start, end)new arrayNoSub-array from start to end (exclusive).
splice(start, n, ...items)same arrayYesRemove/replace/insert at index.
concat(...)new arrayNoConcatenate arrays/values.
includes(v)booleanNoMembership check.
flat(depth)new arrayNoFlatten nested arrays.
flatMap(fn)new arrayNomap then flat(1).
push(...items)new lengthYesAppend to end.
pop()removed elementYesRemove from end.
javascript
const users = [
  { name: "Ada", age: 36 },
  { name: "Linus", age: 55 },
  { name: "Grace", age: 85 },
];

const adults = users
  .filter(u => u.age >= 18)
  .map(u => u.name)
  .sort();

Object idioms

Shorthand and computed keys

javascript
const name = "Ada";
const user = { name, age: 36 };             // shorthand for { name: name }
const key = "id";
const obj = { [key]: 42 };                  // { id: 42 }

Spread and rest

javascript
const a = { x: 1, y: 2 };
const b = { ...a, y: 20, z: 3 };            // { x: 1, y: 20, z: 3 }
const { x, ...rest } = a;                    // rest = { y: 2 }

const nums = [1, 2, 3];
const more = [...nums, 4, 5];                // [1, 2, 3, 4, 5]
const [head, ...tail] = nums;                // head=1, tail=[2,3]

Destructuring

javascript
// object
const { name, age = 0 } = user;             // default for missing key
const { name: userName } = user;            // rename

// nested
const { address: { city } } = user;

// array
const [first, second, ...rest] = items;

// function parameters
function greet({ name = "stranger" }) { /* ... */ }

Optional chaining and nullish coalescing

javascript
const city = user?.address?.city;            // undefined if any link is null/undefined
const port = config.port ?? 8080;            // default only for null/undefined (not 0 or "")

?? differs from ||: it triggers only on null or undefined, so 0 and "" are preserved.

Functions

Arrow vs regular

Arrow functions are concise and do not bind their own this. Use them for callbacks; use function declarations for object methods that need dynamic this.

javascript
const obj = {
  value: 42,
  regular() { return this.value; },         // 42
  arrow: () => this.value,                  // undefined (lexical this)
};

Common parameters

javascript
function f(a, b = 10, ...rest) { /* ... */ }
const f = (a, b) => a + b;
const f = ({ x, y }) => x * y;

Promises and async/await

A Promise represents an eventual value. Chain with .then / .catch, or use async/await for linear code.

javascript
async function fetchUser(id) {
  try {
    const res = await fetch(`/api/users/${id}`);
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const user = await res.json();
    return user;
  } catch (err) {
    console.error("fetch failed:", err);
    throw err;                                // rethrow or return a fallback
  }
}

Key points:

  • await only works inside an async function (or top-level in modules).
  • await unwraps a single value: it does not auto-flatten arrays of promises. Use Promise.all / Promise.allSettled / Promise.race for that.
  • A try/catch around await handles both synchronous throws and rejected promises.
javascript
const [a, b, c] = await Promise.all([p1(), p2(), p3()]);

Modules

ES modules use import / export. Files need either .mjs extension or "type": "module" in package.json.

javascript
// math.js
export const PI = 3.14;
export function add(a, b) { return a + b; }
export default class Calculator { /* ... */ }

// app.js
import Calculator, { PI, add } from "./math.js";
import * as math from "./math.js";

Dynamic import for code-splitting:

javascript
const { default: Chart } = await import("./chart.js");

Equality and truthiness

Table
ExpressionResult
NaN === NaNfalse
0 === -0true
null == undefinedtrue
null === undefinedfalse
[] == falsetrue
[] === falsefalse

Use === and !== by default. Reach for Object.is(a, b) only when you need to distinguish NaN from NaN or 0 from -0.

References