PLAINFINCH learn by building

JavaScript cheat sheet

The 176 keywords, methods and features you will use most, on one page. The everyday ones come first. Print it, or keep it open beside your editor.

Full reference

Everyday 74

&& || !
Combine or flip true and false conditions.
+ - * / % **
Arithmetic: add, subtract, multiply, divide, remainder, power.
=== and !==
Check whether two values are exactly equal, or not.
+= and ++
Update a variable by adding to it or adding one.
array.filter()
Make a new array holding only the items that pass a test.
array.find()
Get the first item that passes a test, or undefined.
array.forEach()
Run a function once for each item.
array.includes()
Check whether an array contains a value.
array.join()
Combine all items into one string with a separator.
array.length
How many items an array holds.
array.map()
Make a new array by changing every item with a function.
array.push()
Add items to the end of an array.
array.slice()
Copy part of an array without changing the original.
array[index]
Read or set an item by its position, starting at zero.
=> arrow function
Short way to write a function, often used as a callback.
async function
A function that always returns a promise and can use await.
await
Pause an async function until a promise settles.
click event
Fires when an element is clicked or activated by keyboard.
// comments
Notes in code that JavaScript ignores.
console.log()
Print values to the console to see what your code is doing.
const
Declare a variable that cannot be reassigned.
document
The page itself, your starting point for finding elements.
document.createElement()
Make a new element that is not on the page yet.
document.querySelector()
Find the first element matching a CSS selector.
document.querySelectorAll()
Find every element matching a CSS selector.
element.addEventListener()
Run a function when an event happens on an element.
element.append()
Add elements or text at the end of an element.
element.classList.add()
Add one or more classes to an element.
element.classList.remove()
Remove one or more classes from an element.
element.classList.toggle()
Add a class if missing, remove it if present.
element.remove()
Take an element off the page.
element.textContent
Read or set the plain text inside an element.
else if
Check another condition when the previous one was false.
event.preventDefault()
Stop the browser's default action, such as submitting a form.
event.target
The element where the event actually started.
export
Make a value available for other modules to import.
fetch()
Request data from a URL; returns a promise of a response.
for loop
Repeat code with a counter you set up, check and update.
for...of
Loop over each item in an array or other iterable.
function
Declare a named, reusable block of code.
if / else
Run code only when a condition is true.
import
Bring code in from another module file.
input.value
The current text in a form field.
JSON.parse()
Turn a JSON string back into a value.
JSON.stringify()
Turn a value into a JSON string.
let
Declare a variable whose value can be reassigned later.
localStorage.getItem()
Read a saved string, or null if nothing is stored.
localStorage.setItem()
Save a string in the browser that survives reloads.
Math.floor()
Round down to a whole number.
Math.round()
Round to the nearest whole number.
null
A value meaning deliberately empty.
?? nullish coalescing
Use a fallback only when a value is null or undefined.
Number()
Convert a value into a number, or NaN if it cannot.
object destructuring
Pull properties out of an object into variables of the same name.
{ } object literal
Create an object by listing keys and values.
object.key and object[key]
Read or set a property by name.
?. optional chaining
Read a property without crashing if something along the way is missing.
response.json()
Read the response body and parse it as JSON.
response.ok
True when the server answered with a success status.
return
Send a value back from a function and stop running it.
setTimeout()
Run a function once after a delay in milliseconds.
... spread
Copy the items of an array or object into a new one.
string.includes()
Check whether text contains another piece of text.
string.length
How many characters a string has.
string.split()
Break text into an array at each separator.
string.toLowerCase()
Return the text in small letters.
string.toUpperCase()
Return the text in capital letters.
string.trim()
Remove spaces and line breaks from both ends.
submit event
Fires when a form is sent; listen on the form.
`template literals`
Strings in backticks that can include ${values} and line breaks.
? : ternary
Pick one of two values based on a condition, in one expression.
truthy and falsy
How any value behaves when treated as true or false.
try / catch / finally
Run risky code and handle any error it throws.
undefined
The value of something that has not been set.

Also useful 102

