JavaScript Cheat Sheet

This page condenses modern JavaScript, from variables and types to classes, modules, and async code, into one quick reference. You can also download the information as a printable cheat sheet:

Free Bonus: JavaScript Cheat Sheet

Get the JavaScript Cheat Sheet (PDF), a printable reference to variables, types, strings, arrays, objects, functions, classes, modules, and async basics:

JavaScript Cheat Sheet

Want a guided path instead of a reference? Start learning at realjs.com.

Getting Started

  • Every browser runs JavaScript: press F12 and open the Console tab
  • Install Node.js to run JavaScript outside the browser
  • End statements with semicolons to avoid surprises
Language: Shell Filename: Start the Node.js REPL
$ node
> 1 + 2
3
> .exit
Language: Shell Filename: Run a Script
$ node script.js
Language: HTML Filename: Load a Script in a Web Page
<script src="script.js" defer></script>

Comments & Output

Language: JavaScript Filename: Write Comments
// A single-line comment
/* A comment that spans
   multiple lines */
console.log("This will run.");
Language: JavaScript Filename: Log to the Console
console.log("Total:", 42);  // Total: 42
console.warn("Careful!");   // Yellow warning
console.error("Oops!");     // Red error
console.table([{ a: 1 }]);  // Prints a table

Variables

  • Use const by default and let when the value must change
  • Avoid var, which ignores block scope
  • Name variables in camelCase
  • const blocks reassignment, not mutation
Language: JavaScript Filename: Declare Variables
const name = "Ada";
let count = 0;
count = count + 1;   // OK
name = "Grace";      // TypeError
Language: JavaScript Filename: Mutate a Constant Object
const scores = [90, 85];
scores.push(77);     // OK: [90, 85, 77]
Language: JavaScript Filename: Block Scope
if (true) {
  let inside = "only here";
}
console.log(inside); // ReferenceError
Language: JavaScript Filename: Swap Values
let a = 1;
let b = 2;
[a, b] = [b, a];     // a = 2, b = 1

Data Types

  • Primitives: string, number, bigint, boolean, undefined, null, and symbol
  • Everything else is an object, including arrays and functions
  • undefined means “not set yet”, while null means “empty on purpose”
Language: JavaScript Filename: Check Types
typeof "hi"          // "string"
typeof 42            // "number"
typeof 10n           // "bigint"
typeof true          // "boolean"
typeof undefined     // "undefined"
typeof null          // "object" (a quirk)
typeof [1, 2]        // "object"
Array.isArray([1])   // true
Language: JavaScript Filename: Convert Types
Number("42")         // 42
Number("4x")         // NaN
parseInt("42px")     // 42
parseFloat("3.14")   // 3.14
String(42)           // "42"
Boolean(0)           // false

Strings

  • Single and double quotes work the same
  • Backticks create template literals with ${} placeholders
  • Strings are immutable, so methods return new strings
Language: JavaScript Filename: Create Strings
const single = 'Hello';
const double = "World";
const multiline = `Line 1
Line 2`;
Language: JavaScript Filename: Template Literals
const name = "Ada";
`Hi, ${name}!`       // "Hi, Ada!"
`2 + 2 = ${2 + 2}`   // "2 + 2 = 4"
Language: JavaScript Filename: String Methods
const s = " Hello, World! ";
s.length             // 15
s.trim()             // "Hello, World!"
s.toUpperCase()      // " HELLO, WORLD! "
s.includes("World")  // true
s.replace("World", "JS")
// " Hello, JS! "
"a,b,c".split(",")   // ["a", "b", "c"]
"7".padStart(3, "0") // "007"
Language: JavaScript Filename: Index & Slice
const word = "JavaScript";
word[0]              // "J"
word.at(-1)          // "t"
word.slice(0, 4)     // "Java"
word.slice(-6)       // "Script"

Numbers & Math

  • One number type covers integers and decimals
  • Check for NaN with Number.isNaN()
  • Use BigInt (10n) for huge integers
