JavaScript/Cheat sheet
Last edited by disfordave on 27/08/2026, 05:50:42 UTC
You were redirected here from JavaScript cheat sheet.
Contents
Check out the other cheat sheets!
A fast, friendly, and fairly comprehensive guide to modern JavaScript โ for when your brain remembers .map() but forgets what .reduce() actually does.
[!TIP] Prefer modern JavaScript:
const/let,===, arrow functions where appropriate,async/await, modules, optional chaining, and nullish coalescing.
๐จ JavaScript Cheat Sheet
๐งญ Quick Reference
| Need | Use |
|---|---|
| Declare a value | const x = 1 |
| Reassign a value | let x = 1 |
| String interpolation | `Hello ${name}` |
| Strict comparison | a === b |
| Default fallback | value ?? fallback |
| Safe property access | user?.profile?.name |
| Transform an array | .map() |
| Keep matching items | .filter() |
| Find one item | .find() |
| Combine array values | .reduce() |
| Check array membership | .includes() |
| Remove duplicates | [...new Set(arr)] |
| Copy an array | [...arr] |
| Copy an object | { ...obj } |
| Wait for a Promise | await promise |
| Handle errors | try { ... } catch (err) { ... } |
| Convert JSON โ object | JSON.parse() |
| Convert object โ JSON | JSON.stringify() |
| Log a value | console.log() |
โ๏ธ Basics
Declaring Variables
let x = 10; // block-scoped, can be reassigned const y = 20; // block-scoped, cannot be reassigned var z = 30; // function-scoped, legacy syntax
Prefer:
const name = "Alice"; let score = 0; score++;
Use const by default and switch to let only when reassignment is necessary.
const Does Not Mean Immutable
const prevents reassignment of the variable itself, not mutation of the object it references.
const user = { name: "Alice" }; user.name = "Bob"; // โ allowed // user = {}; // โ TypeError
Variable Scope
Block Scope
let and const are scoped to {} blocks.
if (true) { const message = "hello"; let count = 1; } // console.log(message); // โ ReferenceError
Function Scope
var is function-scoped.
function example() { if (true) { var x = 10; } console.log(x); // 10 }
Hoisting
Function declarations are hoisted:
sayHello(); function sayHello() { console.log("Hello!"); }
var declarations are hoisted and initialized with undefined:
console.log(x); // undefined var x = 5;
Conceptually:
var x; console.log(x); x = 5;
let and const are also hoisted but cannot be accessed before their declaration.
// console.log(x); // โ ReferenceError const x = 5;
This period is called the Temporal Dead Zone (TDZ).
๐งฌ Data Types
JavaScript has primitive values and objects.
Primitive Types
string number boolean null undefined symbol bigint
Examples:
const name = "Alice"; // string const age = 25; // number const active = true; // boolean const empty = null; // null let missing; // undefined const id = Symbol("id"); // symbol const huge = 123456789n; // bigint
Objects
Arrays, functions, dates, maps, sets, and ordinary objects are all objects.
const obj = {}; const arr = []; const fn = () => {}; const date = new Date();
typeof
typeof 42; // "number" typeof "hello"; // "string" typeof true; // "boolean" typeof undefined; // "undefined" typeof 123n; // "bigint" typeof Symbol(); // "symbol" typeof {}; // "object" typeof []; // "object" typeof function() {}; // "function" typeof null; // "object" โ historical JavaScript quirk
To check arrays:
Array.isArray([]); // true
To check null:
value === null;
๐ญ Truthy & Falsy Values
JavaScript automatically converts values to booleans in conditions.
Falsy Values
These are falsy:
false 0 -0 0n "" null undefined NaN
Everything else is truthy.
Boolean(""); // false Boolean("hello"); // true Boolean([]); // true Boolean({}); // true
Example:
if (username) { console.log("Username exists"); }
๐ Type Conversion
Explicit Conversion
String(42); // "42" Number("42"); // 42 Boolean(1); // true BigInt("123"); // 123n
Strings โ Numbers
Number("42"); // 42 Number("3.14"); // 3.14 parseInt("42px"); // 42 parseFloat("3.14em");// 3.14
Prefer:
Number.isNaN(value);
instead of global:
isNaN(value);
because global isNaN() performs coercion.
isNaN("hello"); // true Number.isNaN("hello"); // false Number.isNaN(NaN); // true
๐งฎ Operators
Arithmetic
+ // addition / string concatenation - // subtraction * // multiplication / // division % // remainder ** // exponentiation ++ // increment -- // decrement
Examples:
10 + 5; // 15 10 - 5; // 5 10 * 5; // 50 10 / 5; // 2 10 % 3; // 1 2 ** 3; // 8
Assignment Operators
x = 10; x += 5; x -= 5; x *= 2; x /= 2; x %= 3; x **= 2;
Logical assignment:
x ||= fallback; x &&= newValue; x ??= defaultValue;
โ๏ธ Comparison
== // loose equality โ performs coercion === // strict equality != // loose inequality !== // strict inequality > < >= <=
Prefer:
a === b; a !== b;
instead of:
a == b; a != b;
Example:
5 == "5"; // true 5 === "5"; // false
๐ง Logical Operators
&& // AND || // OR ! // NOT
Examples:
true && true; // true true && false; // false false || true; // true !true; // false
JavaScript returns the actual operands, not necessarily booleans:
"hello" && 42; // 42 null || "default"; // "default"
๐ Nullish Coalescing ??
Returns the right-hand value only when the left side is:
nullundefined
const value = input ?? "default";
Difference from ||:
0 || 100; // 100 0 ?? 100; // 0 "" || "fallback"; // "fallback" "" ?? "fallback"; // ""
Use ?? when 0, false, or "" are valid values.
โ Optional Chaining ?.
Safely access nested values.
const city = user?.address?.city;
Instead of:
const city = user && user.address && user.address.city;
Methods:
user.sayHello?.();
Arrays:
users?.[0];
Combined with ??:
const city = user?.address?.city ?? "Unknown";
๐ Control Flow
if / else
if (x > 10) { console.log("Big number!"); } else if (x === 10) { console.log("Exactly ten."); } else { console.log("Small number."); }
Ternary Operator
condition ? valueIfTrue : valueIfFalse;
Example:
const mood = isSunny ? "๐" : "โ";
Useful for short expressions:
const label = age >= 18 ? "Adult" : "Minor";
Avoid deeply nested ternaries when readability suffers.
switch
switch (fruit) { case "apple": console.log("๐"); break; case "banana": console.log("๐"); break; default: console.log("๐ฅ"); }
Multiple cases:
switch (day) { case "Saturday": case "Sunday": console.log("Weekend!"); break; default: console.log("Weekday"); }
๐ Loops
for
for (let i = 0; i < 5; i++) { console.log(i); }
while
let x = 0; while (x < 5) { console.log(x); x++; }
do...while
Runs at least once.
let x = 0; do { console.log(x); x++; } while (x < 5);
for...of
Iterates over values of iterables.
for (const item of array) { console.log(item); }
Works with:
arrays strings sets maps
Example:
for (const char of "JavaScript") { console.log(char); }
for...in
Iterates over enumerable property keys.
for (const key in object) { console.log(key, object[key]); }
Usually use for...of for arrays.
break
Stop a loop:
for (const number of numbers) { if (number === 5) { break; } console.log(number); }
continue
Skip the current iteration:
for (const number of numbers) { if (number % 2 === 0) { continue; } console.log(number); }
๐ฆ Arrays
Creation
const numbers = [1, 2, 3]; const empty = []; const generated = new Array(5);
Access
const arr = ["a", "b", "c"]; arr[0]; // "a" arr[1]; // "b" arr.length; // 3
Last item:
arr[arr.length - 1];
Modern alternative:
arr.at(-1); // "c"
at() supports negative indexes:
arr.at(0); // "a" arr.at(-1); // "c" arr.at(-2); // "b"
๐งฐ Array Mutation Methods
These modify the original array.
const arr = [1, 2, 3];
Add to End
arr.push(4);
// [1, 2, 3, 4]
Remove from End
arr.pop();
Add to Beginning
arr.unshift(0);
Remove from Beginning
arr.shift();
splice()
Add/remove elements.
arr.splice(start, deleteCount, ...items);
Remove:
const arr = ["a", "b", "c"]; arr.splice(1, 1); // arr โ ["a", "c"]
Insert:
arr.splice(1, 0, "new");
Replace:
arr.splice(1, 1, "replacement");
๐ง Non-Mutating Array Methods
slice()
const arr = [1, 2, 3, 4]; arr.slice(1, 3); // [2, 3]
Does not modify the original.
concat()
const a = [1, 2]; const b = [3, 4]; const combined = a.concat(b); // [1, 2, 3, 4]
Modern spread alternative:
const combined = [...a, ...b];
๐ Array Search Methods
includes()
[1, 2, 3].includes(2); // true
indexOf()
["a", "b", "c"].indexOf("b"); // 1
Returns -1 when not found.
find()
Returns the first matching value.
const users = [ { id: 1, name: "Alice" }, { id: 2, name: "Bob" } ]; const user = users.find(user => user.id === 2); // { id: 2, name: "Bob" }
findIndex()
const index = users.findIndex(user => user.id === 2); // 1
findLast()
const value = [1, 4, 7, 10].findLast(x => x < 10); // 7
findLastIndex()
[1, 4, 7, 10].findLastIndex(x => x < 10); // 2
๐ Array Iteration
.forEach()
Runs a function for every element.
arr.forEach(item => { console.log(item); });
Does not create a new array.
.map()
Transform every element.
const numbers = [1, 2, 3]; const doubled = numbers.map(x => x * 2); // [2, 4, 6]
Think:
one item in โ one item out
.filter()
Keep matching values.
const numbers = [1, 2, 3, 4]; const evens = numbers.filter(x => x % 2 === 0); // [2, 4]
Think:
Should this item stay?
.reduce()
Combine an array into one value.
const numbers = [1, 2, 3, 4]; const sum = numbers.reduce( (accumulator, current) => accumulator + current, 0 ); // 10
Mental model:
accumulator + next item โ new accumulator
Example:
[1, 2, 3].reduce((acc, x) => acc + x, 0);
Steps:
0 + 1 โ 1 1 + 2 โ 3 3 + 3 โ 6
Reduce to an object:
const words = ["apple", "banana", "apple"]; const counts = words.reduce((acc, word) => { acc[word] = (acc[word] ?? 0) + 1; return acc; }, {}); // { // apple: 2, // banana: 1 // }
.some()
Does at least one element match?
[1, 2, 3].some(x => x > 2); // true
.every()
Do all elements match?
[2, 4, 6].every(x => x % 2 === 0); // true
๐ Sorting Arrays
sort() mutates the array.
const numbers = [10, 2, 5]; numbers.sort(); // [10, 2, 5] ๐ฌ
By default values are sorted as strings.
Use a comparator:
numbers.sort((a, b) => a - b); // ascending
Descending:
numbers.sort((a, b) => b - a);
Objects:
users.sort((a, b) => a.age - b.age);
Alphabetically:
names.sort((a, b) => a.localeCompare(b));
Non-mutating modern alternative:
const sorted = numbers.toSorted((a, b) => a - b);
๐งฌ Other Array Methods
[1, 2, 3].join("-"); // "1-2-3" [1, [2, [3]]].flat(Infinity); // [1, 2, 3] [1, 2], [3, 4](/wiki/1,_2],_[3,_4).flat(); // [1, 2, 3, 4]
flatMap()
Equivalent to .map().flat(1):
const result = [1, 2, 3].flatMap(x => [x, x * 2]); // [1, 2, 2, 4, 3, 6]
๐งฑ Objects
Creation
const person = { name: "Alice", age: 25, greet() { console.log("Hello!"); } };
Property Access
Dot notation:
person.name;
Bracket notation:
person["age"];
Dynamic keys:
const key = "name"; person[key];
Add / Update Properties
person.job = "Engineer"; person.age = 26;
Delete Properties
delete person.age;
Check for Properties
"name" in person;
Preferred when checking own properties:
Object.hasOwn(person, "name");
๐ง Object Utilities
Object.keys(person);
// ["name", "age", "greet"]
Object.values(person);
// ["Alice", 25, ฦ]
Object.entries(person);
// [ // ["name", "Alice"], // ["age", 25], // ["greet", ฦ] // ]
Create object from entries:
Object.fromEntries([ ["name", "Alice"], ["age", 25] ]); // { name: "Alice", age: 25 }
๐ Copying Objects
Shallow copy:
const copy = { ...person };
Or:
const copy = Object.assign({}, person);
Override properties:
const updated = { ...person, age: 30 };
โ ๏ธ Shallow Copy Gotcha
Spread only copies one level deep.
const original = { profile: { name: "Alice" } }; const copy = { ...original }; copy.profile.name = "Bob"; console.log(original.profile.name); // "Bob"
For supported data structures, deep clone with:
const deepCopy = structuredClone(original);
๐ง Object Immutability Helpers
Prevent adding/removing/changing properties:
Object.freeze(obj);
Prevent adding/removing properties:
Object.seal(obj);
Check:
Object.isFrozen(obj); Object.isSealed(obj);
Object.freeze() is shallow.
๐งฉ Functions
Functions are first-class values.
They can be:
- assigned to variables
- passed as arguments
- returned from functions
- stored in objects and arrays
Function Declaration
function add(a, b) { return a + b; }
Function Expression
const multiply = function (a, b) { return a * b; };
Arrow Functions
const divide = (a, b) => { return a / b; };
Concise form:
const divide = (a, b) => a / b;
Single parameter:
const double = x => x * 2;
No parameters:
const hello = () => "Hello!";
Return an object:
const makeUser = name => ({ name, active: true });
๐น Arrow Functions & this
Arrow functions do not create their own this.
They inherit this lexically from their surrounding scope.
const obj = { value: 10, regular() { console.log(this.value); } };
Use regular methods when you need dynamic method this.
Arrow functions are great for callbacks:
items.map(item => item.id);
๐๏ธ Parameters
Default Parameters
function greet(name = "world") { return `Hello, ${name}!`; } greet(); // "Hello, world!"
Rest Parameters
function sum(...numbers) { return numbers.reduce((a, b) => a + b, 0); } sum(1, 2, 3, 4); // 10
Destructured Parameters
function greet({ name, age }) { console.log(`${name} is ${age}`); } greet({ name: "Alice", age: 25 });
๐ฆ Return Values
function add(a, b) { return a + b; }
Without return:
function test() {} test(); // undefined
return immediately exits the function:
function check(value) { if (!value) { return; } console.log(value); }
๐ง Higher-Order Functions
A function that accepts or returns another function.
function run(fn) { fn(); } run(() => { console.log("Hello!"); });
Returning a function:
function multiplyBy(multiplier) { return number => number * multiplier; } const double = multiplyBy(2); double(5); // 10
๐ Closures
Functions remember variables from the scope where they were created.
function createCounter() { let count = 0; return function () { count++; return count; }; } const counter = createCounter(); counter(); // 1 counter(); // 2 counter(); // 3
๐ช Strings
Strings are immutable.
const text = "Hello, world!";
Common Properties & Methods
text.length; // 13 text.toUpperCase(); // "HELLO, WORLD!" text.toLowerCase(); // "hello, world!" text.includes("world"); // true text.startsWith("Hello"); // true text.endsWith("!"); // true text.indexOf("o"); // 4 text.lastIndexOf("o"); // 8
Extracting Strings
text.slice(0, 5); // "Hello"
Negative indexes:
text.slice(-6); // "world!"
Splitting
"apple,banana,cherry".split(","); // ["apple", "banana", "cherry"]
Characters:
"abc".split(""); // ["a", "b", "c"]
Modern Unicode-friendly alternative:
Array.from("abc");
Trimming
" hello ".trim(); // "hello" " hello".trimStart(); // "hello" "hello ".trimEnd(); // "hello"
Replacing
"Hello Bob".replace("Bob", "Alice"); // "Hello Alice"
Replace all:
"a-b-a".replaceAll("a", "x"); // "x-b-x"
Padding
"5".padStart(2, "0"); // "05" "5".padEnd(3, "0"); // "500"
Repeating
"ha".repeat(3); // "hahaha"
โจ Template Literals
Use backticks:
const name = "Bob"; const greeting = `Hello, ${name}!`;
Expressions:
const price = 10; const quantity = 3; console.log(`Total: $${price * quantity}`);
Multiline:
const text = ` Line one Line two Line three `;
๐ฃ Numbers
JavaScript's normal number type uses floating-point arithmetic.
const integer = 42; const decimal = 3.14;
Scientific notation:
1e3; // 1000
Numeric separators:
const population = 8_000_000_000;
Hex:
0xff; // 255
Binary:
0b1010; // 10
๐ข Number Utilities
Number.isInteger(42); // true Number.isFinite(42); // true Number.isNaN(NaN); // true
Convert:
Number("42"); parseInt("42px", 10); parseFloat("3.14px");
Formatting:
(3.14159).toFixed(2); // "3.14"
โ ๏ธ .toFixed() returns a string.
๐งฎ Math
Math.PI; Math.E;
Common methods:
Math.abs(-5); // 5 Math.floor(3.9); // 3 Math.ceil(3.1); // 4 Math.round(3.5); // 4 Math.trunc(3.9); // 3 Math.max(1, 2, 3); // 3 Math.min(1, 2, 3); // 1 Math.sqrt(16); // 4 Math.cbrt(27); // 3 Math.pow(2, 3); // 8 2 ** 3; // 8
Random Numbers
Math.random();
Returns:
0 <= x < 1
Random integer from 0 to max - 1:
const random = Math.floor(Math.random() * max);
Random integer from min through max:
const random = Math.floor(Math.random() * (max - min + 1)) + min;
[!WARNING]
Math.random()is not suitable for cryptographic/security purposes.
In browsers, use cryptographically secure random values when needed:
crypto.getRandomValues(new Uint32Array(1));
โพ๏ธ Special Number Values
Infinity; -Infinity; NaN;
Examples:
1 / 0; // Infinity Number("hello"); // NaN
NaN is unusual:
NaN === NaN; // false
Use:
Number.isNaN(value);
๐งฎ BigInt
Use for integers larger than JavaScript's safe integer range.
const huge = 123456789012345678901234567890n;
Or:
const huge = BigInt("12345678901234567890");
BigInts cannot be directly mixed with regular numbers:
1n + 2n; // 3n // 1n + 2; // โ TypeError
๐ฐ๏ธ Dates
Current date/time:
const now = new Date();
Specific date:
const date = new Date("2026-08-27T12:00:00");
Useful Date Methods
now.getFullYear(); now.getMonth(); // 0 = January, 11 = December now.getDate(); // day of month now.getDay(); // 0 = Sunday, 6 = Saturday now.getHours(); now.getMinutes(); now.getSeconds(); now.getTime(); // Unix timestamp in milliseconds now.toISOString(); // ISO 8601 UTC string
Timestamp
Date.now();
Equivalent-ish to:
new Date().getTime();
๐ International Formatting
Use Intl.
Number Formatting
const formatter = new Intl.NumberFormat("en-US"); formatter.format(1234567.89); // "1,234,567.89"
Currency:
new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(1234.5); // "$1,234.50"
Date Formatting
new Intl.DateTimeFormat("en-US", { dateStyle: "long" }).format(new Date());
๐งฉ Destructuring
Arrays
const [a, b] = [1, 2]; console.log(a); // 1 console.log(b); // 2
Skip values:
const [first, , third] = [1, 2, 3];
Defaults:
const [x = 10] = [];
Rest:
const [first, ...rest] = [1, 2, 3, 4]; // first โ 1 // rest โ [2, 3, 4]
Objects
const user = { name: "Eve", age: 30 }; const { name, age } = user;
Rename:
const { name: username } = user;
Defaults:
const { role = "user" } = user;
Nested:
const { address: { city } } = user;
๐ Spread Syntax ...
Arrays
Copy:
const copy = [...arr];
Combine:
const combined = [...a, ...b];
Add:
const numbers = [1, 2, 3]; const more = [0, ...numbers, 4]; // [0, 1, 2, 3, 4]
Objects
Copy:
const copy = { ...person };
Merge:
const merged = { ...defaults, ...options };
Later properties win:
const result = { name: "Alice", ...{ name: "Bob" } }; result.name; // "Bob"
๐ฅ Rest Syntax ...
Collect remaining values.
function sum(...nums) { return nums.reduce((a, b) => a + b, 0); }
Object:
const { id, ...rest } = user;
Array:
const [first, ...others] = numbers;
๐บ๏ธ Maps
A Map stores key/value pairs and allows keys of any type.
const map = new Map(); map.set("name", "Alice"); map.set(42, "answer");
Get:
map.get("name"); // "Alice"
Check:
map.has("name"); // true
Delete:
map.delete("name");
Size:
map.size;
Loop:
for (const [key, value] of map) { console.log(key, value); }
Create directly:
const map = new Map([ ["name", "Alice"], ["age", 25] ]);
๐งบ Sets
A Set stores unique values.
const set = new Set(); set.add(1); set.add(2); set.add(2); console.log(set); // Set { 1, 2 }
Check:
set.has(2);
Delete:
set.delete(2);
Size:
set.size;
Remove duplicates:
const unique = [...new Set([1, 1, 2, 3, 3])]; // [1, 2, 3]
๐ WeakMap & WeakSet
WeakMap:
const weakMap = new WeakMap(); const obj = {}; weakMap.set(obj, "metadata");
WeakSet:
const weakSet = new WeakSet(); weakSet.add(obj);
They hold weak references to objects, allowing garbage collection when those objects are otherwise unreachable.
๐งฐ Classes
Basic Class
class Person { constructor(name, age) { this.name = name; this.age = age; } greet() { return `Hi, I'm ${this.name}`; } } const alice = new Person("Alice", 25); alice.greet();
Inheritance
class Developer extends Person { constructor(name, age, language) { super(name, age); this.language = language; } code() { return `${this.name} writes ${this.language}`; } }
Static Methods
class MathHelper { static double(value) { return value * 2; } } MathHelper.double(5); // 10
Private Fields
class Counter { #count = 0; increment() { this.#count++; } get value() { return this.#count; } }
Getters & Setters
class Person { constructor(first, last) { this.first = first; this.last = last; } get fullName() { return `${this.first} ${this.last}`; } set fullName(value) { [this.first, this.last] = value.split(" "); } }
๐งฌ Prototypes
JavaScript uses prototype-based inheritance under the hood.
const animal = { speak() { console.log("Animal sound"); } }; const dog = Object.create(animal); dog.speak();
Check prototype:
Object.getPrototypeOf(dog);
Classes are largely syntax built on top of prototypes.
๐ง this
this depends on how a function is called.
const person = { name: "Alice", greet() { console.log(this.name); } }; person.greet(); // "Alice"
Detached method:
const greet = person.greet; // greet(); // `this` is no longer `person`
๐ call(), apply(), bind()
call()
function greet(greeting) { console.log(`${greeting}, ${this.name}`); } const person = { name: "Alice" }; greet.call(person, "Hello");
apply()
Arguments as an array:
greet.apply(person, ["Hello"]);
bind()
Creates a new function:
const boundGreet = greet.bind(person); boundGreet("Hello");
๐๏ธ Modules
Named Exports
// math.js export const PI = 3.14159; export function add(a, b) { return a + b; }
Import:
import { PI, add } from "./math.js";
Default Export
// greet.js export default function greet() { console.log("Hello!"); }
Import:
import greet from "./greet.js";
Rename Imports
import { add as sum } from "./math.js";
Namespace Import
import * as math from "./math.js"; math.add(1, 2); math.PI;
Dynamic Import
const module = await import("./math.js"); module.add(1, 2);
Useful for lazy loading / code splitting.
๐ฆ CommonJS
Common in older Node.js projects.
Export:
module.exports = { add };
Import:
const { add } = require("./math");
Modern Node.js can also use ES modules.
โณ Promises
A Promise represents a future result.
States:
pending fulfilled rejected
Create a Promise
const promise = new Promise((resolve, reject) => { const success = true; if (success) { resolve("Done!"); } else { reject(new Error("Failed")); } });
.then()
promise.then(result => { console.log(result); });
.catch()
promise.catch(error => { console.error(error); });
.finally()
Runs regardless of success/failure:
promise.finally(() => { console.log("Finished"); });
โก Async / Await
async functions always return a Promise.
async function fetchData() { return "Done"; }
Equivalent conceptually to:
function fetchData() { return Promise.resolve("Done"); }
Use await inside async functions:
async function main() { const result = await fetchData(); console.log(result); }
Error Handling with Async/Await
async function loadData() { try { const result = await fetchData(); console.log(result); } catch (error) { console.error(error); } }
๐๏ธ Parallel Async Operations
Sequential:
const a = await fetchA(); const b = await fetchB();
If independent, run in parallel:
const [a, b] = await Promise.all([ fetchA(), fetchB() ]);
๐ค Promise Helpers
Promise.all()
All must succeed.
const results = await Promise.all([ promise1, promise2, promise3 ]);
Rejects if any promise rejects.
Promise.allSettled()
Waits for everything:
const results = await Promise.allSettled([ promise1, promise2 ]);
Results look like:
[ { status: "fulfilled", value: "..." }, { status: "rejected", reason: Error(...) } ]
Promise.race()
First settled Promise wins.
await Promise.race([ request, timeout ]);
Promise.any()
First fulfilled Promise wins.
await Promise.any([ serverA(), serverB() ]);
Rejects only if all promises reject.
๐ Fetch API
GET:
const response = await fetch( "https://api.example.com/users" ); const data = await response.json();
Check HTTP status:
if (!response.ok) { throw new Error( `HTTP error: ${response.status}` ); }
POST Request
const response = await fetch( "https://api.example.com/users", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "Alice" }) } );
Robust Fetch Pattern
async function getUser(id) { const response = await fetch( `/api/users/${id}` ); if (!response.ok) { throw new Error( `Request failed: ${response.status}` ); } return response.json(); }
๐ Abort a Fetch
const controller = new AbortController(); fetch("/api/data", { signal: controller.signal }); controller.abort();
Timeout pattern:
const controller = new AbortController(); setTimeout(() => { controller.abort(); }, 5000);
๐จ Errors
Throw an Error
throw new Error("Something went wrong");
Built-in error types include:
Error TypeError ReferenceError SyntaxError RangeError URIError AggregateError
๐ก๏ธ try / catch / finally
try { riskyOperation(); } catch (error) { console.error(error); } finally { console.log("Always runs"); }
Inspect:
error.name; error.message; error.stack;
Custom Error
class ValidationError extends Error { constructor(message) { super(message); this.name = "ValidationError"; } } throw new ValidationError( "Invalid username" );
๐งพ JSON
Object โ JSON
const obj = { name: "Anna", age: 22 }; const json = JSON.stringify(obj);
Result:
{"name":"Anna","age":22}
Pretty format:
JSON.stringify(obj, null, 2);
JSON โ Object
const parsed = JSON.parse(json);
JSON Limitations
JSON cannot directly represent:
undefined functions symbols BigInt Map Set
Dates become strings when serialized.
๐ค Regular Expressions
Create:
const regex = /hello/i;
Test:
regex.test("Hello world"); // true
Match:
"abc123".match(/\d+/); // ["123"]
Replace:
"abc123".replace(/\d+/, "456"); // "abc456"
Common Regex Tokens
. any character \d digit \D non-digit \w word character \W non-word character \s whitespace \S non-whitespace ^ start $ end * zero or more + one or more ? zero or one {n} exactly n {n,m} n through m [...] character set (...) group | OR
Flags:
g global i case-insensitive m multiline s dotAll u Unicode y sticky
๐ Iterators
Objects can implement the iterator protocol.
const iterator = [10, 20][Symbol.iterator](); iterator.next(); // { value: 10, done: false } iterator.next(); // { value: 20, done: false } iterator.next(); // { value: undefined, done: true }
โ๏ธ Generators
Generator functions pause and resume execution.
function* numbers() { yield 1; yield 2; yield 3; } for (const number of numbers()) { console.log(number); }
Manual use:
const generator = numbers(); generator.next(); generator.next();
๐ชช Symbols
Symbols create unique primitive values.
const id = Symbol("id"); const user = { [id]: 123 };
Even symbols with identical descriptions differ:
Symbol("id") === Symbol("id"); // false
๐งฎ Equality Details
Strict Equality
1 === 1; // true 1 === "1"; // false
Objects Compare by Reference
{} === {}; // false [] === []; // false
Example:
const a = {}; const b = a; a === b; // true
For the special NaN and signed-zero cases:
Object.is(NaN, NaN); // true Object.is(0, -0); // false
๐ช Value vs Reference Behavior
Primitives behave like copied values:
let a = 10; let b = a; b = 20; console.log(a); // 10
Objects hold references:
const a = { value: 10 }; const b = a; b.value = 20; console.log(a.value); // 20
๐ง Short-Circuiting
AND &&
isLoggedIn && showDashboard();
Equivalent idea:
if (isLoggedIn) { showDashboard(); }
OR ||
const username = inputName || "Anonymous";
Be careful with valid falsy values such as 0.
Nullish ??
const count = inputCount ?? 0;
Usually safer for defaults.
๐งช Type Checking
Primitive:
typeof value === "string"; typeof value === "number"; typeof value === "boolean";
Array:
Array.isArray(value);
Class / constructor:
value instanceof Date; value instanceof Map; value instanceof Set;
Null:
value === null;
NaN:
Number.isNaN(value);
Finite number:
Number.isFinite(value);
๐ Browser APIs
Alerts
alert("Hello!");
Prompt:
const name = prompt( "Enter your name:" );
Confirmation:
const confirmed = confirm( "Are you sure?" );
๐งฑ DOM Selection
Single element:
const element = document.querySelector(".item");
Multiple elements:
const elements = document.querySelectorAll(".item");
By ID:
const element = document.getElementById("app");
โ๏ธ DOM Manipulation
Text:
element.textContent = "Hello!";
HTML:
element.innerHTML = "<strong>Hello!</strong>";
[!WARNING] Avoid inserting untrusted content with
innerHTML; doing so can introduce XSS vulnerabilities.
Attributes:
element.setAttribute( "aria-label", "Close" ); element.getAttribute("aria-label"); element.removeAttribute("aria-label");
๐จ Classes & Styles
element.classList.add("active"); element.classList.remove("active"); element.classList.toggle("active"); element.classList.contains("active");
Inline styles:
element.style.display = "none";
Prefer CSS classes for larger styling changes.
๐๏ธ Creating DOM Elements
const button = document.createElement("button"); button.textContent = "Click me"; document.body.append(button);
Other methods:
parent.append(child); parent.prepend(child); element.before(other); element.after(other); element.remove();
๐ฑ๏ธ Events
button.addEventListener( "click", event => { console.log("Clicked!"); } );
Common events:
click dblclick input change submit keydown keyup focus blur mouseover mouseout DOMContentLoaded
Event Object
button.addEventListener( "click", event => { console.log(event.target); console.log(event.currentTarget); } );
Prevent Default
form.addEventListener( "submit", event => { event.preventDefault(); } );
Stop Propagation
event.stopPropagation();
๐ซง Event Bubbling
Events generally bubble upward through ancestors.
<div id="parent"> <button id="child"> Click </button> </div>
A click on the button can trigger handlers on both:
button โ parent โ document
๐ฏ Event Delegation
Instead of attaching a listener to every child:
list.addEventListener( "click", event => { const button = event.target.closest("button"); if (!button) return; console.log(button.dataset.id); } );
Useful for dynamically created elements.
๐ท๏ธ Data Attributes
HTML:
<button data-user-id="42"> View </button>
JavaScript:
button.dataset.userId; // "42"
Dataset values are strings.
โฒ๏ธ Timers
setTimeout()
Run once:
const timer = setTimeout(() => { console.log("Hello!"); }, 1000);
Cancel:
clearTimeout(timer);
setInterval()
Repeat:
const timer = setInterval(() => { console.log("Tick"); }, 2000);
Cancel:
clearInterval(timer);
๐๏ธ Animation
For browser visual updates:
requestAnimationFrame(() => { // update animation });
Recurring:
function animate() { // update frame requestAnimationFrame(animate); } requestAnimationFrame(animate);
๐พ Web Storage
localStorage
Persists across browser sessions.
localStorage.setItem( "theme", "dark" ); localStorage.getItem( "theme" ); localStorage.removeItem( "theme" ); localStorage.clear();
Stores strings only.
Objects:
localStorage.setItem( "user", JSON.stringify(user) ); const user = JSON.parse( localStorage.getItem("user") );
sessionStorage
Same style API, but typically scoped to the browser tab/session.
sessionStorage.setItem( "step", "2" );
๐ URL Utilities
URL
const url = new URL( "https://example.com/search?q=js" ); url.hostname; // "example.com" url.pathname; // "/search" url.searchParams.get("q"); // "js"
URLSearchParams
const params = new URLSearchParams(); params.set("page", "2"); params.set("sort", "new"); params.toString(); // "page=2&sort=new"
๐ Encoding URLs
encodeURIComponent( "hello world" ); // "hello%20world"
Decode:
decodeURIComponent( "hello%20world" ); // "hello world"
๐ Browser Location
window.location.href; window.location.hostname; window.location.pathname; window.location.search;
Navigate:
window.location.href = "/dashboard";
๐ Clipboard
Modern browsers:
await navigator.clipboard.writeText( "Hello!" );
Read:
const text = await navigator.clipboard.readText();
Permission/security requirements may apply.
๐งต The Event Loop
JavaScript generally executes code on a single call stack.
Simplified model:
Call Stack โ Web/Runtime APIs โ Task Queues โ Event Loop โ Call Stack
Example:
console.log("A"); setTimeout(() => { console.log("B"); }, 0); console.log("C");
Output:
A C B
โก Microtasks vs Tasks
Promise callbacks use the microtask queue.
console.log("A"); setTimeout(() => { console.log("timeout"); }, 0); Promise.resolve().then(() => { console.log("promise"); }); console.log("B");
Output:
A B promise timeout
A simplified priority:
current synchronous code โ microtasks โ tasks / timers
๐งต Async Timing Gotcha
This does not wait one second before each iteration:
items.forEach(async item => { await process(item); });
For sequential processing:
for (const item of items) { await process(item); }
For parallel processing:
await Promise.all( items.map(item => process(item)) );
๐ฆ Useful Built-in Methods
Arrays
Array.isArray([1, 2]); // true Array.from("abc"); // ["a", "b", "c"] Array.from({ length: 5 }, (_, i) => i); // [0, 1, 2, 3, 4]
Objects
Object.keys(obj); Object.values(obj); Object.entries(obj); Object.fromEntries(entries); Object.assign({}, obj); Object.hasOwn(obj, "key");
Strings
str.includes("x"); str.startsWith("x"); str.endsWith("x"); str.trim(); str.slice(0, 5); str.split(","); str.replace("a", "b"); str.replaceAll("a", "b");
๐งน Modern Immutable Array Helpers
Traditional methods often mutate arrays:
arr.sort(); arr.reverse(); arr.splice();
Modern non-mutating alternatives include:
arr.toSorted(); arr.toReversed(); arr.toSpliced(); arr.with(index, value);
Example:
const arr = [3, 1, 2]; const sorted = arr.toSorted((a, b) => a - b); // sorted โ [1, 2, 3] // arr โ [3, 1, 2]
Replace without mutation:
const next = arr.with(1, 99);
๐งช Console & Debugging
Basic:
console.log("value:", x); console.info("Info"); console.warn("Caution!"); console.error( "Something broke!" );
Objects:
console.dir(obj);
Table:
console.table([ { name: "Alice", age: 25 }, { name: "Bob", age: 30 } ]);
Timing:
console.time("operation"); doSomething(); console.timeEnd("operation");
Group:
console.group("User"); console.log(user.name); console.log(user.age); console.groupEnd();
Breakpoint:
debugger;
โ Assertions
console.assert( age >= 18, "Expected adult" );
Useful during development.
๐ช Shorthand Syntax
Property Shorthand
Instead of:
const name = "Alice"; const user = { name: name };
Use:
const name = "Alice"; const user = { name };
Method Shorthand
Instead of:
const obj = { greet: function () { console.log("Hi"); } };
Use:
const obj = { greet() { console.log("Hi"); } };
Computed Property Names
const key = "username"; const user = { [key]: "Alice" };
Result:
{ username: "Alice" }
๐งช Common Patterns
Swap Variables
[a, b] = [b, a];
Remove Duplicates
const unique = [...new Set(array)];
Clone an Array
const copy = [...array];
Clone an Object
const copy = { ...object };
Deep Clone Supported Data
const copy = structuredClone(object);
Flatten an Array
array.flat(Infinity);
Count Object Keys
Object.keys(obj).length;
Reverse a String
Basic ASCII-style approach:
str .split("") .reverse() .join("");
More Unicode-friendly:
[...str] .reverse() .join("");
Convert Array Values to Strings
[1, 2, 3].map(String); // ["1", "2", "3"]
Sum an Array
const sum = numbers.reduce( (total, n) => total + n, 0 );
Maximum Array Value
Math.max(...numbers);
Minimum:
Math.min(...numbers);
Group Items
Manual reduce():
const grouped = users.reduce((acc, user) => { const role = user.role; (acc[role] ??= []).push(user); return acc; }, {});
Where supported, modern grouping helpers may also be available:
Object.groupBy( users, user => user.role );
๐ง Memoization Pattern
Cache expensive results:
function memoize(fn) { const cache = new Map(); return function (value) { if (cache.has(value)) { return cache.get(value); } const result = fn(value); cache.set(value, result); return result; }; }
โณ Delay Utility
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms) );
Use:
await sleep(1000);
๐ฏ Debounce Pattern
Wait until calls stop for a period.
function debounce(fn, delay) { let timeout; return (...args) => { clearTimeout(timeout); timeout = setTimeout(() => { fn(...args); }, delay); }; }
Useful for:
search inputs window resizing autosave validation
๐ฆ Throttle Pattern
Limit how often a function runs.
function throttle(fn, delay) { let waiting = false; return (...args) => { if (waiting) return; fn(...args); waiting = true; setTimeout(() => { waiting = false; }, delay); }; }
Useful for:
scroll events mousemove resize rapid UI updates
๐งฉ Property Descriptors
Inspect a property:
Object.getOwnPropertyDescriptor( obj, "name" );
Define one:
Object.defineProperty( obj, "id", { value: 123, writable: false, enumerable: true, configurable: false } );
๐งฌ Enumeration
Own enumerable keys:
Object.keys(obj);
Own property names:
Object.getOwnPropertyNames(obj);
Own symbols:
Object.getOwnPropertySymbols(obj);
All own keys:
Reflect.ownKeys(obj);
๐ช Reflect
Examples:
Reflect.get(obj, "name"); Reflect.set(obj, "name", "Alice"); Reflect.has(obj, "name"); Reflect.deleteProperty( obj, "name" );
๐ต๏ธ Proxy
Intercept operations on an object.
const user = { name: "Alice" }; const proxy = new Proxy(user, { get(target, property) { console.log( `Reading ${String(property)}` ); return target[property]; } }); proxy.name;
Useful for advanced patterns such as:
validation reactivity logging virtual properties
๐ง Memory & Garbage Collection
JavaScript automatically manages memory.
Objects become eligible for garbage collection when they are no longer reachable.
let user = { name: "Alice" }; user = null;
Avoid unintentionally keeping references alive through:
forgotten event listeners timers large caches closures global variables
๐ Operator Precedence
When uncertain, use parentheses.
Instead of relying on:
a + b * c
make intent explicit:
a + (b * c);
or:
(a + b) * c;
๐ข Bitwise Operators
JavaScript also supports:
& // AND | // OR ^ // XOR ~ // NOT << // left shift >> // signed right shift >>> // unsigned right shift
Example:
5 & 1; // 1
These operate on 32-bit integer representations for normal numbers and are less common in everyday application code.
๐ก๏ธ Strict Mode
Enable stricter JavaScript behavior:
"use strict";
ES modules are strict by default.
Strict mode helps prevent some silent mistakes.
๐ Global Objects
Depending on environment:
Browser:
window; document; navigator; location;
Cross-environment global:
globalThis;
Node.js historically exposes:
global;
Prefer globalThis when you need a standardized global reference.
๐ฅ๏ธ Browser vs Node.js
JavaScript is the language.
The environment provides additional APIs.
Browser
window document DOM localStorage navigator fetch
Node.js
Common Node APIs include:
process Buffer filesystem APIs server/network APIs
Not every browser API exists in Node, and vice versa.
๐ Node.js Basics
Environment variables:
process.env.API_KEY;
Arguments:
process.argv;
Exit code:
process.exitCode = 1;
ES module imports:
import fs from "node:fs";
๐ก๏ธ Safer JavaScript Habits
Prefer:
const let === !== ?. ?? async/await Number.isNaN() Array.isArray() Object.hasOwn()
Avoid relying heavily on:
var == != eval() implicit globals deeply nested callbacks untrusted innerHTML
โ ๏ธ eval()
Avoid:
eval(userInput);
eval() executes strings as JavaScript and creates serious security and maintainability problems, especially with untrusted input.
๐งผ Clean Code Patterns
Guard Clauses
Instead of:
function processUser(user) { if (user) { if (user.active) { // lots of logic } } }
Prefer:
function processUser(user) { if (!user) return; if (!user.active) return; // main logic }
Name Booleans Like Questions
const isLoggedIn = true; const hasPermission = false; const canEdit = true; const shouldRetry = false;
Prefer Intent-Revealing Names
Less clear:
const x = users.filter(u => u.a);
Clearer:
const activeUsers = users.filter( user => user.isActive );
๐ง Common Gotchas
typeof null
typeof null; // "object"
Historical quirk.
Use:
value === null;
NaN
NaN === NaN; // false
Use:
Number.isNaN(value);
Floating-Point Arithmetic
0.1 + 0.2 === 0.3; // false
Because:
0.1 + 0.2; // 0.30000000000000004
For approximate comparison:
Math.abs( (0.1 + 0.2) - 0.3 ) < Number.EPSILON;
For financial calculations, consider using integer minor units when appropriate:
const cents = 1999;
instead of relying blindly on binary floating-point currency arithmetic.
Loose Equality Weirdness
[] == ![]; // true
Another reason to prefer:
===
Empty Arrays / Objects Are Truthy
Boolean([]); // true Boolean({}); // true
Objects Are Compared by Reference
{ a: 1 } === { a: 1 }; // false
Array sort() Mutates
const original = [3, 1, 2]; original.sort(); console.log(original); // [1, 2, 3]
Use:
const sorted = original.toSorted();
or:
const sorted = [...original].sort();
forEach() Cannot Be Broken Normally
This doesn't behave like a loop break:
arr.forEach(item => { // break; โ });
Use:
for (const item of arr) { if (condition) break; }
or methods like:
find() some() every()
Async forEach()
Avoid:
items.forEach(async item => { await save(item); });
Sequential:
for (const item of items) { await save(item); }
Parallel:
await Promise.all( items.map(save) );
const Objects Can Change
const arr = []; arr.push(1); // โ
But:
// arr = []; // โ
delete Doesn't Remove Array Slots Cleanly
const arr = [ "a", "b", "c" ]; delete arr[1]; console.log(arr.length); // 3
Prefer:
arr.splice(1, 1);
or non-mutating:
const next = arr.filter( (_, index) => index !== 1 );
โก One-Liners Worth Remembering
Remove duplicates:
[...new Set(array)];
Flatten deeply:
array.flat(Infinity);
Count keys:
Object.keys(obj).length;
Reverse a string:
[...str].reverse().join("");
Convert to strings:
[1, 2, 3].map(String);
Sum:
array.reduce( (sum, value) => sum + value, 0 );
Clone an object:
const copy = { ...obj };
Clone an array:
const copy = [...arr];
Deep clone:
structuredClone(value);
Swap:
[a, b] = [b, a];
Random item:
array[ Math.floor( Math.random() * array.length ) ];
Last item:
array.at(-1);
Compact truthy values:
array.filter(Boolean);
[!WARNING]
.filter(Boolean)also removes valid falsy values such as0,false, and"".
Object โ query parameters:
new URLSearchParams(obj) .toString();
๐ง map vs filter vs reduce
Remember:
map โ Transform each item โ Same number of items
[1, 2, 3] .map(x => x * 2); // [2, 4, 6]
filter โ Choose which items remain โ Zero to original number of items
[1, 2, 3, 4] .filter(x => x % 2 === 0); // [2, 4]
reduce โ Combine everything โ Anything you want
[1, 2, 3] .reduce( (sum, x) => sum + x, 0 ); // 6
๐ Common Array Method Decision Tree
Need to process an array? โ โโ Do something for every element โ โโ forEach() โ โโ Transform every element โ โโ map() โ โโ Keep matching elements โ โโ filter() โ โโ Find one matching element โ โโ find() โ โโ Find its index โ โโ findIndex() โ โโ Check if at least one matches โ โโ some() โ โโ Check if all match โ โโ every() โ โโ Combine everything โ โโ reduce() โ โโ Check whether value exists โ โโ includes() โ โโ Need full loop control โโ for...of
๐ null vs undefined
undefined
Usually means:
A value has not been assigned / does not exist.
let value; console.log(value); // undefined
Missing property:
const obj = {}; obj.name; // undefined
null
Usually intentionally represents:
No value.
const selectedUser = null;
Common pattern:
if (selectedUser === null) { console.log( "No user selected" ); }
๐ฌ undefined, null, and ??
undefined ?? "fallback"; // "fallback" null ?? "fallback"; // "fallback" false ?? "fallback"; // false 0 ?? "fallback"; // 0 "" ?? "fallback"; // ""
๐ชข Function Syntax Comparison
function add(a, b) { return a + b; }
const add = function (a, b) { return a + b; };
const add = (a, b) => { return a + b; };
const add = (a, b) => a + b;
๐งญ Common JavaScript Naming Conventions
Variables/functions:
camelCase
Examples:
const userName = "Alice"; function calculateTotal() {}
Classes:
PascalCase
class UserProfile {}
Constants that are truly configuration-like constants sometimes use:
UPPER_SNAKE_CASE
const MAX_RETRIES = 3;
Private class fields:
#privateField
๐งช Useful Validation Examples
String:
if ( typeof username !== "string" ) { throw new TypeError( "username must be a string" ); }
Array:
if (!Array.isArray(items)) { throw new TypeError( "items must be an array" ); }
Number:
if ( typeof value !== "number" || !Number.isFinite(value) ) { throw new TypeError( "Expected a finite number" ); }
๐ Safe Property Access
Instead of:
const city = user && user.address && user.address.city;
Use:
const city = user?.address?.city;
With fallback:
const city = user?.address?.city ?? "Unknown";
๐ Async Cheat Sheet
Promise chain:
fetchData() .then(data => { return processData(data); }) .then(result => { console.log(result); }) .catch(error => { console.error(error); });
Equivalent async/await style:
async function main() { try { const data = await fetchData(); const result = await processData(data); console.log(result); } catch (error) { console.error(error); } }
๐ก Basic API Request Pattern
async function fetchUsers() { const response = await fetch("/api/users"); if (!response.ok) { throw new Error( `HTTP ${response.status}` ); } const users = await response.json(); return users; }
Use:
try { const users = await fetchUsers(); console.log(users); } catch (error) { console.error( "Could not fetch users:", error ); }
๐ ๏ธ Common Utility Functions
Clamp a Number
const clamp = ( value, min, max ) => Math.min( Math.max(value, min), max );
clamp(15, 0, 10); // 10
Capitalize
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
Random Integer
const randomInt = ( min, max ) => Math.floor( Math.random() * (max - min + 1) ) + min;
Chunk an Array
function chunk(array, size) { const result = []; for ( let i = 0; i < array.length; i += size ) { result.push( array.slice(i, i + size) ); } return result; }
Unique by Property
const uniqueById = [ ...new Map( users.map(user => [ user.id, user ]) ).values() ];
๐ JSDoc Basics
Document functions:
/** * Adds two numbers. * * @param {number} a * @param {number} b * @returns {number} */ function add(a, b) { return a + b; }
Object type:
/** * @typedef {Object} User * @property {number} id * @property {string} name */
JSDoc can improve editor autocomplete and static analysis even without TypeScript.
๐งช Testing Mindset
A simple function:
function add(a, b) { return a + b; }
Simple assertion:
console.assert( add(2, 3) === 5, "add() failed" );
Typical test structure:
Arrange Act Assert
Example:
const input = [1, 2, 3]; const result = input.map(x => x * 2); console.assert( JSON.stringify(result) === JSON.stringify( [2, 4, 6] ) );
Production projects normally use dedicated testing tools rather than console.assert().
๐ง Common Performance Tips
Prefer clear code first.
Useful principles:
- Avoid unnecessary repeated work inside loops.
- Use
Map/Setfor appropriate fast lookups. - Avoid repeatedly querying the DOM when you can reuse a reference.
- Batch DOM updates when practical.
- Debounce noisy input events.
- Throttle frequent scroll/resize handlers.
- Run independent async operations concurrently.
- Avoid premature optimization.
- Profile before assuming where a bottleneck is.
๐ Security Basics
Never Trust User Input
Validate on the client when useful:
if (!email.includes("@")) { // show validation }
But server-side validation is still required.
Avoid Untrusted innerHTML
Risky:
element.innerHTML = userInput;
Safer for plain text:
element.textContent = userInput;
Don't Expose Secrets in Frontend Code
Anything shipped to a browser can be inspected.
Don't put secret API keys in:
const SECRET_API_KEY = "super-secret";
Use a trusted server when credentials must remain private.
๐ Reserved / Common Keywords
Examples:
break case catch class const continue debugger default delete do else export extends finally for function if import in instanceof let new return static super switch this throw try typeof var void while with yield async await
Don't use reserved keywords as variable identifiers where prohibited.
๐ง Quick Syntax Reference
Variable
const x = 10; let y = 20;
Function
const add = (a, b) => a + b;
Array
const arr = [1, 2, 3];
Object
const obj = { name: "Alice" };
Conditional
if (condition) { // ... } else { // ... }
Loop
for (const item of items) { // ... }
Async
const value = await promise;
Error Handling
try { // ... } catch (error) { // ... }
Import
import { something } from "./module.js";
Export
export const value = 42;
๐ Mutating vs Non-Mutating Methods
| Method | Mutates? | Purpose |
|---|---|---|
.push() | โ | Add to end |
.pop() | โ | Remove last |
.shift() | โ | Remove first |
.unshift() | โ | Add to start |
.splice() | โ | Add/remove at index |
.sort() | โ | Sort |
.reverse() | โ | Reverse |
.fill() | โ | Replace range |
.copyWithin() | โ | Copy array section |
.map() | โ | Transform |
.filter() | โ | Filter |
.reduce() | โ | Aggregate |
.slice() | โ | Extract |
.concat() | โ | Combine |
.flat() | โ | Flatten |
.flatMap() | โ | Map + flatten |
.toSorted() | โ | Immutable sort |
.toReversed() | โ | Immutable reverse |
.toSpliced() | โ | Immutable splice |
.with() | โ | Immutable replacement |
๐ Array Method Summary
| Method | Returns | Typical Use |
|---|---|---|
.forEach() | undefined | Side effects |
.map() | Array | Transform values |
.filter() | Array | Keep matches |
.find() | Value / undefined | Find first match |
.findIndex() | Number | Find match index |
.some() | Boolean | Any match? |
.every() | Boolean | All match? |
.reduce() | Anything | Aggregate |
.includes() | Boolean | Contains value? |
.indexOf() | Number | Locate value |
.slice() | Array | Copy section |
.splice() | Array of removed items | Mutate contents |
.flat() | Array | Flatten |
.flatMap() | Array | Transform + flatten |
.join() | String | Join values |
๐ Equality Cheat Sheet
| Expression | Result |
|---|---|
5 === 5 | true |
5 === "5" | false |
5 == "5" | true |
null === undefined | false |
null == undefined | true |
NaN === NaN | false |
Object.is(NaN, NaN) | true |
[] === [] | false |
{} === {} | false |
Rule of thumb:
Use === and !==
๐ || vs ??
| Value | value || "X" | value ?? "X" |
|---|---|---|
| undefined | "X" | "X" |
| null | "X" | "X" |
| false | "X" | false |
| 0 | "X" | 0 |
| "" | "X" | "" |
| "hello" | "hello" | "hello" |
๐ for...of vs for...in
| Loop | Iterates | Best For |
|---|---|---|
for...of | Values | Arrays, strings, sets, maps |
for...in | Property keys | Objects |
Example:
const arr = ["a", "b"];
for (const value of arr) { console.log(value); } // a // b
for (const key in arr) { console.log(key); } // "0" // "1"
๐ Collection Cheat Sheet
| Structure | Keys | Unique Values | Ordered Iteration | Typical Use |
|---|---|---|---|---|
Array | Numeric indexes | โ | โ | Lists |
Object | String/Symbol | N/A | Mostly predictable | Records |
Map | Any value | Keys unique | โ | Key/value dictionary |
Set | N/A | โ | โ | Unique values |
WeakMap | Objects | Keys unique | โ enumerable | Object metadata |
WeakSet | Objects | โ | โ enumerable | Object membership |
๐ Function Choices
| Syntax | Own this? | Hoisted? | Good For |
|---|---|---|---|
function foo() {} | โ | โ | General functions |
const foo = function() {} | โ | โ usable-before-declaration | Function expressions |
const foo = () => {} | โ lexical this | โ usable-before-declaration | Callbacks / concise functions |
method() {} | โ contextual | N/A | Object/class methods |
๐ง Debugging Checklist
When something breaks:
- Check the console.
- Read the full error message.
- Read the stack trace.
- Verify variable values.
- Verify types with
typeof. - Check
null/undefined. - Check array indexes.
- Confirm asynchronous operations are awaited.
- Check whether a method mutates the original.
- Check object reference sharing.
- Check spelling/case sensitivity.
- Check import/export names.
- Verify API response status.
- Inspect actual API response data.
- Add a breakpoint with
debugger. - Reduce the issue to the smallest reproducible example.
๐ง Error Message Translator
ReferenceError
x is not defined
Usually means:
You're using a variable that doesn't exist in the current scope.
TypeError
Cannot read properties of undefined
Usually means:
something.foo
when something is undefined or null.
Try:
something?.foo;
โbut also determine why the value is missing.
SyntaxError
Usually malformed JavaScript:
const x = ;
... is not a function
Example:
user.map is not a function
You expected a function/method but got another type.
Check:
console.log(user); console.log(typeof user);
Assignment to constant variable
const x = 1; x = 2; // โ
Use let if reassignment is intended.
๐ญ Mental Models Worth Remembering
Variables
const โ name cannot be reassigned let โ name can be reassigned
Objects
Objects are references. Copies made with spread are shallow.
Arrays
map โ transform filter โ select reduce โ combine find โ locate one some โ any? every โ all?
Async
Promise โ value later await โ pause this async function until it settles
Optional chaining
?. โ stop safely if null/undefined
Nullish coalescing
?? โ fallback only for null/undefined
Spread
... โ unpack
Rest
... โ collect
Same syntax, different context.
๐ Modern JavaScript Starter Template
import { getUsers } from "./api.js"; async function main() { try { const users = await getUsers(); const activeUsers = users .filter( user => user.isActive ) .map(user => ({ id: user.id, name: user.name ?? "Unknown" })); console.table(activeUsers); } catch (error) { console.error( "Application failed:", error ); } } main();
๐ง TL;DR Mind Map
| Area | Example | Remember |
|---|---|---|
| Variables | const, let | Prefer const |
| Types | string, number, object | Arrays are objects |
| Equality | ===, !== | Avoid loose equality |
| Truthiness | if (value) | [] and {} are truthy |
| Functions | () => {} | Arrows have lexical this |
| Arrays | .map() | Transform |
| Arrays | .filter() | Select |
| Arrays | .reduce() | Combine |
| Objects | { key: value } | Reference values |
| Copies | { ...obj } | Shallow copy |
| Strings | `Hi ${name}` | Template literals |
| Defaults | ?? | Null/undefined fallback |
| Safe access | ?. | Optional chaining |
| Collections | Map, Set | Specialized collections |
| Async | async/await | Promise-friendly syntax |
| Parallel async | Promise.all() | Run independent work together |
| HTTP | fetch() | Check response.ok |
| Modules | import/export | Standard module system |
| Errors | try/catch | Handle expected failure |
| Classes | class Foo {} | Prototype-based underneath |
| DOM | querySelector() | Find elements |
| Events | addEventListener() | React to browser events |
| Storage | localStorage | Stores strings |
| JSON | JSON.parse() | JSON โ JavaScript |
| Debugging | console.log() | Inspect reality, not assumptions |
โก The 20% That Solves 80%
If you're rusty, remember these first:
// Variables const x = 10; let y = 20; // Function const add = (a, b) => a + b; // Array transformation const names = users.map( user => user.name ); // Array filtering const active = users.filter( user => user.active ); // Find one const user = users.find( user => user.id === id ); // Reduce const total = prices.reduce( (sum, price) => sum + price, 0 ); // Object destructuring const { name, age } = user; // Spread const updatedUser = { ...user, active: true }; // Optional chaining const city = user?.address?.city; // Nullish default const name = user?.name ?? "Unknown"; // Conditional if (user) { console.log(user); } // Loop for (const item of items) { console.log(item); } // Async const data = await fetchData(); // Error handling try { await save(); } catch (error) { console.error(error); }
๐ Final Rules of Thumb
- Prefer
const; useletwhen reassignment is required. - Avoid
varin modern code unless you specifically need its legacy semantics. - Prefer
===and!==. - Use
.map()to transform. - Use
.filter()to select. - Use
.find()when you need one matching value. - Use
.reduce()when combining values actually makes the code clearer. - Prefer
for...ofwhen you need normal loop control. - Remember that objects and arrays are reference values.
- Spread syntax creates shallow, not deep, copies.
- Use
structuredClone()when an appropriate deep clone is needed. - Use
?.for safe nested access. - Use
??instead of||when0,false, and""are valid. - Use
async/awaitfor readable asynchronous code. - Use
Promise.all()for independent async operations that can run concurrently. - Always check
response.okwhen usingfetch(). - Handle failures with
try/catchwhere recovery or reporting matters. - Don't insert untrusted strings with
innerHTML. - Don't put secrets in client-side JavaScript.
- When confused, log the actual value and type.
console.log({ value, type: typeof value });
[!QUOTE] โJavaScript is the worldโs most misunderstood language โ until you understand it.โ
[!TIP] When JavaScript feels weird, ask three questions:
- What type is this value?
- Is this object being mutated or copied?
- Is this code synchronous or asynchronous?
Those three questions explain a surprisingly large percentage of JavaScript bugs.
๐ See Also
Backlinks (3)
- General
- User
No backlinks yet.
- Redirects
- Media
No backlinks yet.
- Categories
No backlinks yet.
Categories (0)
No categories assigned to this page.
Edit Level
> Signed In Users
Latest on Lounge
Join the conversation about the 'JavaScript/Cheat sheet' article โ
No comments yet. Be the first to comment!