A quick-reference instruction sheet covering the fundamentals of JavaScript programming.
JavaScript is a lightweight, interpreted programming language that runs in the browser (and on servers via Node.js). It is the language of the web — used to make pages interactive.
<script> tags or loaded from .js files; (optional, but recommended)// or /* ... */myVar and myvar are different// Inline in HTML
<script>
console.log("Hello, World!");
</script>
// External file
<script src="app.js"></script>
Use const by default, let when the value needs to change, and avoid var.
const name = "Alice"; // String — cannot be reassigned
let age = 30; // Number — can be reassigned
let price = 9.99; // Number (JS has one number type)
const active = true; // Boolean
let nothing = null; // Null (intentional absence)
let undef; // undefined (declared, not assigned)
console.log(typeof name); // "string"
console.log(typeof age); // "number"
console.log(typeof active); // "boolean"
| Type | Example | Description |
|---|---|---|
string | "hello" | Text |
number | 42, 3.14 | All numbers (int and float) |
boolean | true / false | Boolean values |
null | null | Intentional empty value |
undefined | undefined | Variable declared but not set |
object | { key: val } | Key-value pairs |
array | [1, 2, 3] | Ordered list (technically an object) |
const a = 10, b = 3;
a + b; // 13 — addition
a - b; // 7 — subtraction
a * b; // 30 — multiplication
a / b; // 3.333… — division
a % b; // 1 — modulus (remainder)
a ** b; // 1000 — exponentiation
x === y // Strict equal (value AND type) ✓ always use this
x !== y // Strict not equal
x == y // Loose equal (type coercion — avoid)
x < y // Less than
x > y // Greater than
x <= y // Less than or equal
x >= y // Greater than or equal
=== instead of ==. Loose equality causes surprising results: "5" == 5 is true, but "5" === 5 is false.a && b // AND
a || b // OR
!a // NOT
a ?? b // Nullish coalescing — use b if a is null/undefined
const first = "Alice";
const last = "Smith";
// Concatenation
first + " " + last; // "Alice Smith"
// Template literals (backticks) — preferred
`Hello, ${first}!`; // "Hello, Alice!"
`${first} is ${2026 - 1996} years old.`;
// Common string methods
"hello".length; // 5
"hello".toUpperCase(); // "HELLO"
"hello".toLowerCase(); // "hello"
" hello ".trim(); // "hello"
"hello".includes("ell"); // true
"hello".startsWith("he"); // true
"hello".indexOf("l"); // 2
"hello".slice(1, 4); // "ell"
"hello".replace("l", "r"); // "herlo"
"a,b,c".split(","); // ["a","b","c"]
["a","b"].join("-"); // "a-b"
const fruits = ["apple", "banana", "cherry"];
fruits[0]; // "apple"
fruits.length; // 3
fruits.push("date"); // append — ["apple","banana","cherry","date"]
fruits.pop(); // remove last — returns "date"
fruits.unshift("avocado"); // prepend
fruits.shift(); // remove first
fruits.includes("banana"); // true
fruits.indexOf("cherry"); // 2
fruits.reverse(); // reverses in place
fruits.slice(1, 3); // copy of elements [1] to [2]
fruits.join(" | "); // "apple | banana | cherry"
const nums = [1, 2, 3, 4, 5];
// map — transform each element, returns new array
nums.map(n => n * 2); // [2,4,6,8,10]
// filter — keep elements that pass a test
nums.filter(n => n > 2); // [3,4,5]
// reduce — accumulate to a single value
nums.reduce((sum, n) => sum + n, 0); // 15
// find — first matching element
nums.find(n => n > 3); // 4
// some / every
nums.some(n => n > 4); // true (at least one)
nums.every(n => n > 0); // true (all pass)
const person = {
name: "Alice",
age: 30,
city: "NYC",
};
// Access
person.name; // "Alice" (dot notation)
person["age"]; // 30 (bracket notation)
// Add / update / delete
person.email = "a@b.com"; // add
person.age = 31; // update
delete person.city; // remove key
// Destructuring
const { name, age } = person; // name = "Alice", age = 31
// Spread operator
const updated = { ...person, age: 32 }; // copy with override
// Keys and values
Object.keys(person); // ["name","age","email"]
Object.values(person); // ["Alice",31,"a@b.com"]
Object.entries(person); // [["name","Alice"],["age",31],…]
const score = 75;
if (score >= 90) {
console.log("A");
} else if (score >= 75) {
console.log("B");
} else if (score >= 60) {
console.log("C");
} else {
console.log("F");
}
const day = "Mon";
switch (day) {
case "Mon":
console.log("Monday");
break;
case "Fri":
console.log("Friday");
break;
default:
console.log("Other day");
}
// Ternary
const status = age >= 18 ? "adult" : "minor";
// Nullish coalescing — default if null or undefined
const username = inputName ?? "Guest";
// Optional chaining — safe property access
const city = user?.address?.city; // undefined instead of error
for (let i = 0; i < 5; i++) {
console.log(i);
}
// 0 1 2 3 4
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
console.log(fruit);
}
const person = { name: "Alice", age: 30 };
for (const key in person) {
console.log(`${key}: ${person[key]}`);
}
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
break to exit a loop early, and continue to skip to the next iteration.function greet(name) {
return `Hello, ${name}!`;
}
greet("Alice"); // "Hello, Alice!"
// Single expression — implicit return
const double = n => n * 2;
double(5); // 10
// Multiple params
const add = (a, b) => a + b;
add(3, 4); // 7
// Block body — explicit return needed
const greet = (name) => {
const msg = `Hello, ${name}!`;
return msg;
};
// Default parameter
function greet(name = "World") {
return `Hello, ${name}!`;
}
greet(); // "Hello, World!"
// Rest parameter — collects remaining args into array
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3, 4); // 10
The DOM (Document Object Model) is the browser's representation of the HTML page. JavaScript can read and modify it.
// Single element
document.getElementById("myId");
document.querySelector(".my-class"); // first match
document.querySelector("h1");
// Multiple elements (returns NodeList)
document.querySelectorAll(".card"); // all matches
const el = document.querySelector("#title");
el.textContent; // get text
el.textContent = "New Title"; // set text
el.innerHTML = "<b>Bold</b>"; // set HTML (use carefully)
el.style.color = "red"; // inline style
el.classList.add("active"); // add class
el.classList.remove("active"); // remove class
el.classList.toggle("active"); // toggle class
el.getAttribute("href"); // read attribute
el.setAttribute("href", "/"); // set attribute
const p = document.createElement("p");
p.textContent = "New paragraph";
document.body.appendChild(p); // add to end of body
p.remove(); // remove from DOM
const btn = document.querySelector("#myBtn");
// Add event listener
btn.addEventListener("click", (event) => {
console.log("Button clicked!");
console.log(event.target); // the element that was clicked
});
// Common event types
// "click" — mouse click
// "dblclick" — double click
// "mouseover" — hover
// "keydown" — key pressed
// "keyup" — key released
// "submit" — form submitted
// "input" — input value changed
// "DOMContentLoaded" — page loaded
// Prevent default behaviour (e.g. form submission)
document.querySelector("form").addEventListener("submit", (e) => {
e.preventDefault();
console.log("Form intercepted");
});
JavaScript is single-threaded. Async patterns let you handle slow operations (network, timers) without blocking the page.
// Run once after 2 seconds
setTimeout(() => {
console.log("2 seconds later");
}, 2000);
// Run every second (returns an ID to cancel it)
const id = setInterval(() => {
console.log("tick");
}, 1000);
clearInterval(id); // stop it
const promise = new Promise((resolve, reject) => {
const success = true;
if (success) resolve("Done!");
else reject("Failed!");
});
promise
.then(result => console.log(result)) // "Done!"
.catch(err => console.error(err)); // "Failed!"
// fetch() returns a Promise — async/await makes it read like sync code
async function getUser() {
try {
const response = await fetch("https://api.example.com/user/1");
const data = await response.json();
console.log(data.name);
} catch (error) {
console.error("Error:", error);
}
}
getUser();
await calls in a try/catch block to handle network errors gracefully.