JavaScript Cheatsheet — Quick Reference
A cheatsheet for modern JavaScript (ES2022) syntax, the standard library, and the most common DOM / Node helpers — covering about 80% of everyday scenarios.
JavaScript ES2022
ECMAScript · Multi-paradigm · Dynamic, weakly typed
Recommended Learning Path
Start with "Hello World and Runtime" (Node.js or browser console) → learn variables, types, and control flow → master array and object higher-order methods → understand references, copying, functions, and closures → focus on async (Promise / async / await) → finally consult DOM, fetch, Node modules, build, and debugging as needed. The FAQ section is great for revisiting common pitfalls.
1.Hello World and Runtime
Run JavaScript with Node.js or in the browser, and understand scripts, modules, and npm project structure.
console output
console.log writes to the console. console.error prints errors, console.table renders tabular data. Works in browsers and Node.
Run with Node
node runs a .js file directly. node -e evaluates an inline expression; node -p prints the result. Preferred when no browser is required.
Browser <script>
HTML loads JS via <script>. defer delays execution (after DOM is parsed), async loads asynchronously. type="module" enables ESM.
Command-line arguments
In Node, process.argv holds the full command line: argv[0] is node, argv[1] is the script path, argv[2]+ are arguments.
npm init
npm init creates a package.json. npm install adds dependencies and generates node_modules plus a lockfile.
package.json
package.json describes the project: name/version, main entry, scripts, and dependencies.
ES Modules
import/export modules: export exposes values, import pulls them in. Set type: "module" in package.json or use the .mjs extension.
Strict mode
'use strict' enables strict mode: implicit globals are forbidden and silent errors become exceptions. ESM is strict by default.
2.Variables and Constants
let/const declarations, scope, dynamic typing, destructuring, and template literals.
let and const
let declares a mutable binding; const declares a constant binding (the object itself is still mutable). Both are block-scoped. Prefer const; switch to let when you need to reassign.
var vs let
var is function-scoped with hoisting; let/const are block-scoped. Modern code should always use let/const to avoid var's traps.
Scope
Block scope {}, function scope, global scope. Inner scopes can read outer variables; outer scopes cannot read inner ones.
Dynamic typing
JS variables have no type constraint: the same variable can hold any value. typeof checks the runtime type.
Destructuring
Pull values from arrays or objects into variables. Object destructuring matches by name, array destructuring by position. Supports defaults and nested patterns.
Naming conventions
Variables/functions use lowerCamelCase; constants use UPPER_SNAKE_CASE; classes/components use UpperCamelCase. Booleans get is/has prefixes.
Hoisting
var declarations and function declarations are hoisted to the top of their scope. let/const have a temporal dead zone (TDZ): accessing them before declaration throws.
Template literals
Backtick strings support ${} interpolation and multi-line content. Preferred over + concatenation for string building and multi-line text.
3.Data Types
Primitives, objects, typeof checks, and type conversion.
Primitive types
There are 7 primitive types: string, number, boolean, null, undefined, symbol, and bigint. Everything else is object.
Number and NaN
number covers integers and floats. NaN means "not a number"; Infinity is positive infinity. NaN is not equal to anything, including itself.
Strings
Strings are immutable. Use length, [i] indexing, and methods like toUpperCase/slice/split. Strings are sequences of UTF-16 code units.
Truthy and falsy
Falsy values: false, 0, '', null, undefined, NaN. Everything else is truthy. if checks coerce to boolean.
null and undefined
undefined means "not defined" or "not assigned"; null is an explicit empty value. Accessing a missing property returns undefined.
Symbol and BigInt
Symbol creates unique identifiers (great for private object keys). BigInt is arbitrary-precision integers, written with a trailing n. typeof distinguishes them.
typeof checks
typeof identifies primitive types; arrays, Date, and null all return 'object', so other checks are needed to distinguish them.
Type conversion
Explicit conversion: String()/Number()/Boolean(). Implicit conversion causes many bugs: + concatenates, - coerces to number.
Object types
Everything except primitives is an object: plain objects, arrays, functions, Date, Map, etc. Objects are reference types.
4.References and Copying
Value vs reference, shallow vs deep copy, array/object references, and GC.
Value vs reference
Primitives are passed by value (copied); objects/arrays/functions are passed by reference (shared). This is the most important mental model in JS.
Object references
Function arguments: an object argument shares the same object, so mutations inside the function affect the outside. Primitives are unaffected.
Shallow copy
Spread {...obj} / [...arr] or Object.assign produces a one-level copy. Nested objects still share references.
Deep copy
Deep copy recursively clones every level. Use structuredClone (modern) or hand-write a recursive clone. Functions and circular references need special handling.
Array copy
[...arr] shallow-copies, slice() copies, Array.from converts. Nested arrays (multi-dimensional) are still shallow-copied.
JSON round-trip copy
JSON.stringify/parse is a simple deep-copy technique, but it drops undefined, functions, and Symbol, and does not support circular references.
Garbage collection
V8 automatically collects unreachable objects. Locals are released when their function exits. Globals and closed-over variables extend lifetimes.
Object equality
=== compares references for objects, not contents. Two objects with identical contents are not ===. Compare by field with a manual deep-equality routine.
5.Control Flow
if/else, loops, switch, ternary, and logical short-circuit.
if / else
if/else branches on a condition that is truthiness-coerced. Chain with else-if for multiple branches.
Ternary operator
cond ? a : b is a one-line conditional. Nested ternaries hurt readability; use if/switch for complex logic.
for loop
The classic for loop uses an index. Most collection scenarios are cleaner with for...of or array methods.
for...of
for...of iterates iterables (arrays, strings, Map/Set, NodeList). No index needed.
for...in (objects)
for...in iterates an object's enumerable keys (including inherited ones). Use for...of for arrays, or Object.keys to iterate an object's keys.
while / do-while
while checks first then runs; do-while runs at least once. Use when the number of iterations is unknown.
switch
switch uses strict equality (===). After a case matches, execution falls through to the next case until break. Watch for fall-through.
Short-circuit and optional chaining
&&, ||, and ?? short-circuit. ?. chains safely; ?? falls back only on null/undefined.
break and continue
continue skips to the next iteration; break exits the loop. Labeled break/continue controls nested loops.
6.Functions and Closures
Function declarations, arrow functions, parameters, closures, this, and callbacks.
Function declarations and expressions
Function declarations are hoisted; function expressions are not. Arrow functions are expressions and more concise. The three forms have different syntax.
Arrow functions
Arrow functions are concise, have no own this/arguments, cannot be used as constructors, and implicitly return single expressions.
Parameters and defaults
Function parameters can have defaults; rest collects the remainder. arguments is array-like and does not exist in arrow functions.
Closures
A closure lets a function remember the scope where it was created: inner functions access outer variables even after the outer function has returned.
this binding
this is determined at call time: object methods get the object, regular functions in non-strict mode get the global, arrow functions inherit the outer this.
call / apply / bind
call/apply invoke immediately with a specified this; bind returns a new function bound to this. apply takes args as an array.
Callback functions
A callback is a function passed to an async operation. Modern code prefers Promise/async. Nested callbacks become callback hell.
IIFE
An IIFE (function(){})() runs immediately and isolates its scope. Modern code uses block scope {} or modules instead.
Recursion
A function calling itself needs a base case or the stack overflows. Tail-call optimization is not fully implemented in most JS engines.
7.String Handling
String methods, template literals, regex matching, splitting, and character handling.
Common methods
Common methods: length, slice/substring for substrings, indexOf to find, includes to test, replace to substitute, split to break apart, trim to strip whitespace.
Case and encoding
toUpperCase/toLowerCase change case. charCodeAt reads a code unit; fromCharCode converts back. localeCompare compares in collation order.
Unicode handling
Strings are sequences of UTF-16 code units; supplementary-plane characters like emoji take 2 units. Iterate with for...of or Array.from.
Template literal composition
Template literal ${} interpolation and multi-line strings are the most recommended approach. Expressions and method calls can be nested inside.
Regex basics
Use regex literals /pattern/ or new RegExp. test checks a match, exec returns one. g is global, i is case-insensitive.
Regex replacement
replace with a regex supports $1 group references. A replacer callback handles complex logic. replaceAll replaces every literal occurrence.
Split and join
split breaks a string by a delimiter into an array; join merges an array back into a string. split('') splits into characters. Be careful with empty delimiters.
Number to string
toString/templates convert to string, toFixed fixes decimals, toLocaleString adds grouping separators, padStart pads with leading characters.
8.Arrays and Objects
Array higher-order methods, Map/Set, object operations, and destructuring.
Array higher-order methods
map projects, filter selects, reduce folds, find locates, some/every test. These methods do not mutate the original array.
Map
Map keys any value: get/set/has/delete/size. Keys can be objects. Iteration follows insertion order.
Set
Set is a deduplicating collection: add/has/delete/size. Preferred for array deduplication and membership tests.
Object operations
Object.keys/values/entries iterate. Object.assign merges. Object.freeze locks. The in operator tests for a property.
reduce
reduce folds an array to a single value: sum, group, flatten. The initial value is optional but recommended.
Sorting
sort uses string ordering by default (a trap). Numeric sort needs a comparator. sort mutates the array in place.
Spread and merge
The spread operator ... merges arrays/objects, copies, and spreads arguments. Rest collects and spread expands — they are mirrors.
Method chaining
map/filter return new arrays that can be chained. Watch for intermediate array allocations on long chains.
Holes and sparse arrays
Array holes differ from undefined. map skips holes. Build dense arrays with Array.from or fill.
9.Memory and Performance
Closures and memory leaks, WeakMap/WeakSet, large-data processing, and optimization.
Closure memory
Closures hold references to outer variables even when they are no longer needed. Long-lived references prevent GC.
Event listener leaks
DOM elements are removed but listeners still reference them, or listeners hold external objects, causing leaks. Detach listeners or use AbortController before removing elements.
WeakMap / WeakSet
WeakMap keys are weak: when an object has no other references, its entry is collected. Great for associations, caches, and private fields.
Performance optimization
Avoid unnecessary copies and recomputation. Cache length in a local, batch DOM operations, debounce/throttle high-frequency events.
Stack overflow
Infinite or very deep recursion causes RangeError: Maximum call stack. Switch to loops or cap the depth.
Large-data processing
Big arrays plus reduce/map allocate everything at once. Process in batches, use generators for laziness, and TypedArray for binary efficiency.
GC and globals
Global caches never release. Avoid unbounded caches; clean them up. Modern V8's mark-and-sweep handles the rest.
Memoization
Cache pure function results in a Map so identical inputs return the cached value, avoiding repeated expensive work. Watch the cache footprint.
10.Object-Oriented
class syntax, inheritance, encapsulation, static members, and the prototype chain.
class definition
class defines an object template with a constructor, methods, and properties. new creates instances.
Inheritance with extends
extends inherits; super() calls the parent constructor; super.method() calls a parent method.
getter / setter
get/set define accessor properties that run logic on read/write, including validation. They are accessed like properties, not methods.
Static members
static members belong to the class, not instances: static methods for utilities, static fields for constants. static {} is a static block for initialization.
Private fields
A # prefix defines truly private fields/methods; access outside the class throws. This is real encapsulation, not an underscore convention.
instanceof check
instanceof tests whether an object is on the class's prototype chain. Object.getPrototypeOf inspects the prototype.
Prototype chain
Objects share methods through the prototype chain. class is syntactic sugar for prototype inheritance. Mutating prototype affects every instance.
Composition over inheritance
Deep inheritance hierarchies are hard to maintain. Prefer composition: inject dependencies via the constructor or mix in features.
11.Error Handling
try/catch/finally, error types, throwing, and async error handling.
try / catch / finally
try holds risky code, catch handles exceptions, finally runs regardless. Exceptions propagate up the call stack.
Error types
Error is the base, with subclasses TypeError, ReferenceError, RangeError, SyntaxError. Distinguish with instanceof.
Throwing errors
throw new Error('msg') raises an exception. Anything can be thrown, but the convention is to throw an Error (which carries a stack).
Custom errors
extends Error defines a domain error. Set a custom name for recognition, and keep message and stack.
Async errors
Promise/async errors flow through .catch or try/catch (around await). A synchronous try/catch cannot catch an async throw.
Unhandled errors
A Promise without .catch causes unhandledrejection. Listen globally for uncaughtException/unhandledrejection at the top level.
Error isolation
A single failure in batch processing shouldn't kill the whole batch. Wrap each item in try/catch and log before continuing.
Error cause
ES2022 added the Error cause option, preserving the underlying cause and stack when wrapping errors for layered diagnosis.
12.Files and I/O
Node filesystem, console input, JSON read/write, and browser DOM I/O.
fs read file
Node's fs/promises reads files: readFile reads the whole file, readFileSync is the blocking version. Prefer the Promise version.
fs write and append
writeFile overwrites, appendFile appends, mkdir creates directories, access tests existence. rename/cp/rm do file operations.
JSON file read/write
Read JSON files with parse, write with stringify. JSON is common for configuration and data files.
Standard input/output
process.stdin reads input as a stream, readline handles line-by-line interaction, process.stdout.write writes to stdout.
fetch network I/O
fetch reads remote resources. Use async/await with res.json() / res.text() to parse the body. Built into Node 18+.
Browser DOM I/O
The DOM reads/writes page content: getElementById to locate, textContent for text, innerHTML for markup. Browser-only.
Streaming I/O
Use streams for large files to avoid loading everything into memory. createReadStream/createWriteStream, pipe, or for await.
path utilities
node:path handles file paths: join builds paths, resolve makes them absolute, extname gets the extension, basename gets the filename.
13.Common Pitfalls (FAQ)
The pitfalls JS developers hit most: == vs ===, this, async, copying, and truthiness.
== vs ===
== does implicit coercion (bug-prone), === is strict equality. Always use ===, except for the null == undefined idiom.
Lost this
this is lost when a method is assigned to a variable or passed as a callback. Use arrow functions for inheritance or bind explicitly.
Floating-point precision
0.1 + 0.2 !== 0.3 (binary representation is inexact). Compare with a tolerance; store money as integer cents or a library.
Async execution order
setTimeout and network requests are asynchronous. Writing code in source order does not guarantee execution order. Use await/Promise.
Shallow vs deep copy
Spread only copies one level; nested objects still share. Mutating nested values affects the source.
Truthy checks
Empty arrays/objects are truthy. Check array length, and use Object.keys(obj).length for empty objects.
var scope leaks
var has no block scope, so declarations in loops/if leak to function scope. Use let for loop counters.
parseInt pitfalls
parseInt('08') used to be octal on old engines; parseInt('3px') returns 3. Use Number or + for strict parsing.
Nested ternaries
Nested ternaries hurt readability. Use if/else or a lookup map for complex branches.
Mutating object props
Destructuring is a shallow copy; nested properties remain references. Deep-copy first if you need to mutate safely.
14.Async and Event Loop
Event loop, Promise, async/await, timers, and concurrency.
Event loop
JS is single-threaded with an event loop. Synchronous code runs first; async callbacks (timers/I/O) queue up to run later.
Promise
Promise represents an async result. then handles success, catch handles failure, finally wraps up. Chain to avoid callback hell.
async / await
async functions return a Promise; await suspends until the result is ready, letting you write async code like sync. try/catch around await catches errors.
Timers
setTimeout fires once after a delay, setInterval repeats; clearTimeout/clearInterval cancels. Delay is in milliseconds.
Promise combinators
Promise.all resolves when all succeed; allSettled waits for all to finish and reports each status; race resolves with the first to settle.
Web Worker
Workers run expensive code on a separate thread so the UI stays responsive, communicating via postMessage. Node uses worker_threads.
Concurrency limits
Limit concurrency for batch async tasks to avoid exhausting resources. Use batches or a semaphore.
Microtasks vs macrotasks
Microtasks (Promise.then, queueMicrotask) take priority over macrotasks (timers). Microtasks are drained within each turn.
15.Network and HTTP
fetch requests, HTTP methods, error handling, JSON, WebSocket, and URLs.
fetch basics
fetch sends HTTP requests and returns a Promise. res.ok checks success; res.json()/text() reads the body. Built into browsers and Node 18+.
POST and request bodies
The second argument to fetch configures method, headers, and body. JSON request bodies need JSON.stringify.
Query parameters
URLSearchParams builds query strings. encodeURIComponent encodes special characters. URL parses URLs.
Network error handling
fetch only rejects on network failure; HTTP 4xx/5xx don't throw — check res.ok. Use AbortController for timeouts.
WebSocket
WebSocket is a full-duplex long-lived connection with onopen/onmessage/onclose events and send() for outgoing messages. Great for realtime push.
axios vs fetch
axios offers interceptors, automatic JSON, and richer error objects. fetch is native; axios is a third-party library.
HTTP status codes
2xx success, 3xx redirect, 4xx client error, 5xx server error. Common codes: 200/201/400/401/404/500.
File upload with FormData
FormData builds a multipart form for fetch POST uploads with files and fields. XMLHttpRequest is easier for upload progress.
16.Date and Time
Date, timestamps, formatting, timezones, and timers.
Date basics
new Date() is now. getFullYear, getMonth (0-based!), getDate read parts. Month is zero-indexed.
Timestamps
Date.now() is a millisecond timestamp (UTC epoch). getTime() is the same. Store cross-zone times as a timestamp or ISO string.
Formatting output
toLocaleDateString/toLocaleString produce localized output. Intl.DateTimeFormat gives fine control.
Timezones
getTime is a UTC instant; local methods like getHours display in the runtime timezone. Store as ISO/timestamp.
Durations
Subtracting two Dates yields a millisecond delta. Convert to seconds/minutes/hours. Use performance.now for precise measurement.
Date arithmetic
Add days/months with setDate/setMonth or millisecond arithmetic. Watch for 0-based months and month boundaries.
Date parsing
new Date(string) parses a date string. ISO format is most reliable; other formats vary in compatibility.
Intl formatting
Intl.NumberFormat for numbers/currency, Intl.DateTimeFormat for dates. Localize output by region.
17.Node Process
process env vars, arguments, exit codes, cwd, and process info.
Environment variables
process.env reads environment variables in Node. process.env.NODE_ENV is common. Use .env files for cross-platform config.
Command-line arguments
process.argv holds raw arguments. Parse options with commander/yargs, or hand-write for simple cases.
Exit codes
process.exit(code) exits with a code (0 success, non-zero failure). Uncaught exceptions default to exit code 1.
Current directory and paths
process.cwd() is the current working directory; __dirname is the module directory; __filename is the module file (CJS).
Process signals
Handle SIGINT (Ctrl+C) and SIGTERM (default kill) for graceful shutdown (flush data, close connections).
Process info
process.pid is the process ID; process.uptime() is seconds running; process.memoryUsage() reports memory; process.platform is the OS.
Standard streams
process.stdin/stdout/stderr are the three standard streams for piping, redirecting, and shell collaboration.
child_process
child_process launches external commands: exec grabs output, spawn streams I/O, fork runs JS scripts. Beware shell injection.
18.Regular Expressions
Regex literals, matching, capture groups, replacement, and common patterns.
Regex syntax
Use literals /pattern/ or new RegExp. \d digit, \w word char, \s whitespace, [] character class, {} quantifier.
Regex flags
g global, i case-insensitive, m multiline (^$ match per line), s dotAll (. matches newline), u unicode.
test and match
test returns a boolean; match returns the result; matchAll iterates every match. exec returns one match and tracks lastIndex.
Capture groups
Parentheses capture; match[1] reads a group. Named groups (?<name>...) are accessed via match.groups.name. Non-capturing groups use (?:...).
Regex replacement
replace supports $1/$<name> group references and a replacer callback. replaceAll replaces every occurrence (g semantics).
Common patterns
Email, URL, IP, phone, alphanumeric. Production validation should use allowlists/strict libraries.
Regex performance
Avoid catastrophic backtracking (nested quantifiers). Precompile regexes for repeated use. Fall back to string methods when simpler.
Lookaround
Assertions match positions without consuming: lookahead (?=), negative lookahead (?!), lookbehind (?<=). Great for password and boundary checks.
19.Build and Debug
npm scripts, bundlers, debugging, testing, and code style.
npm scripts
package.json scripts define common commands. Run with npm run. Chain with && and use pre/post hooks.
Bundlers
Vite (modern recommendation), webpack, Rollup, and esbuild bundle ES modules for the browser.
Debugging
Use console levels, debugger for breakpoints, and Node --inspect for the debugger. Source maps locate original source.
Testing
Vitest/Jest unit tests: describe for groups, test/it for cases, expect for assertions. Run with npm test.
Linting with ESLint
ESLint checks syntax and style; Prettier formats uniformly. Pre-commit hooks automate the checks.
TypeScript integration
TS adds types. tsc compiles; ts-node/tsx run directly. Vite supports .ts out of the box.
CI and deployment
CI runs tests and builds automatically. Configure workflows in GitHub Actions and similar platforms. Deploy artifacts to static hosts or containers.
ESM vs CJS
Two module systems: ESM uses static import and enables tree-shaking; CJS uses runtime require. The type field controls the default.
Official Links
Direct links to the official docs and resources.
About this Cheatsheet
This page is a self-contained cheatsheet for ECMAScript 2022 (JavaScript), covering the language core and the browser/Node APIs you actually use in about 80% of real projects. The content favors modern idioms: let/const block scope, arrow functions, template literals, destructuring, spread, Promise and async/await, optional chaining, and nullish coalescing. JavaScript was created by Brendan Eich at Netscape in 1995; today it is the only language natively supported by every browser, and the foundation of web frontends, Node.js servers, and desktop apps. The 19 sections each focus on a topic: basic syntax, variables and scope, types, references and value semantics, control flow, functions and closures, strings, arrays and objects, memory and garbage collection, prototypes and classes, error handling, I/O, common pitfalls, concurrency (event loop), network (fetch), time, processes, regex, and build tools. Each subsection pairs a concept with copy-ready code. All code and text render locally in your browser — nothing leaves your device. Authoritative references: MDN Web Docs.
Version 2.1.0