Language: JavaScript Filename: Arithmetic Operators
10 + 3    // 13
10 - 3    // 7
10 * 3    // 30
10 / 3    // 3.3333333333333335
10 % 3    // 1 (remainder)
2 ** 3    // 8 (power)
Language: JavaScript Filename: Update in Place
let n = 5;
n += 2;   // 7
n *= 2;   // 14
n++;      // 15
n--;      // 14
Language: JavaScript Filename: Useful Functions
Math.round(3.7)        // 4
Math.floor(3.7)        // 3
Math.ceil(3.2)         // 4
Math.max(1, 5, 3)      // 5
Math.random()          // 0 <= n < 1
(3.14159).toFixed(2)   // "3.14"
Number.isInteger(5)    // true

Conditionals

  • Always compare with === and !==
  • == converts types before comparing
  • ?? falls back only on null or undefined
Language: JavaScript Filename: If-Else If-Else
const age = 20;
if (age < 13) {
  console.log("Child");
} else if (age < 18) {
  console.log("Teen");
} else {
  console.log("Adult");
}
Language: JavaScript Filename: Ternary Operator
age >= 18 ? "adult" : "minor"  // "adult"
Language: JavaScript Filename: Comparison Operators
5 === 5      // true
5 === "5"    // false
5 == "5"     // true (avoid)
5 !== 6      // true
3 <= 5       // true
Language: JavaScript Filename: Logical Operators
true && false     // false
true || false     // true
!true             // false
0 || 10           // 10
0 ?? 10           // 0
null ?? "guest"   // "guest"
Language: JavaScript Filename: Optional Chaining
const user = { address: null };
user.address?.city   // undefined
user.address.city    // TypeError
Language: JavaScript Filename: Switch Statement
switch (day) {
  case "Sat":
  case "Sun":
    console.log("Weekend");
    break;
  default:
    console.log("Weekday");
}

Loops

  • for...of loops over values, for...in over keys
  • Prefer for...of or array methods for arrays
Language: JavaScript Filename: For Loops
for (let i = 0; i < 3; i++) {
  console.log(i);      // 0, 1, 2
}

for (const fruit of ["fig", "kiwi"]) {
  console.log(fruit);  // fig, kiwi
}
Language: JavaScript Filename: Loop Over an Object
const ages = { ada: 36, alan: 41 };
for (const [name, age] of
  Object.entries(ages)
) {
  console.log(name, age);  // ada 36 ...
}
Language: JavaScript Filename: While Loops
let n = 3;
while (n > 0) {
  console.log(n);  // 3, 2, 1
  n--;
}
Language: JavaScript Filename: Loop Control
for (const n of [1, 2, 3, 4]) {
  if (n === 2) continue;  // Skip 2
  if (n === 4) break;     // Stop at 4
  console.log(n);         // 1, 3
}

Functions

  • Functions are values you can store and pass around
  • Missing arguments become undefined
  • Arrow functions don’t have their own this
Language: JavaScript Filename: Function Declarations
function greet(name) {
  return `Hello, ${name}!`;
}
greet("Ada");  // "Hello, Ada!"
Language: JavaScript Filename: Arrow Functions
const add = (a, b) => a + b;
const square = (x) => x * x;
const toUser = (name) => ({ name });
add(2, 3);     // 5
toUser("Ada"); // { name: "Ada" }
Language: JavaScript Filename: Default & Rest Parameters
function hi(name = "World") {
  return `Hi, ${name}!`;
}
hi();          // "Hi, World!"

function sum(...nums) {
  return nums.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3);  // 6
Language: JavaScript Filename: Callbacks
setTimeout(() => {
  console.log("One second later");
}, 1000);
Language: JavaScript Filename: Closures
function makeCounter() {
  let count = 0;
  return () => ++count;
}
const next = makeCounter();
next();  // 1
next();  // 2

Arrays

  • Arrays are zero-indexed and can hold any type
  • map(), filter(), and slice() return new arrays
  • push(), pop(), sort(), and splice() change the array in place, while toSorted() returns a copy
