JavaScript Cheat Sheet
A searchable reference of everyday JavaScript syntax and what each piece does.
| Snippet | What it does |
|---|---|
let count = 0 | Declare a block-scoped variable you can reassign later. |
const PI = 3.14159 | Declare a block-scoped constant whose binding cannot be reassigned. |
var legacy = 1 | Declare a function-scoped, hoisted variable (legacy; prefer let or const). |
typeof value | Return a string naming the value type, such as "number" or "object". |
`Hi ${name}, you have ${n} new` | Build a string with embedded expressions using a backtick template literal. |
const label = ok ? "yes" : "no" | Pick one of two values based on a condition in a single expression (ternary). |
user?.address?.city | Read a nested property and return undefined instead of throwing if a link is missing. |
const port = input ?? 8080 | Use the right side only when the left is null or undefined (nullish coalescing). |
const all = [...a, ...b] | Expand array elements into a new array with the spread operator. |
const [first, second] = arr | Pull array items into named variables by position (destructuring). |
const { name, age } = user | Pull object properties into variables of the same name (destructuring). |
function add(a, b) { return a + b } | Declare a named function that is hoisted to the top of its scope. |
const add = (a, b) => a + b | Define a compact arrow function; a single expression is returned implicitly. |
function greet(name = "friend") {} | Give a parameter a fallback used when the argument is undefined. |
function sum(...nums) {} | Collect any number of trailing arguments into an array (rest parameters). |
function make() { let n = 0; return () => ++n } | Return an inner function that keeps access to the outer variables (closure). |
(function () {})() | Define and immediately call a function to create a private scope (IIFE). |
const f = () => this.value | Arrow functions take this from where they are defined, not how they are called. |
const bound = fn.bind(obj) | Create a new function whose this is permanently set to obj. |
fn.call(obj, a, b) | Call a function with a given this and arguments listed one by one. |
fn.apply(obj, [a, b]) | Call a function with a given this and arguments passed as an array. |
const user = { name: "Ada", age: 36 } | Create an object with key and value pairs (object literal). |
Object.keys(obj) | Return an array of the object own enumerable property names. |
Object.entries(obj) | Return an array of [key, value] pairs for the object own properties. |
Object.values(obj) | Return an array of the object own enumerable property values. |
Object.assign(target, source) | Copy enumerable properties from source objects onto a target object. |
const copy = { ...user } | Make a shallow copy of an object with the spread operator. |
const o = { [key]: value } | Use an expression in brackets as a dynamic, computed property name. |
const o = { get full() { return this.name } } | Define a getter that runs a function when the property is read. |
JSON.stringify(obj) | Convert a JavaScript value into a JSON string. |
JSON.parse(text) | Parse a JSON string back into a JavaScript value. |
const p = new Promise((resolve, reject) => {}) | Create a promise that you settle by calling resolve or reject. |
p.then(onValue).catch(onError) | Handle a fulfilled value or a rejection with callbacks. |
async function load() {} | Declare a function that always returns a promise. |
const data = await load() | Pause inside an async function until the promise settles, then resume. |
const [a, b] = await Promise.all([p1, p2]) | Wait for all promises and fail fast if any of them rejects. |
const first = await Promise.race([p1, p2]) | Settle as soon as the first of several promises settles. |
const res = await fetch(url) | Request a resource over the network and get a Response object. |
try { await load() } catch (e) {} | Catch a rejected await the same way you catch a thrown error. |
setTimeout(() => doThing(), 1000) | Run a function once after a delay given in milliseconds. |
document.querySelector(".btn") | Return the first element that matches a CSS selector, or null. |
document.querySelectorAll("li") | Return a static NodeList of all elements that match a selector. |
el.addEventListener("click", handler) | Run a handler whenever the given event fires on the element. |
document.createElement("div") | Create a new detached element you can configure and insert later. |
el.classList.toggle("active") | Add or remove a class, returning whether it is now present. |
el.textContent = "Hello" | Read or set the plain text inside an element (no HTML parsing). |
el.dataset.userId | Read or set a data-user-id attribute as a string via the dataset. |
list.addEventListener("click", (e) => e.target.closest("li")) | Handle events for many children with one listener on a parent (event delegation). |
"hello".includes("ell") | Check whether a string contains a substring, returning true or false. |
"hello".slice(1, 3) | Extract part of a string between a start and end index. |
"a,b,c".split(",") | Split a string into an array on a separator. |
"2024-01".replace("-", "/") | Replace the first match of a substring or regular expression. |
"5".padStart(3, "0") | Pad the start of a string up to a target length. |
parseInt("42px", 10) | Parse an integer from the front of a string in a given base. |
parseFloat("3.14rem") | Parse a floating-point number from the front of a string. |
(3.14159).toFixed(2) | Format a number to a fixed count of decimals, returning a string. |
Number("42") | Convert a value to a number, or NaN when it cannot be converted. |
Math.round(4.6) | Round a number to the nearest integer. |
Math.max(1, 2, 3) | Return the largest of the given numbers. |
Math.floor(Math.random() * n) | Get a random integer from 0 up to n minus 1. |
import { sum } from "./math.js" | Bring specific named exports into the current module. |
import config from "./config.js" | Import the default export under any name you choose. |
import * as utils from "./utils.js" | Import every named export bundled as one namespace object. |
export function sum(a, b) {} | Expose a value or function by name from a module (named export). |
export { sum, mul } | Export several already-declared names from a module at once. |
export default function App() {} | Provide the single main export of a module (default export). |
const mod = await import("./lazy.js") | Load a module on demand at runtime and get a promise for it (dynamic import). |
No snippets match your search.
Runs entirely in your browser. Nothing you type is sent anywhere; open DevTools and watch the Network tab to verify zero requests.
What this tool does
This is a searchable quick reference for the JavaScript syntax you reach for every day, from declaring variables to writing functions, working with objects, handling async code, touching the DOM, formatting strings and numbers, and wiring up modules. Each row pairs a short snippet with a plain-English note on what it does. Type in the filter box to search across both columns, or tap a category button to focus on one topic. The whole list is built into the page, so it works offline and sends nothing anywhere.
How to use it
Start typing in the Filter box. Entering await surfaces
the async patterns; entering spread shows the spread and rest examples;
entering fetch jumps to the network call. The category
buttons (Basics, Functions, Objects, Async, DOM, Strings and numbers,
Modules) narrow the table to one family and combine with the text filter, so you can
pick Objects and type keys to zero in on Object.keys. Clear
the box to see the full sheet again.
Common use cases
- Recalling the exact form of a syntax you use rarely, like optional chaining
?.or the nullish operator??. - Copying a correct snippet into your editor instead of guessing the shape of an API.
- Teaching a beginner the difference between
let,const, andvar. - Looking up how
Promise.alldiffers fromPromise.racebefore writing async code. - Reviewing modern JavaScript syntax before an interview or a new project.
Common pitfalls
- Confusing null and any falsy value. The nullish operator
??falls back only on null or undefined, while||also falls back on 0 and the empty string. Use??when 0 is a valid value. - Assuming this in an arrow function. Arrow functions inherit
thisfrom their surrounding scope, so they are wrong for object methods that need to reference the calling object. Use a regular function there. - Reassigning a const. A
constbinding cannot be reassigned, but its object contents can still change. Reach forletonly when you actually need to point the name at a new value. - Forgetting await. Calling an async function without
awaitgives you a pending promise, not its value. Await the call, or chainthen, before using the result.
Frequently asked questions
- What is the difference between let, const, and var?
- All three declare variables, but they differ in scope and reassignment. var is function-scoped and hoisted, which can lead to surprising behavior, so modern code avoids it. let is block-scoped and can be reassigned, which suits values that change like a loop counter. const is also block-scoped but cannot be reassigned after its first value, so reach for it by default and switch to let only when you truly need to reassign. Note that a const object can still have its properties changed; only the binding is fixed.
- What is optional chaining (?.)?
- Optional chaining lets you read a deeply nested property without checking each step for null or undefined. Writing user?.address?.city returns undefined the moment any link in the chain is missing, instead of throwing a TypeError. You can also use it with method calls, as in obj.method?.(), which calls the method only when it exists. It pairs well with the nullish coalescing operator ?? to supply a fallback value.
- What does async/await do?
- An async function always returns a promise, and inside it the await keyword pauses execution until a promise settles, then resumes with its resolved value. This lets you write asynchronous code that reads top to bottom like ordinary synchronous code, instead of chaining many then callbacks. Errors from a rejected promise can be caught with a normal try and catch block around the await. Nothing blocks the main thread; other work continues while the function is suspended.
- How does this differ in an arrow function versus a regular function?
- A regular function decides this based on how it is called, so the same function can see a different this depending on the caller, which is a common source of bugs. An arrow function has no this of its own; it inherits this from the surrounding scope where it was defined. That makes arrow functions ideal for callbacks inside methods, where you want to keep the outer this. For object methods that rely on the calling object, a regular function or method shorthand is usually the better choice.
- What is destructuring?
- Destructuring is a shorthand for pulling values out of arrays or objects into separate variables. With an array you assign by position, as in const [first, second] = list. With an object you assign by property name, and you can rename or set defaults at the same time. It is common in function parameters and when importing named exports, and it keeps code shorter than a series of manual assignments.
- Does this cheat sheet send my searches anywhere?
- No. The entire syntax list is baked into the page and every search and filter runs locally in your browser with JavaScript, so nothing you type leaves your device. There is no server call, no analytics, and no tracking. Open your browser DevTools and watch the Network tab while you search to confirm there are zero requests.
Cite this tool
For academic, journalistic, or technical references. Pick a format:
Citations use 2026 as the publication year. Access date is left as a fillable placeholder where the citation style expects one.