📖 Guide

JavaScript — Complete Reference

Comprehensive JavaScript cheat sheet covering variables, types, operators, strings, arrays, objects, functions, async, DOM, ES6+, and more.

226 commands across 12 categories

Variables & Types

CommandDescription
let x = 10;
Declare a block-scoped variable
const PI = 3.14;
Declare a block-scoped constant
var name = "old";
Declare a function-scoped variable (legacy)
typeof x
e.g. typeof 42 // "number"
Returns the type of a value as a string
instanceof
e.g. [] instanceof Array // true
Check if object is instance of a class
undefined
Variable declared but not assigned a value
null
Intentional absence of any value
NaN
e.g. Number("abc") // NaN
Not a Number — result of invalid math
Number.isNaN(value)
e.g. Number.isNaN(NaN) // true
Check if value is NaN (safer than global isNaN)
Number.isFinite(value)
Check if value is a finite number
Number.isInteger(value)
e.g. Number.isInteger(4.0) // true
Check if value is an integer
Number.parseFloat("3.14")
Parse a string into a floating-point number
Number.parseInt("10", 10)
Parse a string into an integer with given radix
Boolean(value)
Convert to boolean — falsy: 0, '', null, undefined, NaN, false
BigInt(9007199254740991)
e.g. const big = 9007199254740991n;
Create a BigInt for arbitrarily large integers
Symbol("desc")
e.g. const id = Symbol("id");
Create a unique identifier

Operators

CommandDescription
===
e.g. 1 === "1" // false
Strict equality (no type coercion)
==
e.g. 1 == "1" // true
Loose equality (with type coercion)
!==
Strict inequality
? :
e.g. const r = age >= 18 ? "adult" : "minor";
Ternary operator
??
e.g. null ?? "default" // "default"
Nullish coalescing — returns right side if left is null/undefined
?.
e.g. user?.address?.city
Optional chaining — short-circuits if null/undefined
??=
e.g. x ??= 10; // assigns 10 only if x is null/undefined
Nullish coalescing assignment
||=
e.g. x ||= "fallback"; // assigns if x is falsy
Logical OR assignment
&&=
e.g. x &&= newValue; // assigns if x is truthy
Logical AND assignment
...
e.g. const arr2 = [...arr1, 4, 5];
Spread / rest operator
**
e.g. 2 ** 10 // 1024
Exponentiation operator
&, |, ^, ~, <<, >>
Bitwise operators: AND, OR, XOR, NOT, left/right shift
in
e.g. "name" in obj // true
Check if property exists in object
delete obj.prop
Delete a property from an object
void 0
Evaluates expression and returns undefined

Strings

CommandDescription
`template ${expr}`
Template literal with interpolation
str.length
Get the length of a string
str.includes("sub")
Check if string contains a substring
str.startsWith("he")
Check if string starts with a substring
str.endsWith("lo")
Check if string ends with a substring
str.indexOf("sub")
Find first index of substring (-1 if not found)
str.lastIndexOf("sub")
Find last index of substring
str.slice(start, end)
e.g. "hello".slice(1, 3) // "el"
Extract a portion of a string (supports negative indices)
str.substring(start, end)
Extract characters between two indices
str.toUpperCase()
Convert string to uppercase
str.toLowerCase()
Convert string to lowercase
str.trim()
Remove whitespace from both ends
str.trimStart()
Remove whitespace from the start
str.trimEnd()
Remove whitespace from the end
str.padStart(length, char)
e.g. "5".padStart(3, "0") // "005"
Pad from the start to a given length
str.padEnd(length, char)
Pad from the end to a given length
str.repeat(n)
e.g. "ha".repeat(3) // "hahaha"
Repeat the string n times
str.replace("old", "new")
Replace first occurrence
str.replaceAll("old", "new")
Replace all occurrences
str.split(separator)
e.g. "a,b,c".split(",") // ["a","b","c"]
Split string into an array
str.match(/regex/)
Match against a regular expression
str.matchAll(/regex/g)
Returns iterator of all regex matches
str.search(/regex/)
Search for regex and return index
str.at(index)
e.g. "hello".at(-1) // "o"
Get character at index (supports negative)
String.raw`\n`
e.g. String.raw`\n` // "\n"
Raw template string — no escape processing

Arrays

