JavaScript Cheat Sheet
Modern JavaScript quick reference: types, arrays, objects, destructuring, promises, and common idioms.
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
| Type | typeof result | Example | Notes |
|---|---|---|---|
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, NaN | IEEE-754 double precision. |
bigint | "bigint" | 42n | Arbitrary 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
| Keyword | Scope | Hoisting | Reassign | Redeclare |
|---|---|---|---|---|
var | Function | Yes, initialized to undefined | Yes | Yes |
let | Block | Yes, but TDZ until declaration | Yes | No |
const | Block | Yes, but TDZ until declaration | No | No |
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:
const name = "Ada";
const greeting = `Hello, ${name}!`;
const sql = `
SELECT *
FROM users
WHERE active = ${active}
`;
Tagged templates let you parse the literal:
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.
| Method | Returns | Mutates? | One-line behavior |
|---|---|---|---|
map(fn) | new array | No | Transform each element. |
filter(fn) | new array | No | Keep elements where fn returns truthy. |
reduce(fn, init) | single value | No | Accumulate to a single result. |
find(fn) | first match | No | First element matching predicate (or undefined). |
findIndex(fn) | number | No | Index of first match (or -1). |
some(fn) | boolean | No | At least one element matches. |
every(fn) | boolean | No | All elements match. |
forEach(fn) | undefined | No | Iterate; cannot break or return early. |
sort(fn) | same array | Yes | In-place sort; default is lexicographic. |
slice(start, end) | new array | No | Sub-array from start to end (exclusive). |
splice(start, n, ...items) | same array | Yes | Remove/replace/insert at index. |
concat(...) | new array | No | Concatenate arrays/values. |
includes(v) | boolean | No | Membership check. |
flat(depth) | new array | No | Flatten nested arrays. |
flatMap(fn) | new array | No | map then flat(1). |
push(...items) | new length | Yes | Append to end. |
pop() | removed element | Yes | Remove from end. |
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
const name = "Ada";
const user = { name, age: 36 }; // shorthand for { name: name }
const key = "id";
const obj = { [key]: 42 }; // { id: 42 }
Spread and rest
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
// 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
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.
const obj = {
value: 42,
regular() { return this.value; }, // 42
arrow: () => this.value, // undefined (lexical this)
};
Common parameters
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.
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:
awaitonly works inside anasyncfunction (or top-level in modules).awaitunwraps a single value: it does not auto-flatten arrays of promises. UsePromise.all/Promise.allSettled/Promise.racefor that.- A
try/catcharoundawaithandles both synchronous throws and rejected promises.
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.
// 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:
const { default: Chart } = await import("./chart.js");
Equality and truthiness
| Expression | Result |
|---|---|
NaN === NaN | false |
0 === -0 | true |
null == undefined | true |
null === undefined | false |
[] == false | true |
[] === false | false |
Use === and !== by default. Reach for Object.is(a, b) only when you need to distinguish NaN from NaN or 0 from -0.