JavaScript Cheatsheet
Comprehensive JavaScript reference covering variables, types, strings, arrays, objects, functions, promises, async/await, and modern ES6+ syntax.
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.
| Declaration | Behaviour |
|---|---|
| const x = value | Block-scoped, cannot be reassigned. Always use by default. |
| let x = value | Block-scoped, can be reassigned. Use for counters or reassignable variables. |
| var x = value | Function-scoped, can be reassigned. Avoid in modern JS (hoisting quirks). |
| Type | Example | Notes |
|---|---|---|
| string | "hello" | Single, double, or backtick quotes. Immutable. |
| number | 42, 3.14 | All numbers are IEEE-754 floating point (no integer type). |
| boolean | true, false | Falsy values: 0, "", null, undefined, NaN, false. |
| null | null | Intentional absence of value (typeof returns "object", a known bug). |
| undefined | undefined | Default value of uninitialised variables and missing object properties. |
| object | {} | Key-value collections, arrays, functions. Passed by reference. |
| symbol | Symbol("id") | Unique, immutable values, often used as object keys. |
| bigint | 9007199254740991n | Arbitrary-precision integers (ES2020). |
Strings
| Expression | Result / Behaviour |
|---|---|
| `Hello ${name}` | Template literal with interpolation. Multi-line support. |
| "text".length | Returns 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.
| Method | What 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
| Syntax | What it does |
|---|---|
| { key: value } | Object literal. Keys are strings (or symbols). |
| obj.key | Dot notation - access a known property. |
| obj["key"] | Bracket notation - access with dynamic or invalid identifier keys. |
| const { key } = obj | Destructuring: extract properties into variables. |
| const { a, b } = obj | Extract multiple properties at once. |
| const { x: alias } = obj | Destructure with a different variable name. |
| const { a, ...rest } = obj | Rest pattern: collect remaining properties. |
| { ...obj, newKey: v } | Spread: shallow copy with overrides. |
| obj?.prop?.nested | Optional chaining: returns undefined instead of throwing if intermediate is null/undefined. |
| obj.key ?? defaultValue | Nullish coalescing: uses default only if value is null or undefined. |
Classes
ES6 introduced class syntax as syntactic sugar over JavaScript's prototype-based inheritance.
| Syntax | Notes |
|---|---|
| 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 ParentClass | Inheritance: child inherits parent prototype methods. |
| super() | Call parent constructor. Required in child constructor before using this. |
| #privateField | Private class field (ES2022). Only accessible within the class. |
Functions
| Syntax | Notes |
|---|---|
| function name(params) {} | Regular function declaration (hoisted). |
| const fn = (params) => {} | Arrow function. Lexical this (inherits from surrounding scope). |
| const fn = param => expr | Arrow 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.
| Context | this 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 function | Lexical this: inherits from the enclosing scope (where the arrow was defined). |
| new Constructor() | The newly created instance. |
| DOM event handler | The 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.
| Pattern | What 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 promise | Pause 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+)
| Feature | Example |
|---|---|
| Optional chaining | obj?.prop?.nested ?? fallback |
| Nullish coalescing | value ?? defaultValue |
| Nullish assignment | x ??= defaultValue |
| Logical assignment | x ||= default; x &&= mapper |
| Top-level await | const 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.groupBy | Object.groupBy(arr, x => x.type) (ES2024) |
| Promise.withResolvers | const { promise, resolve } = Promise.withResolvers() (ES2024) |
Map, Set & Weak Collections
ES6 introduced dedicated collection types that outperform plain objects and arrays for certain use cases.
| Collection | Use case |
|---|---|
| Map | Key-value pairs with any type as key. Remembers insertion order. O(1) get/set. |
| Set | Unique values of any type. Great for deduplication. O(1) has/add. |
| WeakMap | Like Map but keys must be objects and are garbage-collected. No iteration methods. |
| WeakSet | Like 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.
| Syntax | What it does |
|---|---|
| export const x = 1 | Named export. Multiple per file allowed. |
| export default fn | Default 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.