All cheat sheets

JavaScript Cheatsheet

Comprehensive JavaScript reference covering variables, types, strings, arrays, objects, functions, promises, async/await, and modern ES6+ syntax.

Cheat Sheet

JavaScript (JS) is the language of the web. It runs in every browser, on servers via Node.js, and increasingly on desktop and mobile. The language evolves through ECMAScript (ES) specifications - ES6 (ES2015) introduced the most significant update, and modern JS (ES2020+) continues to add features like optional chaining, nullish coalescing, and top-level await.

Note: All examples use modern ES6+ syntax. Older browsers may need transpilation (Babel) or polyfills.

Variables & Data Types

JavaScript is dynamically typed. Three ways to declare variables, with different scoping rules.

DeclarationBehaviour
const x = valueBlock-scoped, cannot be reassigned. Always use by default.
let x = valueBlock-scoped, can be reassigned. Use for counters or reassignable variables.
var x = valueFunction-scoped, can be reassigned. Avoid in modern JS (hoisting quirks).
TypeExampleNotes
string"hello"Single, double, or backtick quotes. Immutable.
number42, 3.14All numbers are IEEE-754 floating point (no integer type).
booleantrue, falseFalsy values: 0, "", null, undefined, NaN, false.
nullnullIntentional absence of value (typeof returns "object", a known bug).
undefinedundefinedDefault value of uninitialised variables and missing object properties.
object{}Key-value collections, arrays, functions. Passed by reference.
symbolSymbol("id")Unique, immutable values, often used as object keys.
bigint9007199254740991nArbitrary-precision integers (ES2020).

Strings

ExpressionResult / Behaviour
`Hello ${name}`Template literal with interpolation. Multi-line support.
"text".lengthReturns 4 (every string has a length property).
"text".includes("ex")true - checks if substring exists.
"text".startsWith("te")true - checks string start.
"text".endsWith("xt")true - checks string end.
"text".toUpperCase()"TEXT" - transforms to uppercase.
"text".trim()Removes whitespace from both ends.
"a,b,c".split(",")["a", "b", "c"] - splits into array by separator.
["a","b"].join("-")"a-b" - joins array elements into string.

Arrays

Arrays in JS are zero-indexed, dynamically sized, and can hold mixed types. The most common operations use the iteration methods below.

MethodWhat it does
arr.map(fn)Create a new array by transforming each element.
arr.filter(fn)Create a new array with elements that pass the test.
arr.reduce(fn, initial)Reduce array to a single value (sum, average, etc.).
arr.find(fn)Return the first element that passes the test.
arr.findIndex(fn)Return the index of the first matching element.
arr.some(fn)true if at least one element passes the test.
arr.every(fn)true if all elements pass the test.
arr.includes(value)true if the value exists in the array.
arr.flat(depth)Flatten nested arrays to the specified depth.
arr.flatMap(fn)Map then flatten one level (like .map().flat()).
arr.slice(start, end)Extract a shallow copy of a portion (does not mutate).
arr.splice(start, count)Remove/replace elements in place (mutates).

Objects

SyntaxWhat it does
{ key: value }Object literal. Keys are strings (or symbols).
obj.keyDot notation - access a known property.
obj["key"]Bracket notation - access with dynamic or invalid identifier keys.
const { key } = objDestructuring: extract properties into variables.
const { a, b } = objExtract multiple properties at once.
const { x: alias } = objDestructure with a different variable name.
const { a, ...rest } = objRest pattern: collect remaining properties.
{ ...obj, newKey: v }Spread: shallow copy with overrides.
obj?.prop?.nestedOptional chaining: returns undefined instead of throwing if intermediate is null/undefined.
obj.key ?? defaultValueNullish coalescing: uses default only if value is null or undefined.

Classes

ES6 introduced class syntax as syntactic sugar over JavaScript's prototype-based inheritance.

SyntaxNotes
class MyClass {}Class declaration. Not hoisted (unlike function declarations).
constructor(params) {}Called automatically when instantiated with new.
this.method = () => {}Instance method (defined in constructor).
myMethod() {}Prototype method (shared across instances).
static myMethod() {}Static method called on the class itself, not instances.
extends ParentClassInheritance: child inherits parent prototype methods.
super()Call parent constructor. Required in child constructor before using this.
#privateFieldPrivate class field (ES2022). Only accessible within the class.

Functions

