Request a tool
DEVELOPER TOOLS · FREE ONLINE TOOL

JavaScript Cheat Sheet

Arrays, DOM, fetch, async, and ES6 patterns with copy-ready snippetsFree JavaScript cheat sheet: 60+ copy-ready snippets for arrays, DOM, events, fetch, async/await, and modern ES6. Searchable and printable.

✓ Free to use✓ No sign-up✓ Ready in your browser
// JAVASCRIPT CHEAT SHEET · GET STARTED

Use JavaScript Cheat Sheet

Arrays, DOM, fetch, async, and ES6 patterns with copy-ready snippets

62 of 62 entries shown. Click Copy on any snippet.

Variables and Types

let and const · const for values that never change, let for the rest
const name = 'Ada';
let score = 0;
typeof · Returns the type name as a string
typeof 42; // 'number'
typeof 'hi'; // 'string'
Template literals · Backtick strings with ${} interpolation
const msg = `Hello, ${name}!`;
Nullish coalescing · Falls back only for null or undefined
const v = input ?? 'default';
Optional chaining · Stops safely instead of throwing
const city = user?.address?.city;
Destructuring · Unpack objects and arrays
const { name, age } = user;
const [a, b] = pair;

Arrays

map · New array, one output per input
const doubled = nums.map(n => n * 2);
filter · Keep only items that pass the test
const evens = nums.filter(n => n % 2 === 0);
reduce · Boil an array down to one value
const sum = nums.reduce((t, n) => t + n, 0);
find · First match, or undefined
const hit = users.find(u => u.id === 3);
some / every · Any match / all match
nums.some(n => n > 10);
nums.every(n => n > 0);
includes · Membership test
['a','b'].includes('b'); // true
sort numbers · Numeric sort needs a comparator
nums.sort((a, b) => a - b);
Spread copy · Shallow copy of an array
const copy = [...arr];
flat · Flatten one level of nesting
[[1],[2,3]].flat(); // [1,2,3]

Objects

Property access · Dot notation, or brackets for odd keys
user.name;
user['first-name'];
Spread merge · Later objects win on key conflicts
const merged = { ...a, ...b };
Object.keys / values · Arrays of keys or values
Object.keys(user);
Object.values(user);
Object.entries · Loop key-value pairs
for (const [k, v] of Object.entries(user)) {}
JSON round trip · Serialize and parse JSON
const s = JSON.stringify(obj);
const back = JSON.parse(s);
Optional method call · Call only if the method exists
user.save?.();

Functions

Arrow function · Concise function expression
const add = (a, b) => a + b;
Default params · Fallback when argument is missing
function greet(name = 'friend') {}
Rest params · Collect extra args into an array
function sum(...nums) {}
setTimeout · Run once after 1 second
setTimeout(() => {}, 1000);
setInterval · Repeat every 500ms; clearInterval(id) stops it
const id = setInterval(tick, 500);
Debounce · Wait until calls stop for 300ms (see note)
const d = debounce(fn, 300);

DOM Selection

querySelector · First match for a CSS selector
document.querySelector('.card');
querySelectorAll · All matches as a NodeList
document.querySelectorAll('li');
getElementById · Fast lookup by id
document.getElementById('app');
Closest ancestor · Nearest ancestor matching a selector
el.closest('.card');

DOM Manipulation

Text content · Safe plain-text update (no HTML parsing)
el.textContent = 'Hi';
Inner HTML · Parse a string as HTML (avoid with user input)
el.innerHTML = '<b>Hi</b>';
Create element · Build a node in memory
const li = document.createElement('li');
Append · Add as last or first child
list.append(li);
list.prepend(li);
Class list · Add, remove, or toggle classes
el.classList.add('on');
el.classList.toggle('on');
Dataset · Read data-* attributes
el.dataset.userId; // data-user-id
Remove · Detach a node from the DOM
el.remove();

Events

Click listener · React to clicks
btn.addEventListener('click', e => {});
Input listener · Fires on every keystroke
input.addEventListener('input', e => {});
Prevent default · Stop the page reloading on submit
form.addEventListener('submit', e => e.preventDefault());
Event delegation · One listener for many children
list.addEventListener('click', e => {
  if (e.target.matches('li')) {}
});
Once · Listener removes itself after firing
btn.addEventListener('click', fn, { once: true });

Fetch and Async

GET JSON · Fetch and parse in two awaits
const res = await fetch('/api/data');
const data = await res.json();
POST JSON · Send a JSON body
await fetch('/api/save', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(payload),
});
Check status · Fetch only rejects on network failure
if (!res.ok) throw new Error(res.status);
Promise.all · Run promises in parallel
const [a, b] = await Promise.all([fa(), fb()]);
Try/catch · Handle async errors
try { await load(); } catch (e) { console.error(e); }
Async function · Always returns a promise
async function load() {
  return await fetch(url);
}

Strings and Numbers

Split and join · String to array and back
'a,b'.split(',');
['a','b'].join('-');
Includes / startsWith · Substring tests
s.includes('x');
s.startsWith('http');
Trim · Remove whitespace from both ends
s.trim();
Replace all · Replace every occurrence
s.replaceAll('a', 'b');
Pad start · Left-pad a string
String(5).padStart(3, '0'); // '005'
toFixed · Round to 2 decimals as a string
(3.14159).toFixed(2); // '3.14'
Parse numbers · Extract numbers from strings
parseInt('42px', 10);
parseFloat('3.5');
Math helpers · Max, floor, and 0-1 random
Math.max(1, 9);
Math.floor(4.9);
Math.random();

ES6 and Beyond

Modules · Import and export between files
import { x } from './lib.js';
export const y = 2;
Classes · Constructor plus inheritance
class Dog extends Animal {
  constructor() { super(); }
}
for...of · Loop values (arrays, strings, Maps)
for (const item of list) {}
Map and Set · Keyed collection and unique-value collection
const m = new Map();
const s = new Set([1,2,2]);
Promise · Manual promise construction
new Promise((resolve, reject) => {});
// JAVASCRIPT CHEAT SHEET · HOW IT WORKS

How to use the JavaScript Cheat Sheet

01

Search

Type in the search box to filter snippets.

02

Copy

Click Copy on any snippet to grab the code.

03

Print

Print the page for a desk reference.

// JAVASCRIPT CHEAT SHEET · ABOUT THIS TOOL

About the JavaScript Cheat Sheet

The JavaScript you reach for every day: variables and types, array and object methods, functions, DOM selection and manipulation, events, fetch with async/await, string and number helpers, and modern ES6 syntax. Each entry is a working snippet with a plain-English note.

Search to jump to what you need, copy with one click, and print for an offline reference while you code.

// JAVASCRIPT CHEAT SHEET · COMMON QUESTIONS

JavaScript Cheat Sheet FAQs

map returns a new array with one output per input item, so use it when you want transformed data. forEach returns nothing and is for side effects like logging or DOM updates.