JavaScript Cheat Sheet

Core JavaScript syntax, functions, classes, modules, and everyday language patterns.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Basics and Syntax
Log a value
console.log(value);

# Print a value to the console.

Declare block-scoped variables
const name = "Ada";
let count = 0;
Template literal interpolation
const msg = `Hello, ${user.name}!`;
Default function parameters
function greet(name = "friend") {
  return `Hello, ${name}`;
}
Optional chaining
const city = user?.profile?.address?.city;
Nullish coalescing
const pageSize = input ?? 25;
Object destructuring
const { id, email, role = "user" } = account;
Array destructuring
const [first, second, ...rest] = values;
Object spread merge
const merged = { ...defaults, ...overrides };
Rest parameters
function sum(...nums) {
  return nums.reduce((acc, n) => acc + n, 0);
}
## Control Flow
If / else statement
if (score >= 90) {
  grade = "A";
} else {
  grade = "B";
}
Ternary operator
const label = isActive ? "Enabled" : "Disabled";
Switch statement
switch (status) {
  case "draft":
    return "gray";
  case "published":
    return "green";
  default:
    return "blue";
}
for...of loop
for (const item of items) {
  console.log(item);
}
for...in loop
for (const key in object) {
  console.log(key, object[key]);
}
Array forEach
items.forEach((item, index) => {
  console.log(index, item);
});
try / catch / finally
try {
  riskyOperation();
} catch (err) {
  console.error(err.message);
} finally {
  cleanup();
}
Throw an error
throw new Error("Invalid input");
## Functions and Closures
Function declaration
function add(a, b) {
  return a + b;
}
Arrow function
const double = (n) => n * 2;
Immediately-invoked function expression
(() => {
  console.log("Runs immediately");
})();
Pass a callback
function runTask(task, onDone) {
  const result = task();
  onDone(result);
}
Closure counter
function createCounter() {
  let count = 0;
  return () => ++count;
}
Bind function context
const bound = handler.bind(context);
call vs apply
fn.call(ctx, a, b);
fn.apply(ctx, [a, b]);
Currying pattern
const multiply = (a) => (b) => a * b;
Simple memoize helper
function memoize(fn) {
  const cache = new Map();
  return (...args) => {
    const key = JSON.stringify(args);
    if (cache.has(key)) return cache.get(key);
    const value = fn(...args);
    cache.set(key, value);
    return value;
  };
}
## Sets, Maps, and Typed Data
Create a Map
const map = new Map([["id", 1], ["name", "Ada"]]);
Create a Set
const unique = new Set([1, 2, 2, 3]);
Set and get Map values
map.set("email", "ada@example.com");
const email = map.get("email");
Check Set membership
const hasAdmin = roles.has("admin");
Object keys, values, entries
Object.keys(user);
Object.values(user);
Object.entries(user);
Object.fromEntries
const obj = Object.fromEntries([["a", 1], ["b", 2]]);
Convert Set to array
const arr = [...unique];
// or Array.from(unique)
TypedArray example
const bytes = new Uint8Array([72, 73]);
## Classes and Prototypes
Basic class
class User {
  constructor(name) {
    this.name = name;
  }

  greet() {
    return `Hi, ${this.name}`;
  }
}
Class inheritance
class Admin extends User {
  constructor(name, role) {
    super(name);
    this.role = role;
  }
}
Static method
class MathUtil {
  static clamp(n, min, max) {
    return Math.min(Math.max(n, min), max);
  }
}
Private class fields
class Counter {
  #count = 0;
  inc() {
    return ++this.#count;
  }
}
Getters and setters
class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }
  get area() {
    return this.width * this.height;
  }
}
Add a prototype method
User.prototype.isNamed = function (value) {
  return this.name === value;
};
## Modules and Packaging
Named export
export function slugify(text) {
  return text.toLowerCase().replaceAll(" ", "-");
}
Default export
export default class ApiClient {}
Import named members
import { slugify } from "./slugify.js";
Import default export
import ApiClient from "./api-client.js";
Namespace import
import * as math from "./math.js";
Dynamic import
const module = await import("./feature.js");
CommonJS require
const fs = require("node:fs");
Read environment variable
const apiBase = process.env.API_BASE_URL;