Skip to content
Tutorials Center
My learning

Topics

Lesson 150 of 156 ยท Practice and Review

JavaScript Cheat Sheet

A one-page JavaScript cheat sheet - variables, types, operators, functions, objects, array and string methods, classes, async code, modules and the DOM.

This page packs the most-used parts of modern JavaScript onto one screen-friendly sheet. Use it to refresh your memory before an exercise, an interview or a coding session. Each section is short on purpose and links to the full lesson when you want the details.

The examples follow modern style: const by default, let when a value changes, strict equality, and ES2015+ features throughout. A few live editors cover the items that surprise people most often.

Basics

Variables

JavaScript
const name = "Ada";   // can't be reassigned (preferred)
let count = 0;        // can be reassigned
count += 1;
// var: function-scoped and hoisted; avoid in new code

Both let and const are block-scoped and live in the temporal dead zone until their line runs. const stops reassignment, not mutation: const list = []; list.push(1) is fine. More in Variables and Scope and Hoisting.

Data types

Type Examples typeof
String "hi", 'hi', `hi ${x}` "string"
Number 42, 3.14, NaN, Infinity "number"
BigInt 9007199254740993n "bigint"
Boolean true, false "boolean"
undefined undefined "undefined"
null null "object" (historic bug)
Symbol Symbol("id") "symbol"
Object {}, [], functions, dates, maps "object" / "function"

Falsy values: false, 0, -0, 0n, "", null, undefined, NaN. Everything else, including "0", [] and {}, is truthy. See Data Types and Type Conversion.

Operators

JavaScript
a === b; a !== b          // strict equality: always prefer these
a ?? fallback             // fallback only for null/undefined
a || fallback             // fallback for any falsy value
user?.address?.city       // optional chaining: undefined instead of an error
x ??= 10; y ||= "n/a"; z &&= z.trim();  // logical assignment
2 ** 10                   // exponent: 1024
7 % 3                     // remainder: 1
cond ? "yes" : "no"       // ternary

Details in Comparison, Logical Operators and Nullish Coalescing and Optional Chaining.

JS Equality and fallback surprises

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Strings and numbers

String methods

Task Code
Length, char s.length, s[0], s.at(-1)
Search s.includes("x"), s.startsWith("a"), s.endsWith("z"), s.indexOf("x")
Change case s.toUpperCase(), s.toLowerCase()
Trim, pad s.trim(), s.trimStart(), s.padStart(3, "0")
Extract s.slice(1, 4), s.slice(-3)
Split, join s.split(","), arr.join(", ")
Replace s.replace("a", "b"), s.replaceAll("a", "b"), s.replace(/\d+/g, "#")
Repeat "ab".repeat(3)

Strings are immutable: every method returns a new string. Full list in String Methods; templates in Template Literals.

Numbers and Math

JavaScript
Number("42"); parseInt("42px", 10); parseFloat("3.5kg")
(1234.5).toFixed(1)                 // "1234.5" (a string)
Number.isInteger(5); Number.isNaN(x)
Math.round(), Math.floor(), Math.ceil(), Math.trunc()
Math.max(...nums), Math.min(...nums), Math.abs(-3)
Math.floor(Math.random() * 6) + 1   // integer 1-6
new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(9.5)

See Numbers, Math and Intl.

Control flow

JavaScript
if (x > 0) { โ€ฆ } else if (x < 0) { โ€ฆ } else { โ€ฆ }

switch (status) {
  case "open": โ€ฆ ; break;
  case "closed": โ€ฆ ; break;
  default: โ€ฆ
}

for (let i = 0; i < 5; i++) { โ€ฆ }
for (const item of array) { โ€ฆ }       // values of an iterable
for (const key in object) { โ€ฆ }       // keys of an object
while (cond) { โ€ฆ }
do { โ€ฆ } while (cond);
break; continue;

Use for...of for arrays, strings, maps and sets; for...in only for plain object keys. See Loops and for...of and for...in.

Functions

