JavaScript Cheat Sheet
The JavaScript you need most often, from variables to the DOM, each concept explained in one or two lines. It follows the same order as the course, so you can revise as you learn.
Nothing matches your search.
Getting started and variables
Full lesson<script src="app.js" defer>- Loads a JavaScript file. defer waits until the HTML has been parsed.
console.log(x)- Prints a value to the browser console. The first debugging tool you learn.
// and /* */- A single-line comment and a multi-line comment.
let- Declares a variable whose value can change. Block scoped.
const- Declares a variable that cannot be reassigned. The default choice. Objects and arrays declared with const can still be changed inside.
var- The old way to declare variables. Function scoped and hoisted, so avoid it in new code.
naming rules- Use camelCase, start with a letter, _ or $, and never use a reserved word like class.
Data types
Full lessonstring- Text in single quotes, double quotes or backticks.
number- Integers and decimals share one type. Includes NaN and Infinity.
boolean- true or false.
null- An intentional "no value".
undefined- A variable that has been declared but not given a value yet.
bigint- Whole numbers of any size, written with an n: 123n.
symbol- A guaranteed-unique value, mostly used as an object key.
object- Everything else: plain objects, arrays, functions, dates and more.
typeof x- Returns the type as a string. Quirk: typeof null is "object".
Operators
Full lesson+ - * / % **- Add, subtract, multiply, divide, remainder and power.
++ and --- Add or subtract one from a variable.
= += -= *= /=- Assign a value, or update it using its current value.
=== and !==- Strict equal and not equal. They compare value and type. Use these by default.
== and !=- Loose equal. They convert types first and give surprising results, so avoid them.
< > <= >=- Comparison operators.
&& || !- AND, OR, NOT. && and || return one of their operands, not just true or false.
condition ? a : b- Ternary operator: a short if/else that returns a value.
??- Nullish coalescing: use the right side only if the left is null or undefined.
??= ||= &&=- Assign only when the variable is nullish, falsy or truthy.
typeof, instanceof, in- Check a value's type, whether an object comes from a class, and whether a property exists.
Type conversion and coercion
Full lessonNumber("42")- Converts to a number. Gives NaN when the text is not numeric.
String(42)- Converts to a string. Also (42).toString() or a template literal.
Boolean(x)- Converts to true or false. !!x does the same.
parseInt("42px", 10)- Reads a whole number from the start of a string. Always pass 10 as the base.
parseFloat("3.5kg")- Reads a decimal number from the start of a string.
falsy values- false, 0, -0, 0n, "", null, undefined and NaN. Everything else is truthy, including "0" and [].
"5" + 2- Gives "52". With + a string wins and everything is joined as text.
"5" - 2- Gives 3. Other maths operators convert strings to numbers.
coercion- JavaScript converting types automatically. It explains most "weird" results, which is why === is safer.
Strings
Full lesson`Hello ${name}`- Template literal. Embeds expressions and can span several lines.
str.length- The number of characters.
str[0] or str.at(-1)- Gets a character by position. at(-1) counts from the end.
toUpperCase() / toLowerCase()- Changes the case.
trim()- Removes spaces from both ends. trimStart() and trimEnd() do one side.
includes(), startsWith(), endsWith()- Check whether the text contains, begins with or ends with something.
indexOf("x")- Position of the first match, or -1 when there is none.
slice(start, end)- Returns part of the string. End is not included and can be negative.
split(",")- Splits a string into an array.
replace() / replaceAll()- Replace the first or every match. Strings are immutable, so a new string is returned.
padStart(5, "0")- Pads the start to a length, e.g. "7" becomes "00007". padEnd does the end.
repeat(3)- Repeats the string.
Numbers and Math
Full lessonMath.round(), floor(), ceil(), trunc()- Round to nearest, down, up, or cut off the decimals.
Math.max() / Math.min()- Largest or smallest of the arguments. Use Math.max(...arr) for arrays.
Math.abs()- Absolute value (removes the minus sign).
Math.pow(a, b) or a ** b- Raises a to the power b.
Math.sqrt()- Square root.
Math.random()- A random decimal from 0 up to (not including) 1.
Math.floor(Math.random() * n)- A random whole number from 0 to n - 1.
num.toFixed(2)- Formats to 2 decimals. Returns a string.
Number.isNaN(x)- Safe NaN check. NaN is the only value not equal to itself.
Number.isInteger(x)- Checks for a whole number.
0.1 + 0.2- Gives 0.30000000000000004. Decimal maths is approximate in every language, so round for display.
Conditions
Full lessonif / else if / else- Runs the first block whose condition is true.
switch (x) { case 1: ... break; default: }- Chooses between many exact values. Forget break and it falls through to the next case.
truthy / falsy- Any value works in a condition. Falsy values act as false.
early return- Handle the unusual cases first and return, to avoid deep nesting.
x ?? default- Fallback only for null and undefined, so 0 and "" are kept.
Loops
Full lessonfor (let i = 0; i < n; i++)- Classic counting loop: start, condition, step.
while (condition)- Repeats while the condition is true. Make sure something changes it.
do { } while (condition)- Always runs at least once, then checks.
break- Stops the loop completely.
continue- Skips to the next round of the loop.
for (const x of iterable)- Loops over the values of arrays, strings, Maps and Sets.
for (const key in object)- Loops over an object's keys. Do not use it on arrays.
labels- Name a loop to break or continue an outer loop from an inner one.
Functions
Full lessonfunction add(a, b) { return a + b; }- Function declaration. It is hoisted, so you can call it before it is written.
const add = function (a, b) { }- Function expression. Stored in a variable and not hoisted.
const add = (a, b) => a + b- Arrow function. Short syntax. A single expression is returned automatically.
default parameters- function greet(name = "friend") uses the default when the argument is missing.
...args (rest parameter)- Collects the remaining arguments into a real array.
return- Sends a value back and stops the function. Without it the result is undefined.
arrow functions and this- Arrows have no own this. They use the one from the surrounding code.
IIFE- (function () { ... })() runs immediately and keeps its variables private.
pure function- Same input always gives the same output and changes nothing outside. Easy to test.
scope- Where a variable can be seen: global, function or block ({ }).
hoisting- Declarations are moved up before the code runs. let and const exist but cannot be used before their line (the temporal dead zone).
callback- A function passed to another function to be called later.
higher-order function- A function that takes or returns another function, like map and filter.
closure- A function that remembers the variables from where it was created, even after that outer function has finished.
Arrays
Full lesson[1, 2, 3]- Create an array. Indexes start at 0.
arr.length- The number of items. arr[arr.length - 1] or arr.at(-1) is the last item.
push() / pop()- Add or remove at the end. Changes the original array.
unshift() / shift()- Add or remove at the start. Changes the original array.
splice(start, count, ...new)- Remove or insert items in the middle. Changes the original array.
slice(start, end)- Copies part of an array without changing it.
concat() or [...a, ...b]- Joins arrays into a new array.
join(", ")- Turns an array into a string.
includes(x)- true if the array contains the value.
indexOf(x)- Position of the first match, or -1.
Array.isArray(x)- Checks whether something is an array. typeof gives "object".
Array.from(x)- Creates an array from an iterable or array-like value, such as a NodeList.
forEach(fn)- Runs a function for each item. Returns nothing.
map(fn)- Returns a new array with every item transformed.
filter(fn)- Returns a new array with only the items where fn returns true.
reduce(fn, start)- Combines all items into a single value, such as a total.
find(fn) / findIndex(fn)- The first matching item, or its position.
findLast(fn)- The last matching item.
some(fn) / every(fn)- true if at least one item, or all items, pass the test.
sort()- Sorts the array in place as text by default. Use sort((a, b) => a - b) for numbers.
toSorted() / toReversed()- Sorted or reversed copies that leave the original untouched.
reverse()- Reverses the array in place.
flat(depth) / flatMap(fn)- Flattens nested arrays, or maps and flattens in one step.
[...arr] and Array.from(arr)- Make a shallow copy of an array.
Objects
Full lesson{ name: "Sam", age: 20 }- An object literal: key-value pairs.
obj.name and obj["name"]- Dot notation for normal keys. Brackets for keys stored in a variable or containing spaces.
delete obj.key- Removes a property.
"key" in obj- Checks whether a property exists. obj.hasOwnProperty("key") or Object.hasOwn(obj, "key") checks only the object itself.
{ name, age }- Shorthand: the variable name becomes the key.
[expr]: value- A computed key in an object literal.
method() { }- A function stored on an object.
Object.keys / values / entries- Arrays of the keys, the values, or [key, value] pairs.
Object.fromEntries(entries)- Builds an object from [key, value] pairs. The reverse of entries.
Object.assign(target, src)- Copies properties from one object into another.
Object.freeze(obj)- Makes an object read-only (shallow).
Object.seal(obj)- Stops adding or removing properties but allows changing values.
this- Usually the object the method was called on. In a plain function it depends on how it is called.
bind / call / apply- Set what this should be for a function call.
const { a, b } = obj- Object destructuring: pull out properties into variables. Rename with { a: x }, default with { a = 1 }.
const [x, y] = arr- Array destructuring: pull out items by position.
{ ...obj, extra: 1 }- Spread: copy an object and add or override properties.
primitive vs reference- Strings, numbers and booleans are copied. Objects and arrays are shared by reference.
structuredClone(obj)- Makes a deep copy of an object.
obj?.a?.b- Optional chaining: gives undefined instead of an error if something in the chain is missing.
fn?.()- Calls a function only if it exists.
Map, Set, JSON, dates and regex
Full lessonnew Map()- Key-value pairs where keys can be any type and order is kept. Methods: set, get, has, delete, size.
new Set()- A collection of unique values. [...new Set(arr)] removes duplicates.
WeakMap / WeakSet- Hold objects without stopping them being garbage collected. Cannot be looped over.
JSON.stringify(obj)- Turns a value into a JSON string. Functions and undefined are dropped.
JSON.parse(text)- Turns a JSON string back into a value. Throws an error if the JSON is invalid, so wrap it in try/catch.
new Date()- The current date and time. new Date("2026-10-03") parses a date.
Date.now()- The current time as milliseconds since 1 January 1970.
date.getFullYear(), getMonth(), getDate()- Read parts of a date. Months start at 0 for January.
date.toISOString()- A standard UTC text form: 2026-10-03T08:30:00.000Z.
date.toLocaleDateString()- A date formatted for the visitor's language and region.
/pattern/flags- A regular expression. g finds all matches, i ignores case, m is multiline.
regex.test(str)- true if the pattern matches.
str.match(regex)- Returns the matches. With the g flag use matchAll for details.
\d \w \s- Regex shortcuts for a digit, a word character and whitespace. Capital letters mean the opposite.
^ $ . * + ?- Start, end, any character, zero or more, one or more, zero or one.
( ) [ ] { }- A group, a set of characters, and a count such as {3}.
Errors, debugging and symbols
Full lessontry { } catch (err) { }- Run risky code and handle an error instead of crashing.
finally { }- Always runs after try and catch. Good for cleanup.
throw new Error("message")- Raises your own error and stops normal flow.
err.name and err.message- The type of error (TypeError, ReferenceError, SyntaxError) and its description.
class MyError extends Error- A custom error type for your own situations.
"use strict"- Turns on strict mode: silent mistakes become real errors, for example using an undeclared variable.
debugger- Pauses the code at that line when DevTools is open.
console.table(data)- Prints arrays and objects as a table.
console.error() / warn()- Print an error or a warning in colour.
DevTools Sources tab- Set breakpoints, step through code and inspect variables.
Symbol("id")- Creates a unique value, often used as a hidden property key.
DOM: selecting and walking the tree
Full lessondocument- The entry point to the page. document.body and document.head are shortcuts.
getElementById("id")- One element by its id, or null.
querySelector(".card")- The first element matching any CSS selector, or null.
querySelectorAll("li")- A static NodeList of all matches. It supports forEach.
getElementsByClassName / TagName- Older methods that return a live collection.
el.closest(".card")- The nearest ancestor (or itself) that matches the selector.
el.matches(".active")- true if the element matches the selector.
parentElement- The parent element.
children- The child elements as a collection. childNodes also includes text nodes.
firstElementChild / lastElementChild- The first and last child element.
nextElementSibling / previousElementSibling- The neighbouring elements.
DOM: changing content, attributes and styles
Full lessonel.textContent- Gets or sets plain text. Safe from injected HTML.
el.innerText- Like textContent but follows what is visible and is slower.
el.innerHTML- Gets or sets HTML as a string. Never insert untrusted input with it, because it can run scripts.
el.getAttribute("x")- Reads an attribute.
el.setAttribute("x", value)- Sets or changes an attribute.
el.removeAttribute("x") / hasAttribute("x")- Removes or checks an attribute.
el.dataset.userId- Reads data-user-id attributes. Names turn into camelCase.
el.style.color = "red"- Sets an inline style. CSS names become camelCase: backgroundColor.
el.classList.add("on")- Adds a class. remove() removes it.
classList.toggle("on")- Adds the class if missing, removes it if present.
classList.contains("on")- true if the class is present.
document.createElement("div")- Creates a new element in memory.
parent.append(el) / prepend(el)- Adds an element at the end or start of a parent.
el.insertAdjacentHTML("beforeend", html)- Inserts HTML at a chosen position without rebuilding the element.
el.remove()- Removes the element from the page.
el.cloneNode(true)- Copies an element and everything inside it.
Events
Full lessonel.addEventListener("click", fn)- Runs fn when the event happens. The recommended way to handle events.
el.removeEventListener("click", fn)- Removes a listener. You need the same function reference.
{ once: true }- Listener option: run only one time. Also passive and capture.
click, dblclick, contextmenu- Mouse button events.
mouseover, mouseout, mousemove- Pointer movement events.
keydown, keyup- Keyboard events. Read event.key, such as "Enter" or "Escape".
input- Fires on every change in a field. change fires when the value is committed.
submit- Fires when a form is submitted.
focus, blur- An element gained or lost focus.
DOMContentLoaded- The HTML is parsed and ready. Not needed if the script uses defer.
load- The whole page including images has finished loading.
scroll, resize- The page was scrolled or the window changed size. These fire often, so keep the handler light.
event.target- The element that was actually clicked or changed.
event.currentTarget- The element the listener is attached to.
event.preventDefault()- Stops the browser's default action, such as a form submit or link navigation.
event.stopPropagation()- Stops the event from bubbling up to parent elements.
bubbling and capturing- Events travel down to the target (capture) and back up (bubble). Listeners run on the way up by default.
event delegation- Put one listener on a parent and check event.target. It also works for elements added later.
Browser, input, forms and storage
Full lessonalert(msg)- Shows a message box. It blocks the page until dismissed.
prompt(msg)- Asks for text. Returns a string, or null if cancelled.
confirm(msg)- Asks OK or Cancel. Returns true or false.
window- The global browser object. Top-level var variables and function declarations become its properties.
location.href- The current URL. Assign to it to navigate. location.reload() refreshes.
history.back() / forward()- Move through the visitor's browsing history.
navigator.userAgent, language, onLine- Information about the browser and connection.
input.value- The current text of a form control, always as a string.
checkbox.checked- true or false for checkboxes and radios.
form.checkValidity()- true if every field passes its HTML validation rules.
input.setCustomValidity(msg)- Sets a custom validation message. An empty string clears it.
new FormData(form)- Collects every field in a form. Use Object.fromEntries(formData) to get a plain object.
localStorage.setItem(k, v)- Saves a string that stays after the browser is closed.
localStorage.getItem(k)- Reads a saved string, or null.
removeItem(k) / clear()- Delete one saved item or all of them.
sessionStorage- The same API, but cleared when the tab is closed.
storing objects- Storage holds only strings, so use JSON.stringify to save and JSON.parse to read.
new URL(address)- Parses a URL into parts such as hostname, pathname and searchParams.
new URLSearchParams(location.search)- Reads query parameters with get(), has(), set() and append().