Cheatsheet
← All cheat sheets

JavaScript cheat sheet

Modern JavaScript you write every day, with short examples. Click one to copy it.

Variables and basics

Value that won’t be reassigned (use by default)
Value that will change
Arrow function with a template string
Equal, without type conversion (!== for not equal)
Short if/else
"string", "number", "object", "undefined"…

Arrays

New array with each item changed
New array with the items that pass
Combine everything into one value
First match, or undefined (findIndex for its position)
Is at least one true? (every: are all?)
Is this value in the array?
Do something with each item
Add to the end (pop removes the last)
First 3 items, without changing the array
Sorted copy, numbers small to large
Sorted copy by name (newer browsers)
Array to text
Remove duplicates
Last item
[0, 1, 2, 3, 4]

Strings

Remove spaces at both ends
lowercase (toUpperCase for CAPITALS)
Contains? (startsWith, endsWith too)
Text to array
Replace every match
First 10 characters
"7" → "07"
Text to number (NaN if it isn’t one)
Number to text with 2 decimals
1234567 → "1,234,567"

Objects

Destructuring: take properties into variables
Destructure an array
Copy an object and change a property
Property names (values, entries too)
Loop over keys and values
Optional chaining: undefined instead of an error
Fallback only for null or undefined
Deep copy
Object to JSON text (JSON.parse back)

Async

Get JSON from an API
Send JSON
Handle errors
Run several at once and wait for all
Wait one second
Run once later (setInterval: repeat)

The page (DOM)

First element matching a CSS selector
All matching elements
React to a click
Change the text
Add or remove a class (add, remove too)
Read data-id="…"
Remember a value in this browser
Something not working?

Send feedback

What is it?

The page you’re on, your browser and your screen size are sent along to help us fix it. Never your files or what you typed into the tool.