Bookmark this page. Use Ctrl+F (or Cmd+F on Mac) to find what you need. This cheat sheet covers modern JavaScript (ES6+) and TypeScript essentials. Try examples at typescriptlang.org/play.

Last updated: March 2026

Variables

const name = "Alex";     // constant — cannot reassign
let count = 0;           // block-scoped — can reassign
// var — avoid (function-scoped, hoisted, error-prone)

TypeScript Types

// Basic types
let name: string = "Alex";
let age: number = 25;
let active: boolean = true;
let items: string[] = ["a", "b"];
let tuple: [string, number] = ["Alex", 25];
let anything: any = "skip type checking";   // avoid
let safe: unknown = "must check before use"; // safer than any

// Type inference — no annotation needed when obvious
const name = "Alex";      // TypeScript infers string

// Union types
let id: string | number = "abc";

// Literal types
type Direction = "north" | "south" | "east" | "west";

// Interfaces
interface User {
    name: string;
    age: number;
    email?: string;        // optional
    readonly id: number;   // cannot modify after creation
}

// Type aliases
type Point = { x: number; y: number };
type StringOrNumber = string | number;

// Generics
function first<T>(items: T[]): T | undefined {
    return items[0];
}

Utility Types

TypeDescriptionExample
Partial<T>All properties optionalPartial<User>
Required<T>All properties requiredRequired<User>
Pick<T, K>Select propertiesPick<User, "name" | "email">
Omit<T, K>Remove propertiesOmit<User, "id">
Record<K, V>Key-value map typeRecord<string, number>
Readonly<T>All properties readonlyReadonly<User>
ReturnType<F>Function return typeReturnType<typeof fn>
Parameters<F>Function parameter typesParameters<typeof fn>

Functions

// Arrow function
const greet = (name: string): string => `Hello ${name}`;

// Default parameters
const greet = (name = "World") => `Hello ${name}`;

// Rest parameters
const sum = (...nums: number[]) => nums.reduce((a, b) => a + b, 0);

// Destructured parameters
const greet = ({ name, age }: User) => `${name}, ${age}`;

// Function overloads (TypeScript)
function format(value: string): string;
function format(value: number): string;
function format(value: string | number): string {
    return String(value);
}

Strings

const name = "Alex";
`Hello ${name}`                    // template literal
`Total: ${price * 1.2}`           // expression
`Line 1
Line 2`                            // multi-line

"hello".toUpperCase()              // "HELLO"
"hello".includes("ell")            // true
"hello".startsWith("he")           // true
"hello world".split(" ")           // ["hello", "world"]
"  hello  ".trim()                 // "hello"
"hello".padStart(10, ".")          // ".....hello"
"hello".repeat(3)                  // "hellohellohello"
"hello".at(-1)                     // "o" (last char)
"hello".replaceAll("l", "r")      // "herro"

Arrays

const nums = [1, 2, 3, 4, 5];

// Transform
nums.map(x => x * 2)              // [2, 4, 6, 8, 10]
nums.filter(x => x > 2)           // [3, 4, 5]
nums.reduce((sum, x) => sum + x, 0) // 15
[1, [2, 3], [4, 5]].flat()         // flatten nested arrays: [1, 2, 3, 4, 5]
nums.flatMap(x => [x, x * 10])    // [1, 10, 2, 20, ...]

// Search
nums.find(x => x > 3)             // 4
nums.findIndex(x => x > 3)        // 3
nums.includes(3)                   // true
nums.some(x => x > 4)             // true
nums.every(x => x > 0)            // true
nums.indexOf(3)                    // 2

// Modify
nums.push(6)                      // add to end
nums.pop()                        // remove from end
nums.unshift(0)                   // add to start
nums.shift()                      // remove from start
nums.splice(1, 2)                 // remove 2 items at index 1
nums.slice(1, 3)                  // [2, 3] (no mutation)

// Sort
nums.sort((a, b) => a - b)        // ascending (MUTATES original!)
nums.sort((a, b) => b - a)        // descending (MUTATES original!)
nums.toSorted((a, b) => a - b)    // new sorted array (no mutation, ES2023+)
nums.toReversed()                  // new reversed array

// Create
Array.from({ length: 5 }, (_, i) => i)  // [0, 1, 2, 3, 4]
Array.from("hello")                // ["h", "e", "l", "l", "o"]
[...new Set(nums)]                 // remove duplicates

Objects

// Destructuring
const { name, age } = user;
const { name, ...rest } = user;    // rest = everything except name