Language: JavaScript Filename: Create & Access
const nums = [10, 20, 30];
nums[0]              // 10
nums.at(-1)          // 30
nums.length          // 3
nums.includes(20)    // true
nums.indexOf(30)     // 2
Language: JavaScript Filename: Add & Remove Items
const a = [1, 2];
a.push(3);           // a is [1, 2, 3]
a.pop();             // a is [1, 2]
a.unshift(0);        // a is [0, 1, 2]
a.shift();           // a is [1, 2]
Language: JavaScript Filename: Transform & Search
const n = [1, 2, 3, 4];
n.map((x) => x * 2)     // [2, 4, 6, 8]
n.filter((x) => x > 2)  // [3, 4]
n.find((x) => x > 2)    // 3
n.some((x) => x > 3)    // true
n.every((x) => x > 0)   // true
n.reduce((s, x) => s + x, 0)  // 10
Language: JavaScript Filename: Sort Numbers Correctly
[10, 9, 1].sort()    // [1, 10, 9]
[10, 9, 1].sort((a, b) => a - b)
// [1, 9, 10]
Language: JavaScript Filename: Spread & Destructuring
const first = [1, 2];
const all = [...first, 3];  // [1, 2, 3]
const [head, ...tail] = all;
// head is 1, tail is [2, 3]
Language: JavaScript Filename: Slice & Join
[1, 2, 3].slice(1)   // [2, 3]
["a", "b"].join("-") // "a-b"

Objects

  • Objects store key-value pairs
  • Use dot notation for fixed keys and brackets for dynamic keys
Language: JavaScript Filename: Create & Access
const user = {
  name: "Ada",
  age: 36,
  greet() {
    return `Hi, I'm ${this.name}`;
  },
};
user.name            // "Ada"
user["age"]          // 36
user.greet()         // "Hi, I'm Ada"
Language: JavaScript Filename: Update & Delete
user.email = "[email protected]";
user.age += 1;
delete user.email;
"email" in user      // false
Language: JavaScript Filename: Destructuring & Spread
const { name, age } = user;
const older = { ...user, age: 40 };
const x = 1;
const y = 2;
const point = { x, y };  // { x: 1, y: 2 }
Language: JavaScript Filename: Inspect Objects
const p = { x: 1, y: 2 };
Object.keys(p)       // ["x", "y"]
Object.values(p)     // [1, 2]
Object.entries(p)    // [["x", 1], ["y", 2]]
Language: JavaScript Filename: Work With JSON
const text = JSON.stringify({ a: 1 });
// '{"a":1}'
JSON.parse(text)     // { a: 1 }

Classes

  • Fields that start with # are private
  • Call super() before using this in a subclass constructor
Language: JavaScript Filename: Define a Class
class Dog {
  static count = 0;
  #treats = 0;          // Private field

  constructor(name) {
    this.name = name;
    Dog.count++;
  }

  bark() {
    return `${this.name} says woof!`;
  }
}
const rex = new Dog("Rex");
rex.bark();  // "Rex says woof!"
Language: JavaScript Filename: Inheritance
class Puppy extends Dog {
  bark() {
    return super.bark() + " (squeak)";
  }
}
new Puppy("Bo").bark();
// "Bo says woof! (squeak)"

Errors

  • Throw Error objects, not plain strings
  • finally runs whether or not an error happened
Language: JavaScript Filename: Try-Catch-Finally
try {
  JSON.parse("{bad json}");
} catch (error) {
  console.error(error.name);  // SyntaxError
} finally {
  console.log("Done");
}
Language: JavaScript Filename: Throw Errors
function divide(a, b) {
  if (b === 0) {
    throw new RangeError("Divide by 0");
  }
  return a / b;
}
Language: JavaScript Filename: Common Errors
missing;             // ReferenceError
null.name;           // TypeError
const pi = 3.14;
pi = 3;              // TypeError
JSON.parse("{");     // SyntaxError

Maps & Sets

  • A Map keeps insertion order and accepts any type of key
  • A Set stores each value only once
Language: JavaScript Filename: Map
const ages = new Map();
ages.set("ada", 36);
ages.get("ada")      // 36
ages.has("alan")     // false
ages.size            // 1
ages.delete("ada");  // true
Language: JavaScript Filename: Set
const tags = new Set(["js", "web"]);
tags.add("js");      // Ignored duplicate
tags.has("web")      // true
tags.size            // 2
[...tags]            // ["js", "web"]