CommandDescription
Array.isArray(value)
Check if a value is an array
Array.from(iterable)
e.g. Array.from("abc") // ["a","b","c"]
Create array from iterable/array-like
Array.of(1, 2, 3)
Create array from arguments
arr.push(item)
Add element(s) to end, returns new length
arr.pop()
Remove and return last element
arr.unshift(item)
Add element(s) to beginning
arr.shift()
Remove and return first element
arr.splice(i, count, ...items)
e.g. arr.splice(1, 2, "a", "b")
Remove/insert elements at position
arr.slice(start, end)
Return shallow copy of a portion
arr.concat(arr2)
Merge arrays, returns new array
arr.flat(depth)
e.g. [1,[2,[3]]].flat(Infinity) // [1,2,3]
Flatten nested arrays
arr.flatMap(fn)
Map then flatten one level
arr.map(fn)
e.g. [1,2,3].map(x => x * 2)
Transform each element, returns new array
arr.filter(fn)
e.g. [1,2,3].filter(x => x > 1)
Keep elements that pass the test
arr.reduce(fn, init)
e.g. [1,2,3].reduce((sum, x) => sum + x, 0)
Reduce array to single value
arr.forEach(fn)
Execute a function for each element (no return)
arr.find(fn)
Return first element matching condition
arr.findIndex(fn)
Return index of first matching element
arr.findLast(fn)
Return last element matching condition
arr.findLastIndex(fn)
Return index of last matching element
arr.some(fn)
True if at least one element passes test
arr.every(fn)
True if all elements pass test
arr.includes(value)
Check if array contains a value
arr.indexOf(value)
Find index of value (-1 if not found)
arr.sort((a, b) => a - b)
Sort array in place (numeric ascending)
arr.reverse()
Reverse array in place
arr.toSorted(fn)
Return new sorted array (non-mutating, ES2023)
arr.toReversed()
Return new reversed array (non-mutating, ES2023)
arr.with(index, value)
e.g. [1,2,3].with(1, 20) // [1,20,3]
Return new array with element replaced (ES2023)
arr.at(index)
e.g. [1,2,3].at(-1) // 3
Get element at index (supports negative)
arr.join(separator)
e.g. [1,2,3].join("-") // "1-2-3"
Join all elements into a string
[...new Set(arr)]
Remove duplicates from array
structuredClone(arr)
Deep clone an array (or any object)

Objects

CommandDescription
{ key: value }
Object literal
{ [expr]: value }
e.g. const key = "name"; const obj = { [key]: "Dan" };
Computed property name
{ method() {} }
Shorthand method definition
{ key }
e.g. const name = "Dan"; const obj = { name };
Shorthand property (variable name = key)
Object.keys(obj)
Get array of own enumerable keys
Object.values(obj)
Get array of own enumerable values
Object.entries(obj)
Get array of [key, value] pairs
Object.fromEntries(entries)
e.g. Object.fromEntries([["a",1],["b",2]])
Create object from [key, value] pairs
Object.assign(target, ...sources)
Copy properties from sources to target (shallow)
{ ...obj }
Spread operator — shallow clone an object
structuredClone(obj)
Deep clone an object
Object.freeze(obj)
Make object immutable (shallow)
Object.isFrozen(obj)
Check if object is frozen
Object.seal(obj)
Prevent adding/removing properties (values still editable)
Object.hasOwn(obj, prop)
e.g. Object.hasOwn({a:1}, "a") // true
Check if object has own property (ES2022)
obj.hasOwnProperty("key")
Check if object has own property (legacy)
Object.getPrototypeOf(obj)
Get the prototype of an object
Object.create(proto)
Create object with specified prototype
Object.defineProperty(obj, prop, desc)
Define or modify a property with descriptor
const { a, b } = obj
Destructure properties from an object
const { a: x, b: y = 0 } = obj
Destructure with rename and default value
Object.getOwnPropertyNames(obj)
Get all own property names (including non-enumerable)

Functions

CommandDescription
function name(params) { }
Function declaration (hoisted)
const fn = function(params) { }
Function expression (not hoisted)
const fn = (params) => { }
Arrow function
const fn = (x) => x * 2
Arrow function with implicit return
function fn(a = 10) { }
Default parameter value
function fn(...args) { }
Rest parameters — collect remaining args into array
fn(...arr)
Spread arguments from array
function fn({ name, age }) { }
Destructured parameters
(function() { })()
IIFE — Immediately Invoked Function Expression
fn.call(thisArg, a, b)
Call function with specific this and arguments
fn.apply(thisArg, [a, b])
Call function with specific this and array of arguments
const bound = fn.bind(thisArg)
Create new function with bound this
function* gen() { yield 1; }
e.g. const g = gen(); g.next() // { value: 1, done: false }
Generator function
arguments
Array-like object of all arguments (not in arrow functions)
fn.name
Get the name of a function
fn.length
Get number of expected parameters

Control Flow

CommandDescription
if (cond) { } else if (cond) { } else { }
Conditional branching
switch (val) { case x: break; default: }
Switch statement
for (let i = 0; i < n; i++) { }
Classic for loop
for (const item of iterable) { }
For...of loop (arrays, strings, maps, sets)
for (const key in obj) { }
For...in loop (object keys, includes inherited)
while (cond) { }
While loop
do { } while (cond)
Do...while loop (runs at least once)
break
Exit current loop
continue
Skip to next iteration
label: for (...) { break label; }
Labeled statement — break/continue outer loops
for await (const x of asyncIterable) { }
Async iteration over async iterables