SyntaxNotes
function name(params) {}Regular function declaration (hoisted).
const fn = (params) => {}Arrow function. Lexical this (inherits from surrounding scope).
const fn = param => exprArrow with single parameter and implicit return.
function f(a, b = 1) {}Default parameter values (applied when argument is undefined).
function f(...args) {}Rest parameters: gathers remaining arguments into an array.
function f(a, b, ...rest) {}Named parameters + rest combination.
() => ({ key: val })Arrow returning an object literal (wrap in parentheses).
function* gen() { yield x; }Generator function: yields multiple values over time using .next().

this Binding

The value of this depends on how a function is called, not where it is defined. A common source of bugs.

Contextthis refers to
Regular function (call)The object the method is called on (the receiver).
Regular function (standalone)Global object (window/globalThis), or undefined in strict mode.
Arrow functionLexical this: inherits from the enclosing scope (where the arrow was defined).
new Constructor()The newly created instance.
DOM event handlerThe element that fired the event.
.call() / .apply() / .bind()Explicitly set this to the first argument passed.

Promises & Async/Await

Promises represent a value that may be available now, later, or never. The async/await syntax provides a cleaner way to work with promises.

PatternWhat it does
new Promise((res, rej) => {})Create a promise. Resolve with res(), reject with rej().
promise.then(fn).catch(fn)Handle resolved value (then) and errors (catch).
promise.finally(fn)Run cleanup after resolve or reject.
async function fn() {}Declare an async function (always returns a promise).
const val = await promisePause execution until the promise resolves, then unwrap the value.
try { await fn() } catch (e) {}Handle errors from async functions with try/catch.
Promise.all([p1, p2])Wait for all promises to resolve (rejects fast on first error).
Promise.allSettled([p1, p2])Wait for all to settle (resolves with results regardless of rejections).
Promise.race([p1, p2])Resolve/reject as soon as the first promise settles.
Promise.any([p1, p2])Resolve as soon as the first promise fulfills (ignores rejections).

Modern Syntax (ES6+)

FeatureExample
Optional chainingobj?.prop?.nested ?? fallback
Nullish coalescingvalue ?? defaultValue
Nullish assignmentx ??= defaultValue
Logical assignmentx ||= default; x &&= mapper
Top-level awaitconst data = await fetch(url) (ES2022, modules)
Array.at(-1)arr.at(-1) - last element, cleaner than arr[arr.length-1]
String.replaceAll"a-a".replaceAll("-", ".") => "a.a"
Object.groupByObject.groupBy(arr, x => x.type) (ES2024)
Promise.withResolversconst { promise, resolve } = Promise.withResolvers() (ES2024)

Map, Set & Weak Collections

ES6 introduced dedicated collection types that outperform plain objects and arrays for certain use cases.

CollectionUse case
MapKey-value pairs with any type as key. Remembers insertion order. O(1) get/set.
SetUnique values of any type. Great for deduplication. O(1) has/add.
WeakMapLike Map but keys must be objects and are garbage-collected. No iteration methods.
WeakSetLike Set but values must be objects and are garbage-collected. No iteration methods.

Modules (ES Modules)

ES Modules (import/export) are the standard for sharing code between files. Supported in all modern browsers and Node.js.

SyntaxWhat it does
export const x = 1Named export. Multiple per file allowed.
export default fnDefault export. One per file. Imported without braces.
export { a, b }Named exports grouped at the end of the file.
import { x } from "./mod"Import a named export. Braces required.
import x from "./mod"Import the default export. No braces.
import * as mod from "./mod"Import all named exports into a namespace object.
import("./mod").then(m => {})Dynamic import. Returns a promise. For lazy loading.

Common Pitfalls

== vs ===

Always use === (strict equality). == performs type coercion ("2" == 2 is true), which leads to subtle bugs.

Truthy/Falsy Gotchas

0, "", null, undefined, NaN, and false are falsy. Everything else is truthy, including empty arrays [] and empty objects {}.

const is not immutable

const prevents reassignment, but object/array contents can still be mutated (obj.key = val, arr.push()). Use Object.freeze() for shallow immutability.

Closures in Loops

Using var in a loop creates a shared scope. Use let (block-scoped) or an IIFE to capture the correct iteration value.

OCMA Tools

Free developer tools. Most features run client-side, your data stays in your browser. Optional accounts unlock extra features.

Most tools run client-side

© 2026 OCMA Tools — Free developer tools

built for developers, by developers