JavaScript/Cheat sheet

Last edited by disfordave on 27/08/2026, 05:50:42 UTC

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

NeedUse
Declare a valueconst x = 1
Reassign a valuelet x = 1
String interpolation`Hello ${name}`
Strict comparisona === b
Default fallbackvalue ?? fallback
Safe property accessuser?.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 Promiseawait promise
Handle errorstry { ... } catch (err) { ... }
Convert JSON โ†’ objectJSON.parse()
Convert object โ†’ JSONJSON.stringify()
Log a valueconsole.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:

  • null
  • undefined
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 as 0, 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 / Set for 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

MethodMutates?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

MethodReturnsTypical Use
.forEach()undefinedSide effects
.map()ArrayTransform values
.filter()ArrayKeep matches
.find()Value / undefinedFind first match
.findIndex()NumberFind match index
.some()BooleanAny match?
.every()BooleanAll match?
.reduce()AnythingAggregate
.includes()BooleanContains value?
.indexOf()NumberLocate value
.slice()ArrayCopy section
.splice()Array of removed itemsMutate contents
.flat()ArrayFlatten
.flatMap()ArrayTransform + flatten
.join()StringJoin values

๐Ÿ“Š Equality Cheat Sheet

ExpressionResult
5 === 5true
5 === "5"false
5 == "5"true
null === undefinedfalse
null == undefinedtrue
NaN === NaNfalse
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

LoopIteratesBest For
for...ofValuesArrays, strings, sets, maps
for...inProperty keysObjects

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

StructureKeysUnique ValuesOrdered IterationTypical Use
ArrayNumeric indexesโŒโœ…Lists
ObjectString/SymbolN/AMostly predictableRecords
MapAny valueKeys uniqueโœ…Key/value dictionary
SetN/Aโœ…โœ…Unique values
WeakMapObjectsKeys uniqueโŒ enumerableObject metadata
WeakSetObjectsโœ…โŒ enumerableObject membership

๐Ÿ“Š Function Choices

SyntaxOwn this?Hoisted?Good For
function foo() {}โœ…โœ…General functions
const foo = function() {}โœ…โŒ usable-before-declarationFunction expressions
const foo = () => {}โŒ lexical thisโŒ usable-before-declarationCallbacks / concise functions
method() {}โœ… contextualN/AObject/class methods

๐Ÿง  Debugging Checklist

When something breaks:

  1. Check the console.
  2. Read the full error message.
  3. Read the stack trace.
  4. Verify variable values.
  5. Verify types with typeof.
  6. Check null / undefined.
  7. Check array indexes.
  8. Confirm asynchronous operations are awaited.
  9. Check whether a method mutates the original.
  10. Check object reference sharing.
  11. Check spelling/case sensitivity.
  12. Check import/export names.
  13. Verify API response status.
  14. Inspect actual API response data.
  15. Add a breakpoint with debugger.
  16. 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

AreaExampleRemember
Variablesconst, letPrefer const
Typesstring, number, objectArrays are objects
Equality===, !==Avoid loose equality
Truthinessif (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
CollectionsMap, SetSpecialized collections
Asyncasync/awaitPromise-friendly syntax
Parallel asyncPromise.all()Run independent work together
HTTPfetch()Check response.ok
Modulesimport/exportStandard module system
Errorstry/catchHandle expected failure
Classesclass Foo {}Prototype-based underneath
DOMquerySelector()Find elements
EventsaddEventListener()React to browser events
StoragelocalStorageStores strings
JSONJSON.parse()JSON โ†’ JavaScript
Debuggingconsole.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

  1. Prefer const; use let when reassignment is required.
  2. Avoid var in modern code unless you specifically need its legacy semantics.
  3. Prefer === and !==.
  4. Use .map() to transform.
  5. Use .filter() to select.
  6. Use .find() when you need one matching value.
  7. Use .reduce() when combining values actually makes the code clearer.
  8. Prefer for...of when you need normal loop control.
  9. Remember that objects and arrays are reference values.
  10. Spread syntax creates shallow, not deep, copies.
  11. Use structuredClone() when an appropriate deep clone is needed.
  12. Use ?. for safe nested access.
  13. Use ?? instead of || when 0, false, and "" are valid.
  14. Use async/await for readable asynchronous code.
  15. Use Promise.all() for independent async operations that can run concurrently.
  16. Always check response.ok when using fetch().
  17. Handle failures with try/catch where recovery or reporting matters.
  18. Don't insert untrusted strings with innerHTML.
  19. Don't put secrets in client-side JavaScript.
  20. 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:

  1. What type is this value?
  2. Is this object being mutated or copied?
  3. Is this code synchronous or asynchronous?

Those three questions explain a surprisingly large percentage of JavaScript bugs.


๐Ÿ”— See Also

Backlinks (3)
Categories (0)

    No categories assigned to this page.

Edit Level

> Signed In Users