Skip to content

JavaScript Quick Reference

A quick lookup for JavaScript language features grouped by category. Each entry covers what it does and how to use it, so you can find answers without leaving the platform.

OperatorWhat it doesExample
+Addition (also concatenates strings)3 + 25
-Subtraction3 - 21
*Multiplication3 * 26
/Division6 / 23
%Remainder (modulo)7 % 31
**Exponentiation2 ** 38
++Increment by 1x++ or ++x
--Decrement by 1x-- or --x
OperatorWhat it doesNotes
===Strict equality — value and typePrefer over ==
!==Strict inequalityPrefer over !=
==Loose equality — type-coercesAvoid
!=Loose inequalityAvoid
<Less than
>Greater than
<=Less than or equal
>=Greater than or equal
OperatorWhat it doesExample
&&AND — true if both sides are truthyisOpen && hasStock
||OR — true if either side is truthyisGuest || isAdmin
!NOT — inverts truthiness!isLoading
??Nullish coalescing — right side if left is null/undefinedname ?? 'Guest'
OperatorEquivalent to
x = yassign y to x
x += yx = x + y
x -= yx = x - y
x *= yx = x * y
x /= yx = x / y
x %= yx = x % y
x **= yx = x ** y

The ternary operator is a compact if/else expression:

const label = count === 1 ? 'item' : 'items';
// If count is 1, label is 'item'; otherwise 'items'
const discount = isMember ? 0.1 : 0;

condition ? valueIfTrue : valueIfFalse

All array methods are called on an array instance. Methods that accept a callback receive (element, index, array) — use only what you need.

MethodWhat it doesReturns
forEach(fn)Runs fn for each element — no return valueundefined
map(fn)Transforms each element with fnNew array
filter(fn)Keeps elements where fn returns trueNew array
find(fn)First element where fn returns trueElement or undefined
findIndex(fn)Index of first matchNumber or -1
reduce(fn, initial)Accumulates elements to a single valueAccumulated value
some(fn)true if any element passes fnBoolean
every(fn)true if all elements pass fnBoolean
includes(value)true if value is in the arrayBoolean
indexOf(value)Index of first occurrenceNumber or -1
push(item)Adds item to the end — mutatesNew length
pop()Removes and returns the last element — mutatesRemoved element
shift()Removes and returns the first element — mutatesRemoved element
unshift(item)Adds item to the beginning — mutatesNew length
splice(start, n)Removes n elements at start — mutatesRemoved elements
slice(start, end)Copies from start up to (not including) endNew array
sort(fn)Sorts in place — mutatesSame array
reverse()Reverses in place — mutatesSame array
join(separator)Joins all elements into a stringString
flat(depth)Flattens nested arraysNew array
flatMap(fn)map then flat(1)New array
const prices = [12, 5, 8, 20, 3];
// map — apply a transformation
const withTax = prices.map(p => p * 1.1);
// filter — keep items that pass the test
const affordable = prices.filter(p => p < 10);
// find — first item that matches
const firstExpensive = prices.find(p => p > 15); // 20
// reduce — sum all values
const total = prices.reduce((sum, p) => sum + p, 0); // 48
// chaining
const result = prices
.filter(p => p >= 5)
.map(p => p * 1.1)
.sort((a, b) => a - b);

push, pop, splice, sort, and reverse mutate the original array. map, filter, slice, and reduce return a new array and leave the original unchanged.

These methods and properties are available on element objects returned by query methods. document refers to the global document object.

MethodWhat it doesReturns
document.querySelector(selector)First element matching a CSS selectorElement or null
document.querySelectorAll(selector)All elements matching a CSS selectorNodeList (array-like)
document.getElementById(id)Element with the given idElement or null
document.getElementsByClassName(name)Elements with the given classHTMLCollection
Method / PropertyWhat it does
document.createElement(tag)Creates a new element — not yet in the DOM
element.append(node)Adds a node or text string as the last child
element.prepend(node)Adds a node or text string as the first child
element.remove()Removes the element from the DOM
parent.removeChild(child)Removes a specific child node
element.cloneNode(deep)Copies the element; deep: true copies children too
Property / MethodWhat it doesNotes
element.textContentGets or sets all text contentSafe — no HTML parsing
element.innerHTMLGets or sets HTML string contentParses HTML — avoid with user input
element.setAttribute(name, value)Sets an attribute
element.getAttribute(name)Gets an attribute value
element.removeAttribute(name)Removes an attribute
element.datasetObject of all data-* attributesdata-user-iddataset.userId
Method / PropertyWhat it does
element.classList.add(name)Adds a class
element.classList.remove(name)Removes a class
element.classList.toggle(name)Adds if absent, removes if present
element.classList.contains(name)Returns true if the class is present
element.classList.replace(old, new)Swaps one class for another
element.style.propertyGets or sets an inline style — use camelCase (backgroundColor)
// Select and modify
const btn = document.querySelector('#submit-btn');
btn.textContent = 'Save changes';
btn.classList.add('is-loading');
// Create and insert
const li = document.createElement('li');
li.textContent = 'New item';
document.querySelector('ul').append(li);
// Data attributes
// <div data-tour-id="42" data-price="89">
const card = document.querySelector('[data-tour-id]');
console.log(card.dataset.tourId); // '42'
console.log(card.dataset.price); // '89'

querySelectorAll returns a NodeList — use forEach to iterate, or spread into an array with [...nodeList] to access full array methods.

Attach events with element.addEventListener(type, handler). Remove with element.removeEventListener(type, handler) using the same function reference.

EventFires when
clickUser clicks the element
dblclickUser double-clicks the element
mouseenterPointer moves onto the element (does not bubble)
mouseleavePointer moves off the element (does not bubble)
mouseoverPointer moves onto the element or a descendant (bubbles)
mouseoutPointer moves off the element or a descendant (bubbles)
mousemovePointer moves over the element
contextmenuUser right-clicks the element
EventFires whenUseful properties
keydownKey is pressed — fires repeatedly while heldevent.key, event.code, event.ctrlKey
keyupKey is releasedevent.key, event.code

keypress is deprecated — use keydown instead.

EventFires when
submitForm is submitted
inputValue changes as the user types
changeValue is committed (on blur or selection change)
focusElement receives focus
blurElement loses focus
resetForm is reset
EventFires when
DOMContentLoadedHTML is parsed and the DOM is ready (before images/styles load)
loadPage and all resources (images, styles) have loaded
resizeBrowser window is resized
scrollUser scrolls the page or an element
// Click handler
document.querySelector('#menu-btn').addEventListener('click', () => {
document.querySelector('#nav').classList.toggle('is-open');
});
// Form submit with preventDefault
document.querySelector('form').addEventListener('submit', (event) => {
event.preventDefault();
const name = event.target.elements['name'].value;
console.log('Submitted:', name);
});
// Keyboard shortcut
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
closeModal();
}
});
// Run after DOM is ready
document.addEventListener('DOMContentLoaded', () => {
initApp();
});

Use mouseenter/mouseleave for hover effects on a single element. Use mouseover/mouseout only when you need to detect movement over child elements too.