Variables
var / let / const
// const — can't be reassigned (preferred)
const name = "Alice";
const PI = 3.14;
// let — block-scoped, can be reassigned
let score = 0;
score = 10;
// var — function-scoped (avoid)
var old = "legacy";
// Multiple assignment
let a = 1, b = 2, c = 3;
// Destructuring
const [x, y] = [10, 20];
const { first, last } = { first: "John", last: "Doe" };
Data Types
Primitives
typeof "hello" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" (quirk)
typeof Symbol() // "symbol"
typeof 42n // "bigint"
// Type conversion
Number("42") // 42
String(42) // "42"
Boolean(0) // false
parseInt("10px") // 10
parseFloat("3.14") // 3.14
Strings
const str = "Hello World";
str.length // 11
str.toUpperCase() // "HELLO WORLD"
str.toLowerCase() // "hello world"
str.trim() // remove whitespace
str.includes("World")// true
str.startsWith("He") // true
str.endsWith("ld") // true
str.indexOf("o") // 4
str.slice(0, 5) // "Hello"
str.replace("World","JS") // "Hello JS"
str.split(" ") // ["Hello","World"]
// Template literal
const name = "Alice";
const msg = `Hello, ${name}! 2+2=${2+2}`;
Operators
Comparison & Logical
// Comparison
5 === 5 // true (strict equality)
5 == "5" // true (loose equality — avoid)
5 !== 3 // true
5 > 3; 5 >= 5; 5 < 10; 5 <= 5
// Logical
true && false // false (AND)
true || false // true (OR)
!true // false (NOT)
// Nullish coalescing
const val = null ?? "default"; // "default"
// Optional chaining
user?.address?.city // undefined (no error)
// Ternary
const result = score > 50 ? "pass" : "fail";
Control Flow
if / switch
if (score >= 90) {
console.log("A");
} else if (score >= 70) {
console.log("B");
} else {
console.log("F");
}
switch (day) {
case "Mon": console.log("Monday"); break;
case "Fri": console.log("Friday"); break;
default: console.log("Other");
}
Loops
// for
for (let i = 0; i < 5; i++) {
console.log(i);
}
// while
let i = 0;
while (i < 5) { console.log(i); i++; }
// for...of (arrays)
for (const item of items) {
console.log(item);
}
// for...in (objects)
for (const key in obj) {
console.log(key, obj[key]);
}
// break / continue
for (let i = 0; i < 10; i++) {
if (i === 5) break;
if (i % 2 === 0) continue;
console.log(i);
}
Functions
Function Types
// Declaration (hoisted)
function greet(name) {
return `Hello, ${name}!`;
}
// Expression
const greet = function(name) {
return `Hello, ${name}!`;
};
// Arrow function
const greet = (name) => `Hello, ${name}!`;
const add = (a, b) => a + b;
const square = n => n * n;
// Default params
function add(a, b = 0) { return a + b; }
// Rest params
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
Arrays
Array Methods
const arr = [1, 2, 3, 4, 5];
arr.push(6) // add to end
arr.pop() // remove from end
arr.unshift(0) // add to beginning
arr.shift() // remove from beginning
arr.length // 5
arr.includes(3) // true
arr.indexOf(3) // 2
arr.slice(1, 3) // [2, 3] (non-destructive)
arr.splice(1, 2) // removes 2 items at index 1
arr.map(x => x * 2) // [2,4,6,8,10]
arr.filter(x => x > 2) // [3,4,5]
arr.reduce((a, b) => a+b, 0) // 15
arr.find(x => x > 3) // 4
arr.findIndex(x => x > 3) // 3
arr.some(x => x > 4) // true
arr.every(x => x > 0) // true
arr.sort((a, b) => a - b) // [1,2,3,4,5]
arr.flat() // flatten nested
[...arr1, ...arr2] // spread / merge
Objects
Object Basics
const person = {
name: "Alice",
age: 25,
greet() { return `Hi, I'm ${this.name}`; }
};
person.name // "Alice"
person["age"] // 25
person.city = "NYC" // add property
delete person.age // delete property
"name" in person // true
Object.keys(person) // ["name","age","greet"]
Object.values(person) // ["Alice",25,fn]
Object.entries(person)// [["name","Alice"],...]
// Spread / copy
const copy = { ...person };
const merged = { ...obj1, ...obj2 };
// Destructuring
const { name, age } = person;
const { name: n, age: a = 0 } = person;
DOM Manipulation
Selecting Elements
// Single element
document.getElementById("myId")
document.querySelector(".class")
document.querySelector("#id")
document.querySelector("div > p")
// Multiple elements
document.querySelectorAll(".card")
document.getElementsByClassName("class")
document.getElementsByTagName("p")
// Traversal
el.parentElement
el.children
el.firstElementChild
el.nextElementSibling
Modifying DOM
el.textContent = "New text";
el.innerHTML = "<strong>Bold</strong>";
el.style.color = "red";
el.style.display = "none";
// Classes
el.classList.add("active");
el.classList.remove("active");
el.classList.toggle("dark");
el.classList.contains("active"); // true/false
// Attributes
el.setAttribute("href", "#");
el.getAttribute("href");
el.removeAttribute("disabled");
// Create & insert
const div = document.createElement("div");
div.textContent = "Hello";
parent.appendChild(div);
parent.insertBefore(div, ref);
el.remove();
Events
Event Listeners
// Add event
el.addEventListener("click", function(e) {
console.log(e.target);
});
// Arrow function
btn.addEventListener("click", (e) => {
e.preventDefault();
e.stopPropagation();
});
// Remove event
const handler = () => console.log("clicked");
el.addEventListener("click", handler);
el.removeEventListener("click", handler);
// Common events
"click" | "dblclick" | "mouseover" | "mouseout"
"keydown" | "keyup" | "keypress"
"input" | "change" | "submit" | "focus" | "blur"
"load" | "DOMContentLoaded" | "resize" | "scroll"
Async / Fetch
Promises & Async/Await
// Promise
const p = new Promise((resolve, reject) => {
setTimeout(() => resolve("done"), 1000);
});
p.then(val => console.log(val))
.catch(err => console.error(err));
// Async / Await
async function getData() {
try {
const res = await fetch("https://api.example.com/data");
const json = await res.json();
return json;
} catch (err) {
console.error(err);
}
}
// Fetch POST
const res = await fetch("/api", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Alice" })
});
ES6+ Features
Modern Syntax
// Classes
class Animal {
constructor(name) { this.name = name; }
speak() { return `${this.name} makes a noise.`; }
}
class Dog extends Animal {
speak() { return `${this.name} barks.`; }
}
// Modules
export const PI = 3.14;
export default function main() {}
import { PI } from './math.js';
import main from './main.js';
// Map & Set
const map = new Map();
map.set("key", "value");
map.get("key");
const set = new Set([1, 2, 2, 3]); // {1,2,3}
set.add(4); set.has(2); // true