JavaScript
function add(a, b = 0) { return a + b; }        // declaration (hoisted)
const square = function (n) { return n * n; };  // expression
const double = (n) => n * 2;                     // arrow, implicit return
const makeUser = (name) => ({ name });           // return an object: wrap in ()
function sum(...nums) { return nums.reduce((s, n) => s + n, 0); } // rest
add(...[1, 2]);                                  // spread

Arrow functions have no own this, arguments or prototype, and can't be used with new. See Functions, Arrow Functions and Closures.

this at a glance

Call this is
obj.method() obj
fn() (strict mode, modules, classes) undefined
new Fn() the new instance
fn.call(x), fn.apply(x), fn.bind(x)() x
Arrow function this of the surrounding code
Event listener (regular function) the element (event.currentTarget)
JS Closures in loops and lost this

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Objects

JavaScript
const user = { name: "Ana", age: 31, "favorite color": "teal" };
user.name; user["favorite color"]; user.email = "[email protected]"; delete user.age;
const key = "level"; const obj = { [key]: 3, greet() { return "hi"; } };

Object.keys(o); Object.values(o); Object.entries(o); Object.fromEntries(pairs)
Object.hasOwn(o, "name"); "name" in o
const copy = { ...user, age: 32 };       // shallow copy + override
const deep = structuredClone(user);      // deep copy
Object.freeze(o)                          // shallow, no changes allowed

See Objects, Object Methods and Copying Objects.

Destructuring and spread

JavaScript
const { name, age = 18, address: { city } = {} } = user;
const [first, , third, ...rest] = list;
[a, b] = [b, a];                          // swap
function draw({ x = 0, y = 0 } = {}) { โ€ฆ } // destructured parameters
const merged = [...a, ...b];

See Destructuring and Spread and Rest.

Arrays

Goal Method Changes original?
Add/remove at end push(x), pop() Yes
Add/remove at start unshift(x), shift() Yes
Insert/remove anywhere splice(i, n, ...items) / toSpliced() Yes / No
Copy a part slice(start, end) No
Transform each item map(fn) No
Keep matching items filter(fn) No
Combine into one value reduce((acc, x) => โ€ฆ, start) No
Find item / index find, findLast, findIndex, indexOf No
Test items some(fn), every(fn), includes(x) No
Sort / reverse sort(cmp), reverse() / toSorted(cmp), toReversed() Yes / No
Flatten flat(depth), flatMap(fn) No
Join join(", "), concat(other) No
Loop forEach(fn), for...of No
Create Array.from(iter, fn), Array.of(), new Array(3).fill(0) โ€”
Group Object.groupBy(arr, fn), Map.groupBy(arr, fn) No
JavaScript
const total = cart.reduce((sum, item) => sum + item.price * item.qty, 0);
const names = users.filter((u) => u.active).map((u) => u.name);
nums.toSorted((a, b) => a - b);           // numbers: ALWAYS pass a comparator
words.toSorted((a, b) => a.localeCompare(b));
const unique = [...new Set(list)];

See Array Methods, Iterating Arrays, Sorting Arrays and Array Recipes.

Map and Set

JavaScript
const m = new Map([["a", 1]]);
m.set("b", 2).get("b"); m.has("a"); m.delete("a"); m.size;
for (const [key, value] of m) { โ€ฆ }

const s = new Set([1, 2, 2, 3]);         // {1, 2, 3}
s.add(4); s.has(2); s.delete(1); s.size;

See Maps and Sets.

Classes

JavaScript
class Animal {
  static count = 0;          // on the class
  #secret = "hidden";        // private field
  sound = "โ€ฆ";               // public field

  constructor(name) { this.name = name; Animal.count++; }
  speak() { return `${this.name} says ${this.sound}`; }
  get label() { return this.name.toUpperCase(); }
  static create(name) { return new Animal(name); }
}

class Dog extends Animal {
  sound = "woof";
  speak() { return super.speak() + "!"; }
}
new Dog("Rex").speak();      // "Rex says woof!"

See Classes, Inheritance and Private and Static.

Errors