Promises & Async

CommandDescription
new Promise((resolve, reject) => { })
Create a new Promise
promise.then(onFulfilled, onRejected)
Handle promise resolution/rejection
promise.catch(onRejected)
Handle promise rejection
promise.finally(onFinally)
Run code after promise settles (fulfilled or rejected)
Promise.resolve(value)
Create a resolved promise
Promise.reject(reason)
Create a rejected promise
Promise.all(promises)
e.g. const [a, b] = await Promise.all([p1, p2])
Wait for all promises — rejects if any reject
Promise.allSettled(promises)
Wait for all to settle, returns status + value/reason
Promise.race(promises)
Resolve/reject with first settled promise
Promise.any(promises)
Resolve with first fulfilled — rejects only if all reject
async function fn() { }
Declare an async function (returns a Promise)
const result = await promise
Wait for a promise to resolve
await Promise.all([...])
Run promises concurrently and wait for all
setTimeout(fn, ms)
Run function after delay (returns timer ID)
setInterval(fn, ms)
Run function repeatedly at interval
clearTimeout(id)
Cancel a timeout
clearInterval(id)
Cancel an interval
queueMicrotask(fn)
Schedule a microtask (runs before next macrotask)

DOM

CommandDescription
document.getElementById("id")
Select element by ID
document.querySelector("css")
Select first matching element
document.querySelectorAll("css")
Select all matching elements (NodeList)
el.classList.add("cls")
Add a CSS class
el.classList.remove("cls")
Remove a CSS class
el.classList.toggle("cls")
Toggle a CSS class
el.classList.contains("cls")
Check if element has a class
el.setAttribute("attr", "val")
Set an attribute
el.getAttribute("attr")
Get an attribute value
el.removeAttribute("attr")
Remove an attribute
el.textContent = "text"
Set text content (no HTML parsing)
el.innerHTML = "<b>html</b>"
Set inner HTML (parses HTML)
el.style.color = "red"
Set inline style
el.addEventListener("click", fn)
Attach event listener
el.removeEventListener("click", fn)
Remove event listener
document.createElement("div")
Create a new element
parent.appendChild(child)
Append child to parent
parent.removeChild(child)
Remove child from parent
el.remove()
Remove element from the DOM
el.insertAdjacentHTML("beforeend", html)
Insert HTML at specified position
el.closest("selector")
Find closest ancestor matching selector
el.matches("selector")
Check if element matches CSS selector
el.getBoundingClientRect()
Get element position and dimensions
el.dataset.name
e.g. <div data-name="x"> → el.dataset.name // "x"
Access data-* attributes
el.cloneNode(true)
Clone element (true = deep clone with children)

ES6+ Features