aria-live regions
Announce changing text to screen readers.
array destructuring
Pull items out of an array into separate variables.
array.at()
Get an item by position; negative numbers count from the end.
array.every()
Check whether all items pass a test.
array.findIndex()
Get the position of the first item that passes a test.
Array.from()
Turn a list-like thing, such as a NodeList, into a real array.
array.indexOf()
Find the position of a value, or -1 if missing.
Array.isArray()
Check whether a value is an array.
array.pop()
Remove and return the last item.
array.reduce()
Combine all items into a single value, such as a total.
array.reverse()
Reverse the order of items in place.
array.shift()
Remove and return the first item.
array.some()
Check whether at least one item passes a test.
array.sort()
Sort the array in place; pass a compare function for numbers.
array.splice()
Remove or insert items in place, changing the original array.
array.toSorted()
Return a sorted copy and leave the original alone.
array.unshift()
Add items to the start of an array.
break
Exit a loop or switch immediately.
class
Define a blueprint for making objects with shared methods.
clearInterval()
Stop a repeating interval.
clearTimeout()
Cancel a timeout before it runs.
console.error()
Print an error message in the console.
console.table()
Show an array or object as a table in the console.
console.warn()
Print a warning message in the console.
constructor()
Method that sets up a new object made from a class.
continue
Skip to the next round of a loop.
crypto.randomUUID()
Make a random unique id string.
date.getFullYear()
Get the four-digit year from a date.
Date.now()
Current time in milliseconds since 1970.
date.toLocaleDateString()
Show a date in the user's local format.
debugger
Pause the code here when DevTools is open.
default parameters
Give a parameter a fallback value when nothing is passed.
delete
Remove a property from an object.
dialog.close()
Close an open dialog element.
dialog.showModal()
Open a dialog element as a modal that traps focus.
document.getElementById()
Find the element with a given id.
element.classList.contains()
Check whether an element has a class.
element.closest()
Find the nearest ancestor, or itself, matching a selector.
element.dataset
Read and write the element's data-* attributes.
element.disabled
Turn a button or field off and on.
element.focus()
Move keyboard focus to an element.
element.getAttribute()
Read an attribute's current value.
element.hidden
Show or hide an element with the hidden attribute.
element.innerHTML
Read or set the HTML inside an element; never use untrusted text.
element.prepend()
Add elements or text at the start of an element.
element.removeEventListener()
Stop a function from responding to an event.
element.replaceChildren()
Swap out everything inside an element, or empty it.
element.scrollIntoView()
Scroll the page until an element is visible.
element.setAttribute("aria-expanded")
Tell assistive tech whether a toggle is open.
element.setAttribute()
Set an attribute such as href, alt or aria-label.
element.style
Set inline styles; property names use camelCase.
error.message
The readable text describing what went wrong.
event.currentTarget
The element the listener is attached to.
event.key
Which key was pressed in a keyboard event.
export default
Mark the main value a module provides.
input / change events
Fire as a field's value changes, or once it is committed.
input.checked
Whether a checkbox or radio button is ticked.
Intl.DateTimeFormat
Format dates and times for a locale.
Intl.NumberFormat
Format numbers, prices and percentages for a locale.
keydown event
Fires when a key is pressed.
localStorage.removeItem()
Delete one saved item.
Math.ceil()
Round up to a whole number.
Math.min() / Math.max()
Get the smallest or largest of several numbers.
Math.random()
Get a random number from 0 up to, not including, 1.
NaN
Special number meaning the result is not a valid number.
new
Create an object from a class or constructor.
new Date()
Create a date for now or for a given moment.
new Error()
Create an error object with a message you choose.
new FormData()
Collect all named fields from a form.
new URLSearchParams()
Read or build the ?key=value part of a URL.
Number.isNaN()
Check whether a value is exactly NaN.
number.toFixed()
Format a number with a set number of decimal places.
number.toLocaleString()
Format a number with the user's separators.
Object.entries()
Get an array of [key, value] pairs.
Object.keys()
Get an array of an object's property names.
Object.values()
Get an array of an object's property values.
parseFloat()
Read a decimal number from the start of a string.
parseInt()
Read a whole number from the start of a string.
Promise
An object standing for a value that will arrive later.
Promise.all()
Wait for several promises; fail if any one fails.
promise.catch()
Run a function when a promise fails.
promise.then()
Run a function when a promise succeeds.
response.status
The numeric HTTP status code, such as 200 or 404.
...rest parameters
Collect any remaining arguments into an array.
<script type="module">
Load a script as a module so import and export work.
sessionStorage
Like localStorage but cleared when the tab closes.
setInterval()
Run a function repeatedly at a fixed delay.
String()
Convert a value into a string.
string.endsWith()
Check whether text finishes with certain characters.
string.padStart()
Add characters to the front until text reaches a length.
string.replace()
Swap the first match for new text.
string.replaceAll()
Swap every match for new text.
string.slice()
Copy part of a string by start and end positions.
string.startsWith()
Check whether text begins with certain characters.
structuredClone()
Make a deep copy of an object, nested parts included.
style.setProperty()
Set a CSS property or custom property such as --size.
switch
Compare one value against several cases.
this
The object a method was called on.
throw
Raise an error on purpose to stop bad input.
typeof
Get a string naming the type of a value.
while
Repeat code as long as a condition stays true.
window.matchMedia()
Check a media query, such as prefers-reduced-motion, from JavaScript.

PlainFinch JavaScript cheat sheet · plainfinch.com/js/cheat-sheet/ · version 3.25.2