// Spread
const updated = { ...user, age: 26 };   // clone + update
const merged = { ...obj1, ...obj2 };     // merge

// Computed property names
const key = "name";
const obj = { [key]: "Alex" };     // { name: "Alex" }

// Optional chaining
user?.address?.city                // undefined if any is null/undefined
user?.getName?.()                  // call method if it exists

// Nullish coalescing
const name = user.name ?? "Unknown";  // "Unknown" only if null/undefined
// Unlike ||, does NOT fall back on "" or 0 or false

// Logical assignment operators (ES2021)
x ??= 10;    // x = x ?? 10 (assign if null/undefined)
x &&= 10;    // x = x && 10 (assign if truthy)
x ||= 10;    // x = x || 10 (assign if falsy)

// Object methods
Object.keys(obj)                   // ["name", "age"]
Object.values(obj)                 // ["Alex", 25]
Object.entries(obj)                // [["name", "Alex"], ["age", 25]]
Object.fromEntries(entries)        // back to object
Object.assign({}, obj1, obj2)     // merge (older syntax)

Async/Await

// Async function
async function fetchUser(id: number): Promise<User> {
    const response = await fetch(`/api/users/${id}`);
    if (!response.ok) throw new Error("Failed to fetch");
    return response.json();
}

// Error handling
try {
    const user = await fetchUser(1);
} catch (error) {
    console.error("Error:", error);
}

// Parallel execution
const [users, posts] = await Promise.all([
    fetchUsers(),
    fetchPosts()
]);

// Race — first to resolve wins
const result = await Promise.race([fetchData(), timeout(5000)]);

// Promise.allSettled — wait for all, never rejects
const results = await Promise.allSettled([fetchA(), fetchB()]);
results.forEach(r => {
    if (r.status === "fulfilled") console.log(r.value);
    if (r.status === "rejected") console.log(r.reason);
});

Modules

// Named exports
export const API_URL = "https://api.example.com";
export function fetchData() { }

// Default export
export default class UserService { }

// Import
import UserService from "./user-service";
import { API_URL, fetchData } from "./api";
import * as api from "./api";

// Dynamic import (lazy loading)
const module = await import("./heavy-module");

Classes (TypeScript)

class User {
    private id: number;
    public name: string;
    readonly email: string;

    constructor(id: number, name: string, email: string) {
        this.id = id;
        this.name = name;
        this.email = email;
    }

    // Shorthand constructor
    // constructor(private id: number, public name: string) {}

    greet(): string {
        return `Hi, I'm ${this.name}`;
    }
}

// Abstract class
abstract class Shape {
    abstract area(): number;
}

class Circle extends Shape {
    constructor(private radius: number) { super(); }
    area(): number { return Math.PI * this.radius ** 2; }
}

Type Guards (TypeScript)

// typeof
if (typeof value === "string") {
    value.toUpperCase();   // TypeScript knows it's string
}

// instanceof
if (error instanceof TypeError) {
    error.message;          // TypeScript knows it's TypeError
}

// Custom type guard
function isUser(obj: unknown): obj is User {
    return (
        typeof obj === "object" &&
        obj !== null &&
        "name" in obj &&
        "age" in obj &&
        "id" in obj
    );
}

// Discriminated union
type Result =
    | { status: "success"; data: string }
    | { status: "error"; message: string };

function handle(result: Result) {
    if (result.status === "success") {
        result.data;        // TypeScript knows data exists
    }
}

Modern TypeScript Features

// satisfies — validate type without widening
const config = {
    port: 3000,
    host: "localhost"
} satisfies Record<string, string | number>;
// config.port is still number (not string | number)

// as const — immutable literal type
const COLORS = ["red", "green", "blue"] as const;
type Color = typeof COLORS[number]; // "red" | "green" | "blue"

// template literal types
type EventName = `on${Capitalize<string>}`;  // "onClick", "onHover", etc.

Common Mistakes

  1. == vs ===== does type coercion ("1" == 1 is true). Always use === for strict equality. The only exception: value == null checks both null and undefined.

  2. this in callbacksthis inside a regular function depends on how it was called. Arrow functions capture this from the surrounding scope. Use arrow functions in callbacks and event handlers.

  3. Unhandled promise rejections — Every await should be in a try/catch, and every .then() should have a .catch(). Unhandled rejections crash Node.js and silently fail in browsers.

  4. ?? vs || confusion|| falls back on any falsy value ("", 0, false, null, undefined). ?? only falls back on null and undefined. Use ?? when 0 or "" are valid values: const port = config.port ?? 3000.