JavaScript
try {
  riskyThing();
} catch (error) {
  console.error(error.name, error.message);
} finally {
  cleanUp();
}

throw new TypeError("Expected a number");
class ValidationError extends Error { name = "ValidationError"; }
new Error("Save failed", { cause: originalError });

See Errors and Throwing Errors.

Asynchronous code

JavaScript
setTimeout(fn, 1000); const id = setInterval(fn, 500); clearInterval(id);

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
wait(500).then(() => "done").catch(console.error).finally(stop);

async function load(url) {
  const response = await fetch(url);
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return response.json();
}

await Promise.all([a(), b()]);        // all succeed or the first rejection
await Promise.allSettled([a(), b()]); // every result, success or failure
await Promise.race([a(), timeout]);   // the first to settle
await Promise.any([a(), b()]);        // the first to succeed

See Promises, Async and Await, Promise Combinators and Fetch.

JS Event loop order

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Synchronous code runs first, then all queued microtasks (promise callbacks), and only then the next macrotask (timers, events). See Asynchronous JavaScript.

Modules and JSON

JavaScript
// math.js
export const PI = 3.14159;
export function area(r) { return PI * r ** 2; }
export default class Circle { โ€ฆ }

// main.js
import Circle, { area, PI as pi } from "./math.js";
const { format } = await import("./format.js"); // dynamic import

JSON.stringify(data, null, 2);   // object โ†’ string (pretty-printed)
JSON.parse(text);                // string โ†’ object (throws on bad JSON)

See Modules and JSON.

The DOM and events

JavaScript
const el = document.querySelector(".card");       // first match or null
const all = document.querySelectorAll("li");       // static NodeList
el.textContent = "Safe text";                      // never innerHTML for user input
el.classList.add("active"); el.classList.toggle("open");
el.style.setProperty("--size", "2rem");
el.dataset.id;                                     // data-id attribute
const li = document.createElement("li"); list.append(li); li.remove();

button.addEventListener("click", (event) => { โ€ฆ });
form.addEventListener("submit", (event) => {
  event.preventDefault();
  const data = Object.fromEntries(new FormData(form));
});
list.addEventListener("click", (event) => {        // event delegation
  const item = event.target.closest("li");
  if (item) { โ€ฆ }
});

See The DOM, Selecting Elements, Events and Event Delegation.

Built-in tools

JavaScript
localStorage.setItem("theme", "dark"); localStorage.getItem("theme");
new URL(location.href).searchParams.get("q");
new Date().toISOString();
new Intl.DateTimeFormat("en-GB", { dateStyle: "long" }).format(date);
/^\d{3}-\d{4}$/.test("555-1234");
"a1b22".match(/\d+/g);                     // ["1", "22"]

See Web Storage, URL and History, Dates and Regular Expressions.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. const config = { retries: 0 }; Which expression gives 3 only when retries is missing?

    ?? falls back only for null and undefined, so a real 0 is kept. || would replace 0 with 3.
  2. 2. Which array method returns a new sorted array and leaves the original unchanged?

    toSorted() (ES2023) returns a copy. sort(), reverse() and splice() change the array in place.
  3. 3. In what order do these log? setTimeout(() => log("A"), 0); Promise.resolve().then(() => log("B")); log("C");

    Synchronous code (C) runs first, then microtasks such as promise callbacks (B), then the timer macrotask (A).
  4. 4. What does typeof null return?

    It is a famous early bug that can never be fixed without breaking the web. Check for null with value === null.

Summary

  • Use const by default, let when you must reassign, and === for comparisons.
  • ?? and ?. handle missing values without treating 0 and "" as missing.
  • Prefer non-mutating array methods (map, filter, toSorted) and always pass a comparator when sorting numbers.
  • Arrow functions take this from their surroundings; detached methods lose this.
  • Synchronous code runs first, then microtasks (promises), then macrotasks (timers, events).
  • Set text with textContent, listen with addEventListener, and use delegation for long lists.

Next: JavaScript Practice Exercises โ€” 28 graded exercises with solutions.