CommandDescription
const [a, b, ...rest] = arr
Array destructuring with rest
const { a, b, ...rest } = obj
Object destructuring with rest
const [a = 1, b = 2] = arr
Destructuring with defaults
new Map()
e.g. const m = new Map(); m.set("k", "v"); m.get("k")
Create a Map (key-value, any key type)
new Set()
e.g. const s = new Set([1,2,2,3]); // Set {1,2,3}
Create a Set (unique values)
new WeakMap()
Map with weakly held object keys (GC-friendly)
new WeakSet()
Set with weakly held objects
for (const [k, v] of map) { }
Iterate over Map entries
class Foo { constructor() {} }
Class declaration
class Bar extends Foo { }
Class inheritance
static method() { }
Static method (called on class, not instance)
get prop() { } / set prop(v) { }
Getter and setter in class
#privateField
e.g. class Foo { #count = 0; }
Private class field (ES2022)
static #privateStatic
Private static field
globalThis
Universal global object (works in browser, Node, workers)
structuredClone(obj)
Deep clone any serializable value
Object.groupBy(arr, fn)
e.g. Object.groupBy([1,2,3], n => n > 1 ? "big" : "small")
Group array elements by key function (ES2024)
using resource = getResource()
Explicit resource management (ES2024 proposal)
arr.toSorted() / arr.toReversed()
Non-mutating sort/reverse (ES2023)
arr.toSpliced(i, n, ...items)
Non-mutating splice (ES2023)

Error Handling

CommandDescription
try { } catch (e) { } finally { }
Try-catch-finally block
throw new Error("message")
Throw an error
throw new TypeError("msg")
Throw a TypeError
throw new RangeError("msg")
Throw a RangeError
throw new ReferenceError("msg")
Throw a ReferenceError
throw new SyntaxError("msg")
Throw a SyntaxError
class MyError extends Error { }
Custom error class
error.message
Get the error message
error.name
Get the error type name
error.stack
Get the stack trace string
error.cause
e.g. throw new Error("fail", { cause: originalError })
Get the cause of the error (ES2022)
try { } catch { }
Optional catch binding (omit error param)

Modules

CommandDescription
export const x = 1;
Named export
export function fn() { }
Named function export
export default value
Default export
export { a, b }
Export multiple values
export { a as alias }
Export with alias
import { a, b } from "./mod"
Named import
import def from "./mod"
Default import
import * as mod from "./mod"
Namespace import
import { a as alias } from "./mod"
Import with alias
const mod = await import("./mod")
e.g. const { fn } = await import("./utils.js")
Dynamic import (code splitting)
export * from "./mod"
Re-export everything from another module
export { default } from "./mod"
Re-export default from another module
import.meta.url
URL of the current module

More Guides

🌿
Git Commands
Complete Git command reference — from basics to advanced workflows. Searchable, with examples.
📝
Vim Commands
Complete Vim/Vi command reference — modes, motions, editing, search, and advanced features.
🐳
Docker Commands
Complete Docker & Docker Compose command reference — containers, images, volumes, networks, and orchestration.
🔤
Regex Reference
Complete regular expression reference — syntax, patterns, quantifiers, groups, lookaheads, and common recipes.
🐧
Linux Commands
Complete Linux/Bash command reference — file management, text processing, networking, system admin, and shell scripting.
☸️
Kubernetes Commands
Complete Kubernetes & kubectl command reference — pods, deployments, services, configmaps, and cluster management.
🐍
Python Reference
Complete Python reference — syntax, data structures, string methods, file I/O, comprehensions, and common patterns.
🗃️
SQL Reference
Complete SQL reference — queries, joins, aggregation, subqueries, indexes, and database management.
🌐
Nginx Reference
Complete Nginx configuration reference — server blocks, locations, proxying, SSL, load balancing, and caching.
🔐
SSH Commands
Complete SSH reference — connections, key management, tunneling, config, SCP/SFTP, and security hardening.
👷
Jenkins Reference
Complete Jenkins reference — pipeline syntax, Jenkinsfile, plugins, CLI, agents, and CI/CD patterns.
📨
HTTP Headers Reference
Complete HTTP headers reference — request headers, response headers, caching, security, CORS, and content negotiation. Searchable, with examples.
🐘
PostgreSQL Reference
Comprehensive PostgreSQL reference — from connection basics to advanced features like JSONB, full-text search, window functions, and performance tuning.
Async Patterns Reference
Multi-language async/concurrency patterns — JavaScript, Python, Go, Rust, Java, and universal concurrency patterns.
📡
Protobuf & gRPC Reference
Comprehensive reference for Protocol Buffers (proto3) and gRPC — message definitions, services, streaming, and common patterns.
📚
JS Array Methods
Complete JavaScript Array methods reference — creating, searching, transforming, sorting, iterating, and common patterns. Searchable, with examples.
🌊
Tailwind CSS Reference
Complete Tailwind CSS reference — layout, spacing, typography, colors, responsive design, states, and common patterns. Searchable, with examples.
GraphQL Reference
Complete GraphQL reference — schema definition, types, queries, mutations, directives, fragments, and common patterns. Searchable, with examples.
💻
VS Code Shortcuts
Complete VS Code keyboard shortcuts — editing, navigation, search, multi-cursor, terminal, debug, and more. Searchable, with Cmd/Ctrl notation.
🔲
CSS Grid Reference
Complete CSS Grid reference — container properties, item placement, grid functions, and common layout patterns. Searchable, with examples.
📦
CSS Flexbox Reference
Complete CSS Flexbox reference — container properties, item properties, and common layout patterns. Searchable, with examples.
⚛️
React Hooks Reference
Complete React Hooks reference — useState, useEffect, useContext, custom hooks, and common patterns. Searchable, with examples.
🔷
TypeScript Reference
Complete TypeScript reference — types, interfaces, generics, utility types, and advanced patterns. Searchable, with examples.
☁️
AWS CLI Reference
Complete AWS CLI reference — EC2, S3, IAM, Lambda, ECS, RDS, CloudFormation, and common operations.
🐹
Go Reference
Complete Go (Golang) reference — syntax, types, functions, concurrency, error handling, and common patterns.
💠
PowerShell Reference
Complete PowerShell reference — cmdlets, pipelines, scripting, file operations, remote management, and Active Directory.
💾
Redis Commands
Complete Redis command reference — strings, hashes, lists, sets, sorted sets, pub/sub, transactions, and server management.
🏗️
Terraform Commands
Complete Terraform reference — init, plan, apply, state management, modules, workspaces, and HCL syntax.
⚙️
Ansible Commands
Complete Ansible reference — playbooks, modules, inventory, roles, vault, and ad-hoc commands.

📖 Free, searchable command reference. Bookmark this page for quick access.