Cheat sheet · JavaScript
JavaScript Cheat Sheet
A scannable JavaScript reference covering variables, template literals, string and array methods, objects, destructuring, control flow, functions, arrow functions, and common built-ins.
A cheat sheet is for the thing you have understood once and cannot quite remember the shape of. It is written to be scanned, so the common cases come first. Starting from nothing? The JavaScript exercises are the right first step; come back here once the syntax is something you are recalling rather than meeting. Looking for another language? See every cheat sheet.
This page is a fast-scanning reference for JavaScript syntax you'll reach for constantly — not a
tutorial. Each section is a self-contained group of runnable snippets, so jump straight to the part you
need. Where a line's output isn't obvious from reading it, the comment after it (or a text block
underneath) shows exactly what JavaScript produces.
Variables & Types
let creates a variable you can reassign; const creates one you can't. Every value still has its own
type — JavaScript just doesn't make you declare it up front, and unlike some languages there is only
one numeric type, number, covering both whole numbers and decimals.
let name = "Priya"; // string
let age = 27; // number
let gpa = 3.85; // number — no separate float type
let isActive = true; // boolean
let data = null; // "no value", set on purpose
let notSet; // undefined — declared but never assigned
typeof age; // 'number'
typeof data; // 'object' — a long-standing JavaScript quirkConverting between types is done with Number(), String(), Boolean(), and the more forgiving
parseInt()/parseFloat(), which read leading digits and ignore whatever comes after:
Number("42"); // 42
Number("42px"); // NaN — the whole string must be numeric
parseInt("42px"); // 42 — reads leading digits, ignores the rest
String(17); // '17'
Boolean(0); // false
Boolean(""); // false
Boolean("false"); // true — any non-empty string is truthyJavaScript lets you assign or swap several variables at once through destructuring, covered in full further down:
let x = 1;
let y = 2;
[x, y] = [y, x]; // swap without a temp variable — x=2, y=1
const [first, ...rest] = [1, 2, 3, 4]; // first=1, rest=[2, 3, 4]Template Literals & String Formatting
A template literal is a string delimited by backticks instead of quotes. Anything inside ${} is
evaluated as a real JavaScript expression and inserted into the string — this is the standard way to
build strings in modern JavaScript.
const name = "Priya";
const score = 87.4567;
`Hello, ${name}!`; // 'Hello, Priya!'
`Score: ${score.toFixed(1)}`; // 'Score: 87.5' — 1 decimal place
`Score: ${score.toFixed(2)}%`; // 'Score: 87.46%' — 2 decimal places
`${String(7).padStart(5, "0")}`; // '00007' — zero-padded to width 5
`${score.toFixed(2).padStart(10)}`; // ' 87.46' — right-aligned in a width-10 field
`${score.toFixed(2).padEnd(10)}|`; // '87.46 |' — left-aligned, padding before |
`${(1234567).toLocaleString()}`; // '1,234,567' — thousands separators.toFixed() rounds a number to a fixed number of decimal places and always returns a string, which
is why it's the standard tool for money and percentages. .toLocaleString() follows the browser's own
locale settings, so treat its exact formatting as a convenience rather than something to rely on being
identical everywhere.
You can call methods and use a ternary directly inside the braces:
const items = ["pen", "book"];
`You have ${items.length} item${items.length !== 1 ? "s" : ""}`; // 'You have 2 items'Common String Methods
Strings are immutable — every method below returns a new string rather than changing the original.
const s = " Hello, World! ";
s.trim(); // 'Hello, World!' — trims both ends
s.toLowerCase(); // ' hello, world! '
s.toUpperCase(); // ' HELLO, WORLD! '
s.trim().replace("World", "JavaScript"); // 'Hello, JavaScript!'
s.trim().split(","); // [ 'Hello', ' World!' ]
["a", "b", "c"].join("-"); // 'a-b-c' — opposite of split()
"Hello".startsWith("He"); // true
"Hello".endsWith("lo"); // true
"42".padStart(4, "0"); // '0042'
"hi".repeat(3); // 'hihihi'.indexOf() and .includes() both search for a substring, but only .indexOf() tells you where:
"Hello".indexOf("l"); // 2 — index of the first match
"Hello".indexOf("z"); // -1 — not found, never throws
"Hello".includes("z"); // false.replace() only swaps the first match; use .replaceAll() for every match:
"a-a-a".replace("a", "b"); // 'b-a-a'
"a-a-a".replaceAll("a", "b"); // 'b-b-b'Arrays
An array is an ordered, mutable collection — you can change, add to, or remove from it after creation, and it can hold a mix of types.
const fruits = ["apple", "banana", "cherry"];
fruits.push("date"); // add to the end — mutates, returns the new length
fruits.unshift("kiwi"); // add to the front — mutates
fruits.pop(); // remove and return the last item — mutates
fruits.shift(); // remove and return the first item — mutates
fruits.splice(1, 0, "fig"); // insert "fig" at index 1, deleting 0 items — mutates
fruits.includes("cherry"); // true — membership test
fruits.indexOf("cherry"); // 3 — index of the first match, or -1
fruits.length; // 4 — number of itemsReading past the end of an array, or with a negative bracket index, gives undefined rather than an
error. For "count from the end," use .at():
const fruits = ["apple", "fig", "banana", "cherry"];
fruits[99]; // undefined
fruits.at(-1); // 'cherry' — .at() understands negative positions, [] does notSlicing and Copying
.slice(start, end) pulls out a range without touching the original, and it doubles as the standard way
to copy an array before a mutating method like .sort() or .reverse():
const nums = [10, 20, 30, 40, 50];
nums.slice(1, 3); // [ 20, 30 ]
nums.slice(-2); // [ 40, 50 ] — negative counts from the end
[...nums].reverse(); // [ 50, 40, 30, 20, 10 ] — reversed copy, nums untouched
const messy = [40, 10, 30, 20];
messy.slice().sort((a, b) => a - b); // [ 10, 20, 30, 40 ] — sorted copy; messy itself is untouchedSorting without a comparator compares elements as strings, which breaks numeric order — always pass
(a, b) => a - b for ascending numbers, or (a, b) => b - a for descending.
Transforming Arrays: map, filter, reduce, find, some, every
All six take a function and call it once per element. .map() and .filter() return a new array of the
same or shorter length; the rest reduce the array to a single answer.
const values = [1, 2, 3, 4, 5];
values.map(n => n * 2); // [ 2, 4, 6, 8, 10 ]
values.filter(n => n % 2 === 0); // [ 2, 4 ]
values.reduce((sum, n) => sum + n, 0); // 15 — combines every item into one value
values.find(n => n > 3); // 4 — first match, or undefined if none
values.some(n => n > 4); // true — at least one item passes
values.every(n => n > 4); // false — not every item passesNone of these six methods change the original array — each one returns a fresh array or value.
Objects
An object maps string keys to values. Since ES2015, JavaScript remembers the order keys were inserted in, except that keys which look like non-negative integers are always listed first, in ascending order.
const person = { name: "Zoe", age: 30 };
person.age; // 30 — dot notation
person["age"]; // 30 — bracket notation, needed for dynamic keys
person.email; // undefined — missing key, never throws
person.email ?? "n/a"; // 'n/a' — missing key, with a fallback
person.email = "zoe@example.com"; // adds a new key (or overwrites an existing one)
delete person.age; // removes "age"
"name" in person; // true — checks the keys, not the valuesSquare-bracket and dot access both read the same way; only bracket notation accepts a variable in place
of a literal key name. ?? only falls back for null/undefined — use it instead of || whenever 0,
"", or false could be a genuine value.
Merge objects with the spread operator, later keys winning on a conflict:
const defaults = { theme: "dark", retries: 3 };
const overrides = { retries: 5, verbose: true };
const merged = { ...defaults, ...overrides };
merged; // { theme: 'dark', retries: 5, verbose: true }Walk an object's contents with Object.keys(), Object.values(), or Object.entries(), all of which
return real arrays:
const scores = { tea: 3, coffee: 5 };
Object.keys(scores); // [ 'tea', 'coffee' ]
Object.values(scores); // [ 3, 5 ]
Object.entries(scores); // [ [ 'tea', 3 ], [ 'coffee', 5 ] ]Destructuring
Destructuring pulls values out of an array or object straight into named variables in one step.
const [first, second, ...rest] = [10, 20, 30, 40];
first; // 10
second; // 20
rest; // [ 30, 40 ]
const { name, age } = { name: "Ada", age: 36, city: "London" };
name; // 'Ada'
age; // 36
const { city = "Unknown" } = { name: "Ada" };
city; // 'Unknown' — default used because "city" was missing on the right-hand sideIt works directly in a function's parameter list too, which is extremely common for functions that take a single options object:
function printUser({ name, age }) {
console.log(`${name} is ${age}`);
}
printUser({ name: "Zoe", age: 30 });Zoe is 30Spread and Rest
The same ... syntax means two different things depending on which side of an assignment or call it
appears on: spread unpacks a collection into individual items, and rest gathers individual items
back into a collection.
const parts = [1, 2, 3];
Math.max(...parts); // 3 — spread: unpacks the array into separate arguments
function logAll(...args) { // rest: collects every argument into one array
console.log(args);
}
logAll(1, 2, 3);[ 1, 2, 3 ]Control Flow
Comparison and Equality
5 === 5; // true
5 === "5"; // false — different types, === never coerces
5 == "5"; // true — == coerces before comparing; prefer === almost always
null ?? "default"; // 'default' — ?? falls back only for null/undefined
0 || "default"; // 'default' — || falls back for ANY falsy value, including 0if / else if / else and the Ternary Operator
const age = 20;
let stage;
if (age < 13) {
stage = "child";
} else if (age < 20) {
stage = "teen";
} else {
stage = "adult";
}
stage; // 'adult'
const label = age % 2 === 0 ? "even" : "odd"; // 'even'switch
JavaScript's switch compares a value against a list of cases with ===. A case with no break
falls through into the next one — useful for grouping cases, dangerous if done by accident.
const day = "Mon";
switch (day) {
case "Sat":
case "Sun":
console.log("Weekend");
break;
default:
console.log("Weekday");
}WeekdayLoops
for (let i = 0; i < 3; i++) { /* classic counting loop */ }
for (const x of [10, 20, 30]) { /* walks values directly */ }
for (const key in { a: 1, b: 2 }) { /* walks an object's keys */ }
let total = 0;
let n = 1;
while (n <= 5) {
total += n;
n++;
}
total; // 15break exits a loop immediately; continue skips straight to the next pass:
for (const n of [0, 1, 2, 3, 4, 5, 6]) {
if (n === 3) continue;
if (n === 6) break;
console.log(n);
}0
1
2
4
5Functions & Arrow Functions
function declarations are hoisted and can be called before their line in the file; arrow functions
assigned to const cannot. A single-expression arrow body returns automatically; a block body needs an
explicit return.
function greet(name, greeting = "Hello") {
return `${greeting}, ${name}!`;
}
greet("Sam"); // 'Hello, Sam!'
greet("Sam", "Hey"); // 'Hey, Sam!'
const add = (a, b) => a + b; // concise body — implicit return
const shout = text => text.toUpperCase() + "!"; // single param — parentheses optional
const makePoint = (x, y) => ({ x, y }); // parentheses required to return an object... collects any extra arguments into a real array:
function total(...numbers) {
return numbers.reduce((sum, n) => sum + n, 0);
}
total(1, 2, 3); // 6
total(); // 0Common Built-ins
JSON.stringify() and JSON.parse() convert between a JavaScript value and its JSON text form —
essential whenever data needs to leave your program, such as into localStorage or a network request.
JSON.stringify({ a: 1, b: [2, 3] }); // '{"a":1,"b":[2,3]}'
JSON.parse('{"a":1,"b":[2,3]}'); // { a: 1, b: [ 2, 3 ] }Array.from() builds a real array out of anything array-like or iterable, optionally applying a mapping
function as it goes — the standard way to build a numeric range in JavaScript, since there is no
built-in range():
Array.from({ length: 5 }, (_, i) => i); // [ 0, 1, 2, 3, 4 ]
Array.from("abc"); // [ 'a', 'b', 'c' ] — spreads a string into charactersA handful of Number and Math functions come up constantly:
Number.isInteger(4); // true
Number.isInteger(4.5); // false
Number.isNaN(NaN); // true — the only reliable way to test for NaN
Number.parseFloat("3.14m"); // 3.14 — reads the leading numeric part
Math.max(4, 9, 1); // 9
Math.min(4, 9, 1); // 1
Math.round(4.5); // 5
Math.random(); // a float from 0 up to (not including) 1 — different every timeError Handling
try runs code that might fail; catch handles it if it does; finally always runs last, whether or
not there was an error — useful for cleanup that must happen no matter what.
function safeDivide(a, b) {
try {
if (b === 0) throw new Error("Cannot divide by zero");
return a / b;
} catch (error) {
console.log("Caught:", error.message);
return null;
} finally {
console.log("Done attempting division");
}
}
console.log(safeDivide(10, 2));
console.log(safeDivide(10, 0));Done attempting division
5
Caught: Cannot divide by zero
Done attempting division
nullNotice that finally runs even though both branches hit a return earlier — JavaScript finishes the
finally block before the function actually hands the value back to its caller. throw can raise any
value, but throwing an Error (or a subclass of it) is standard practice, since it carries a .message
and a stack trace for free.
Try any snippet with your own values in the JavaScript playground.