Async JavaScript

  • JavaScript runs one task at a time but never waits idly on network or timers
  • A Promise stands for a value that arrives later
  • Use await inside async functions or at the top level of a module
Language: JavaScript Filename: Async & Await
async function getUser(id) {
  const url = `/api/users/${id}`;
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(response.statusText);
  }
  return response.json();
}
Language: JavaScript Filename: Handle Async Errors
try {
  const user = await getUser(1);
  console.log(user.name);
} catch (error) {
  console.error(error.message);
}
Language: JavaScript Filename: Promise Chains
getUser(1)
  .then((user) => console.log(user.name))
  .catch((error) => console.error(error));
Language: JavaScript Filename: Run Tasks in Parallel
const [ada, alan] = await Promise.all([
  getUser(1),
  getUser(2),
]);
Language: JavaScript Filename: Pause for a While
const sleep = (ms) =>
  new Promise((ok) => setTimeout(ok, ms));
await sleep(1000);  // Wait one second

Modules & Packages

  • Each file is a module with its own scope
  • Load modules in a page with <script type="module">
  • Add "type": "module" to package.json to use import in Node.js
Language: JavaScript Filename: Export
// math.js
export const PI = 3.14159;
export function add(a, b) {
  return a + b;
}
export default function mul(a, b) {
  return a * b;
}
Language: JavaScript Filename: Import
// main.js
import mul, { PI, add } from "./math.js";
import * as math from "./math.js";
Language: Shell Filename: Install Packages With npm
$ npm init -y
$ npm install date-fns
$ npm install --save-dev vitest
$ npx vitest run

The DOM

  • The DOM is the browser’s live model of the page
  • Use textContent for text, since innerHTML can run injected code
Language: JavaScript Filename: Select Elements
const title = document.querySelector("h1");
const lis = document.querySelectorAll("li");
const form = document.querySelector("form");
Language: JavaScript Filename: Change Content & Style
title.textContent = "Hello, DOM!";
title.classList.add("highlight");
title.style.color = "tomato";
Language: JavaScript Filename: Create Elements
const li = document.createElement("li");
li.textContent = "New item";
document.querySelector("ul").append(li);
Language: JavaScript Filename: Handle Events
const btn = document.querySelector("#go");
btn.addEventListener("click", (event) => {
  console.log("Clicked", event.target);
});

Debugging

  • Open DevTools to set breakpoints and step through code line by line
  • Read a stack trace from the top to find where an error started
Language: JavaScript Filename: Pause in the Debugger
function total(items) {
  debugger;  // Pauses if DevTools is open
  return items.reduce((s, x) => s + x, 0);
}
Language: JavaScript Filename: Inspect Values
const user = "Ada";
const score = 42;
console.log({ user, score });
// { user: 'Ada', score: 42 }
console.assert(score > 50, "Low score");
// Assertion failed: Low score
console.time("loop");
// ...code to measure...
console.timeEnd("loop");  // loop: 0.1ms

Miscellaneous

Truthy Falsy
42, -1 0, -0
"hi", "0" ""
[], {} null
true undefined
Infinity NaN, false
Language: JavaScript Filename: Common Gotchas
0.1 + 0.2 === 0.3    // false
NaN === NaN          // false
[] === []            // false (by reference)
"5" + 1              // "51"
"5" - 1              // 4
[1, 2] + [3]         // "1,23"
Language: JavaScript Filename: Handy Idioms
// Remove duplicates
const unique = [...new Set([1, 1, 2])];

// Deep copy an object
const copy = structuredClone({ a: [1] });

// Count occurrences
const counts = {};
for (const word of ["a", "b", "a"]) {
  counts[word] = (counts[word] ?? 0) + 1;
}
// { a: 2, b: 1 }

// Current date and time
new Date().toISOString();

You can download this information as a printable cheat sheet:

Free Bonus: JavaScript Cheat Sheet

Get the JavaScript Cheat Sheet (PDF), a printable reference to variables, types, strings, arrays, objects, functions, classes, modules, and async basics:

JavaScript Cheat Sheet