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:
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
Start the Node.js REPL
$ node
> 1 + 2
3
> .exit
Run a Script
$ node script.js
Load a Script in a Web Page
<script src="script.js" defer></script>
Comments & Output
Write Comments
// A single-line comment
/* A comment that spans
multiple lines */
console.log("This will run.");
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
constby default andletwhen the value must change - Avoid
var, which ignores block scope - Name variables in
camelCase constblocks reassignment, not mutation
Declare Variables
const name = "Ada";
let count = 0;
count = count + 1; // OK
name = "Grace"; // TypeError
Mutate a Constant Object
const scores = [90, 85];
scores.push(77); // OK: [90, 85, 77]
Block Scope
if (true) {
let inside = "only here";
}
console.log(inside); // ReferenceError
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, andsymbol - Everything else is an object, including arrays and functions
undefinedmeans “not set yet”, whilenullmeans “empty on purpose”
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
Convert Types
Number("42") // 42
Number("4x") // NaN
parseInt("42px") // 42
parseFloat("3.14") // 3.14
String(42) // "42"
Boolean(0) // false
Free Bonus: Download the JavaScript Cheat Sheet PDF and keep the essentials at hand.
Strings
- Single and double quotes work the same
- Backticks create template literals with
${}placeholders - Strings are immutable, so methods return new strings
Create Strings
const single = 'Hello';
const double = "World";
const multiline = `Line 1
Line 2`;
Template Literals
const name = "Ada";
`Hi, ${name}!` // "Hi, Ada!"
`2 + 2 = ${2 + 2}` // "2 + 2 = 4"
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"
Index & Slice
const word = "JavaScript";
word[0] // "J"
word.at(-1) // "t"
word.slice(0, 4) // "Java"
word.slice(-6) // "Script"
Numbers & Math
- One
numbertype covers integers and decimals - Check for
NaNwithNumber.isNaN() - Use
BigInt(10n) for huge integers
Arithmetic Operators
10 + 3 // 13
10 - 3 // 7
10 * 3 // 30
10 / 3 // 3.3333333333333335
10 % 3 // 1 (remainder)
2 ** 3 // 8 (power)
Update in Place
let n = 5;
n += 2; // 7
n *= 2; // 14
n++; // 15
n--; // 14
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 onnullorundefined
If-Else If-Else
const age = 20;
if (age < 13) {
console.log("Child");
} else if (age < 18) {
console.log("Teen");
} else {
console.log("Adult");
}
Ternary Operator
age >= 18 ? "adult" : "minor" // "adult"
Comparison Operators
5 === 5 // true
5 === "5" // false
5 == "5" // true (avoid)
5 !== 6 // true
3 <= 5 // true
Logical Operators
true && false // false
true || false // true
!true // false
0 || 10 // 10
0 ?? 10 // 0
null ?? "guest" // "guest"
Optional Chaining
const user = { address: null };
user.address?.city // undefined
user.address.city // TypeError
Switch Statement
switch (day) {
case "Sat":
case "Sun":
console.log("Weekend");
break;
default:
console.log("Weekday");
}
Loops
for...ofloops over values,for...inover keys- Prefer
for...ofor array methods for arrays
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
}
Loop Over an Object
const ages = { ada: 36, alan: 41 };
for (const [name, age] of
Object.entries(ages)
) {
console.log(name, age); // ada 36 ...
}
While Loops
let n = 3;
while (n > 0) {
console.log(n); // 3, 2, 1
n--;
}
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
}
Free Bonus: Download the JavaScript Cheat Sheet PDF and keep the essentials at hand.
Functions
- Functions are values you can store and pass around
- Missing arguments become
undefined - Arrow functions don’t have their own
this
Function Declarations
function greet(name) {
return `Hello, ${name}!`;
}
greet("Ada"); // "Hello, Ada!"
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" }
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
Callbacks
setTimeout(() => {
console.log("One second later");
}, 1000);
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(), andslice()return new arrayspush(),pop(),sort(), andsplice()change the array in place, whiletoSorted()returns a copy
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
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]
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
Sort Numbers Correctly
[10, 9, 1].sort() // [1, 10, 9]
[10, 9, 1].sort((a, b) => a - b)
// [1, 9, 10]
Spread & Destructuring
const first = [1, 2];
const all = [...first, 3]; // [1, 2, 3]
const [head, ...tail] = all;
// head is 1, tail is [2, 3]
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
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"
Update & Delete
user.email = "[email protected]";
user.age += 1;
delete user.email;
"email" in user // false
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 }
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]]
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 usingthisin a subclass constructor
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!"
Inheritance
class Puppy extends Dog {
bark() {
return super.bark() + " (squeak)";
}
}
new Puppy("Bo").bark();
// "Bo says woof! (squeak)"
Free Bonus: Download the JavaScript Cheat Sheet PDF and keep the essentials at hand.
Errors
- Throw
Errorobjects, not plain strings finallyruns whether or not an error happened
Try-Catch-Finally
try {
JSON.parse("{bad json}");
} catch (error) {
console.error(error.name); // SyntaxError
} finally {
console.log("Done");
}
Throw Errors
function divide(a, b) {
if (b === 0) {
throw new RangeError("Divide by 0");
}
return a / b;
}
Common Errors
missing; // ReferenceError
null.name; // TypeError
const pi = 3.14;
pi = 3; // TypeError
JSON.parse("{"); // SyntaxError
Maps & Sets
- A
Mapkeeps insertion order and accepts any type of key - A
Setstores each value only once
Map
const ages = new Map();
ages.set("ada", 36);
ages.get("ada") // 36
ages.has("alan") // false
ages.size // 1
ages.delete("ada"); // true
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
Promisestands for a value that arrives later - Use
awaitinsideasyncfunctions or at the top level of a module
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();
}
Handle Async Errors
try {
const user = await getUser(1);
console.log(user.name);
} catch (error) {
console.error(error.message);
}
Promise Chains
getUser(1)
.then((user) => console.log(user.name))
.catch((error) => console.error(error));
Run Tasks in Parallel
const [ada, alan] = await Promise.all([
getUser(1),
getUser(2),
]);
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"topackage.jsonto useimportin Node.js
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;
}
Import
// main.js
import mul, { PI, add } from "./math.js";
import * as math from "./math.js";
Install Packages With npm
$ npm init -y
$ npm install date-fns
$ npm install --save-dev vitest
$ npx vitest run
Free Bonus: Download the JavaScript Cheat Sheet PDF and keep the essentials at hand.
The DOM
- The DOM is the browser’s live model of the page
- Use
textContentfor text, sinceinnerHTMLcan run injected code
Select Elements
const title = document.querySelector("h1");
const lis = document.querySelectorAll("li");
const form = document.querySelector("form");
Change Content & Style
title.textContent = "Hello, DOM!";
title.classList.add("highlight");
title.style.color = "tomato";
Create Elements
const li = document.createElement("li");
li.textContent = "New item";
document.querySelector("ul").append(li);
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
Pause in the Debugger
function total(items) {
debugger; // Pauses if DevTools is open
return items.reduce((s, x) => s + x, 0);
}
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 |
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"
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();
Want to go deeper on JavaScript?
RealJS teaches the mental models that let you write, read, and review modern JavaScript with confidence, whether you or an AI wrote it.
Not sure where you stand? Take the free JavaScript Skill Test quiz to find your level.
Learn more at realjs.com 💡
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: