JavaScript: JavaScript Quick Reference
This page is a quick-reference cheat sheet for common JavaScript syntax and APIs, organized by category.
1. Statement Reference
| Statement | Syntax | Description |
|---|---|---|
var |
var name = value; |
Function-scoped variable declaration (deprecated — use let instead) |
let |
let name = value; |
Block-scoped variable declaration, reassignable |
const |
const name = value; |
Block-scoped constant declaration, not reassignable |
if/else |
if (cond) {} else if (cond) {} else {} |
Conditional branching |
for |
for (let i = 0; i < n; i++) {} |
Classic loop |
while |
while (cond) {} |
Condition-first loop |
do...while |
do {} while (cond); |
Body-first loop (runs at least once) |
switch |
switch (expr) { case val: break; default: } |
Multi-branch matching |
try/catch |
try {} catch (err) {} finally {} |
Exception handling |
function |
function name(params) {} |
Function declaration |
return |
return value; |
Return a value from a function |
class |
class Name { constructor() {} } |
Class declaration |
import |
import { name } from 'module'; |
Import a module |
export |
export const name = value; |
Export from a module |
2. Operator Reference
| Category | Operators | Description |
|---|---|---|
| Arithmetic | + - * / % ** |
Add, subtract, multiply, divide, remainder, exponentiation |
| Arithmetic | ++ -- |
Increment, decrement |
| Comparison | == != === !== |
Equal, not equal, strict equal, strict not equal |
| Comparison | > < >= <= |
Greater than, less than, greater or equal, less or equal |
| Logical | && || ! |
AND, OR, NOT |
| Assignment | = += -= *= /= %= |
Assignment and compound assignment |
| Ternary | cond ? a : b |
Conditional expression |
| Spread | ...arr |
Spread an array or object |
3. String Methods Cheat Sheet
| Method | Syntax | Description |
|---|---|---|
length |
str.length |
String length (property, not a method) |
charAt |
str.charAt(index) |
Character at the given position |
indexOf |
str.indexOf(search, from?) |
Find substring position; returns -1 if not found |
includes |
str.includes(search, from?) |
Check if substring exists; returns boolean |
slice |
str.slice(start, end?) |
Extract a substring (supports negative indices) |
substring |
str.substring(start, end?) |
Extract a substring (no negative indices) |
replace |
str.replace(pattern, replacement) |
Replace the first match |
toUpperCase |
str.toUpperCase() |
Convert to uppercase |
toLowerCase |
str.toLowerCase() |
Convert to lowercase |
trim |
str.trim() |
Remove leading and trailing whitespace |
split |
str.split(separator, limit?) |
Split string into an array by separator |
padStart |
str.padStart(length, fill) |
Pad the start to a given length |
padEnd |
str.padEnd(length, fill) |
Pad the end to a given length |
repeat |
str.repeat(count) |
Repeat the string |
match |
str.match(regexp) |
Regex match; returns array or null |
4. Array Methods Cheat Sheet
| Method | Syntax | Description |
|---|---|---|
push |
arr.push(item) |
Add to end; returns new length |
pop |
arr.pop() |
Remove from end; returns removed item |
shift |
arr.shift() |
Remove from start; returns removed item |
unshift |
arr.unshift(item) |
Add to start; returns new length |
splice |
arr.splice(start, deleteCount, ...items) |
Add/remove/replace (mutates the array) |
slice |
arr.slice(start, end?) |
Extract a sub-array (does not mutate) |
map |
arr.map(fn) |
Transform each element; returns a new array |
filter |
arr.filter(fn) |
Keep elements that pass the test; returns a new array |
reduce |
arr.reduce(fn, init) |
Accumulate a single result from the array |
find |
arr.find(fn) |
Return the first element that passes the test |
findIndex |
arr.findIndex(fn) |
Return the index of the first matching element |
sort |
arr.sort(compareFn?) |
Sort the array (mutates it) |
reverse |
arr.reverse() |
Reverse the array (mutates it) |
forEach |
arr.forEach(fn) |
Iterate over each element; no return value |
every |
arr.every(fn) |
Check if all elements pass the test |
some |
arr.some(fn) |
Check if at least one element passes the test |
includes |
arr.includes(item, from?) |
Check if the array contains an element |
indexOf |
arr.indexOf(item, from?) |
Find the index of an element |
join |
arr.join(separator?) |
Join array into a string |
concat |
arr.concat(arr2) |
Merge arrays (does not mutate) |
flat |
arr.flat(depth?) |
Flatten nested arrays |
5. Math Methods Cheat Sheet
| Method | Syntax | Description |
|---|---|---|
round |
Math.round(x) |
Round to the nearest integer |
floor |
Math.floor(x) |
Round down |
ceil |
Math.ceil(x) |
Round up |
random |
Math.random() |
Random number in [0, 1) |
max |
Math.max(a, b, ...) |
Return the largest value |
min |
Math.min(a, b, ...) |
Return the smallest value |
abs |
Math.abs(x) |
Absolute value |
pow |
Math.pow(base, exp) |
Exponentiation |
sqrt |
Math.sqrt(x) |
Square root |
PI |
Math.PI |
Pi ≈ 3.14159 |
E |
Math.E |
Euler's number ≈ 2.71828 |
trunc |
Math.trunc(x) |
Remove the fractional part |
sign |
Math.sign(x) |
Returns 1 / 0 / -1 |
6. DOM Methods Cheat Sheet
| Method/Property | Syntax | Description |
|---|---|---|
getElementById |
document.getElementById('id') |
Get a single element by ID |
querySelector |
document.querySelector('selector') |
Get the first element matching a CSS selector |
querySelectorAll |
document.querySelectorAll('selector') |
Get all elements matching a CSS selector |
getElementsByClassName |
document.getElementsByClassName('cls') |
Get elements by class name (live collection) |
getElementsByTagName |
document.getElementsByTagName('tag') |
Get elements by tag name (live collection) |
textContent |
el.textContent |
Read or write plain text content |
innerHTML |
el.innerHTML |
Read or write HTML content (watch out for XSS) |
setAttribute |
el.setAttribute('name', 'value') |
Set an attribute |
getAttribute |
el.getAttribute('name') |
Get an attribute value |
classList |
el.classList.add/remove/toggle/contains |
Manipulate CSS classes |
createElement |
document.createElement('tag') |
Create a new element node |
appendChild |
parent.appendChild(child) |
Append a child node to the end |
removeChild |
parent.removeChild(child) |
Remove a child node |
cloneNode |
el.cloneNode(deep?) |
Clone a node (true = deep clone) |
7. Event Reference
| Event | When It Fires | Common Elements |
|---|---|---|
click |
Single click | Any element |
dblclick |
Double click | Any element |
mouseover |
Mouse enters | Any element |
mouseout |
Mouse leaves | Any element |
keydown |
Key pressed down | document, form elements |
keyup |
Key released | document, form elements |
submit |
Form submitted | form |
change |
Value changed and lost focus | input, select, textarea |
input |
Value changed in real time | input, textarea |
load |
Page and resources fully loaded | window |
DOMContentLoaded |
HTML parsing complete | document |
focus |
Element gains focus | Form elements |
blur |
Element loses focus | Form elements |
scroll |
Scrolling | window, scrollable elements |
resize |
Window size changes | window |
▶ Example: Combining Common Methods
JAVASCRIPT
// A typical data processing chain
const products = [
{ name: "Apple", price: 1.5, inStock: true },
{ name: "Bread", price: 3.0, inStock: false },
{ name: "Cheese", price: 5.5, inStock: true }
];
const availableNames = products
.filter(p => p.inStock)
.map(p => p.name)
.sort();
console.log(availableNames); // ["Apple", "Cheese"]
This shows how filter, map, and sort work together to transform an array of objects.
▶ Example
DOM manipulation: creating and removing elements:
JAVASCRIPT
const ul = document.createElement('ul');
['Apple', 'Banana', 'Cherry'].forEach(fruit => {
const li = document.createElement('li');
li.textContent = fruit;
ul.appendChild(li);
});
document.body.appendChild(ul);
ul.removeChild(ul.querySelector('li'));
console.log(ul.children.length);
▶ Example
Promise chaining with error handling:
JAVASCRIPT
function fetchData(url) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (url.startsWith('https')) {
resolve({ status: 200, data: 'OK' });
} else {
reject(new Error('Insecure URL'));
}
}, 100);
});
}
fetchData('https://api.example.com')
.then(res => console.log(res.data))
.catch(err => console.error(err.message));
❓ FAQ
Q Where can I find the official JavaScript reference?
A The official reference is on the MDN Web Docs — it covers every method, property, and edge case.
Q How do I keep this reference up to date?
A Bookmark MDN. JavaScript is evolving yearly; this page covers ES2020+ features. New methods like
Array.toSorted() (ES2023) may not appear here yet.Q Why is
== not recommended?A
== performs implicit type coercion (e.g., 0 == "0" is true). Use === for strict equality to avoid surprises.📖 Summary
- This reference covers core JavaScript statements, operators, and methods
- MDN is the authoritative source for edge cases and new features
- Prefer
===over==to avoid type coercion bugs - Array and string methods are stable but new ones appear yearly
📝 Exercises
- Pick 3 methods you don't recognize. Read their MDN docs. Write a one-line summary for each.
- Find one place in your code that uses
==and refactor it to===. Run the tests. - List 5 array methods that take a callback function. Describe the callback's signature.