Everyday JavaScript
&& || ! 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.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.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.findIndex() Get the position of the first item that passes a test.array.flat() Flatten nested arrays into one level.array.forEach() Run a function once for each item.Array.from() Turn a list-like thing, such as a NodeList, into a real array.array.includes() Check whether an array contains a value.array.indexOf() Find the position of a value, or -1 if missing.Array.isArray() Check whether a value is an array.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.pop() Remove and return the last item.array.push() Add items to the end of an array.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.slice() Copy part of an array without changing the original.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.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.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.click event Fires when an element is clicked or activated by keyboard.// comments Notes in code that JavaScript ignores.console.error() Print an error message in the console.console.group() Indent related console messages under a heading.console.log() Print values to the console to see what your code is doing.console.table() Show an array or object as a table in the console.console.time() Measure how long some code takes to run.console.warn() Print a warning message in the console.const Declare a variable that cannot be reassigned.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.toISOString() Turn a date into a standard text format for storage.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 The page itself, your starting point for finding elements.document.cookie Read or write the page's cookies as one string.document.createElement() Make a new element that is not on the page yet.document.getElementById() Find the element with a given id.document.querySelector() Find the first element matching a CSS selector.document.querySelectorAll() Find every element matching a CSS selector.DOMContentLoaded Event fired once the HTML has been fully read.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.before() / after() Insert content just outside an element.element.classList.add() Add one or more classes to an element.element.classList.contains() Check whether an element has a class.element.classList.remove() Remove one or more classes from an element.element.classList.toggle() Add a class if missing, remove it if present.element.cloneNode() Copy an element, optionally with everything inside it.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.matches() Check whether an element matches a CSS selector.element.prepend() Add elements or text at the start of an element.element.remove() Take an element off the page.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.element.textContent Read or set the plain text inside an element.else if Check another condition when the previous one was false.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.event.preventDefault() Stop the browser's default action, such as submitting a form.event.stopPropagation() Stop an event from bubbling up to parent elements.event.target The element where the event actually started.export Make a value available for other modules to import.export default Mark the main value a module provides.extends Make a class that builds on another class.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.form.checkValidity() Check whether every field passes its HTML rules.form.reportValidity() Check fields and show the browser's error messages.function Declare a named, reusable block of code.getComputedStyle() Read the styles the browser actually applied.if / else Run code only when a condition is true.import Bring code in from another module file.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.input.value The current text in a form field.Intl.DateTimeFormat Format dates and times for a locale.Intl.NumberFormat Format numbers, prices and percentages for a locale.JSON.parse() Turn a JSON string back into a value.JSON.stringify() Turn a value into a JSON string.keydown event Fires when a key is pressed.let Declare a variable whose value can be reassigned later.localStorage.getItem() Read a saved string, or null if nothing is stored.localStorage.removeItem() Delete one saved item.localStorage.setItem() Save a string in the browser that survives reloads.Math.abs() Get a number without its minus sign.Math.ceil() Round up to a whole number.Math.floor() Round down 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.Math.round() Round to the nearest whole number.NaN Special number meaning the result is not a valid number.new Create an object from a class or constructor.new AbortController() Cancel a fetch or remove listeners when you no longer need them.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 Promise() Wrap callback-based code so it returns a promise.new URL() Parse a web address into its parts.new URLSearchParams() Read or build the ?key=value part of a URL.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.Number.isInteger() Check whether a value is a whole number.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 destructuring Pull properties out of an object into variables of the same name.{ } object literal Create an object by listing keys and values.Object.assign() Copy properties from one or more objects into a target.Object.entries() Get an array of [key, value] pairs.Object.fromEntries() Build an object from a list of [key, value] pairs.object.key and object[key] Read or set a property by name.Object.keys() Get an array of an object's property names.Object.values() Get an array of an object's property values.{ once: true } Listener option that removes itself after running once.?. optional chaining Read a property without crashing if something along the way is missing.parseFloat() Read a decimal number from the start of a string.parseInt() Read a whole number from the start of a string.performance.now() High-precision time for measuring how long something takes.Promise An object standing for a value that will arrive later.Promise.all() Wait for several promises; fail if any one fails.Promise.allSettled() Wait for several promises and report each result.promise.catch() Run a function when a promise fails.promise.finally() Run a function when a promise settles either way.Promise.race() Settle as soon as the first promise settles.promise.then() Run a function when a promise succeeds.requestAnimationFrame() Run a function just before the browser draws the next frame.response.json() Read the response body and parse it as JSON.response.ok True when the server answered with a success status.response.status The numeric HTTP status code, such as 200 or 404.response.text() Read the response body as plain text....rest parameters Collect any remaining arguments into an array.return Send a value back from a function and stop running it.<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.setTimeout() Run a function once after a delay in milliseconds.... spread Copy the items of an array or object into a new one.String() Convert a value into a string.string.endsWith() Check whether text finishes with certain characters.string.includes() Check whether text contains another piece of text.string.length How many characters a string has.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.split() Break text into an array at each separator.string.startsWith() Check whether text begins with certain characters.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.structuredClone() Make a deep copy of an object, nested parts included.style.setProperty() Set a CSS property or custom property such as --size.submit event Fires when a form is sent; listen on the form.switch Compare one value against several cases.`template literals` Strings in backticks that can include ${values} and line breaks.template.content The ready-to-copy contents of a template element.? : ternary Pick one of two values based on a condition, in one expression.this The object a method was called on.throw Raise an error on purpose to stop bad input.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.typeof Get a string naming the type of a value.undefined The value of something that has not been set.while Repeat code as long as a condition stays true.window.matchMedia() Check a media query, such as prefers-reduced-motion, from JavaScript.