-
-
Notifications
You must be signed in to change notification settings - Fork 2
JavaScript Notes
Mattscreative edited this page Mar 9, 2026
·
2 revisions
Quick reference for all JavaScript topics. Use for tests and quizzes!
- Variables & Data Types
- Operators
- Control Flow
- Functions
- Arrays
- Objects
- Classes (ES6+)
- DOM Manipulation
- Async Programming
- Error Handling
- Regular Expressions
- Storage APIs
- Common Methods Quick Reference
- Syntax Rules Summary
- Common Errors
var old = "old way"; // Function-scoped, hoisted
let block = "new way"; // Block-scoped
const constant = "cannot change"; // Block-scoped, immutable reference| Type | Example |
|---|---|
string |
"Hello" |
number |
42, 3.14
|
boolean |
true, false
|
undefined |
let x; |
null |
let x = null; |
symbol (ES6) |
Symbol("id") |
bigint (ES2020) |
BigInt(9007199254740991) |
typeof "hello" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" (BUG!)
typeof {} // "object"
typeof [] // "object" (arrays are objects!)// To string
String(42) // "42"
(42).toString() // "42"
42 + "" // "42"
// To number
Number("42") // 42
parseInt("42") // 42
parseFloat("3.14")// 3.14
+"42" // 42 (unary plus)
// To boolean
Boolean(1) // true
!!value // double NOT
// Falsy values (convert to false)
// false, 0, "", null, undefined, NaN+ - * / % // Basic
++ -- // Increment/decrement
+= -= *= /= %= // Compound assignment
** // Exponentiation (ES2016)== != // Loose equality (type coercion)
=== !== // Strict equality (no coercion)
"5" == 5 // true
"5" === 5 // false&& // AND
|| // OR
! // NOT
// Short-circuit
const name = userInput || "Guest"; // Default value// Nullish coalescing (ES2020)
value ?? "default" // Only null/undefined
// Optional chaining (ES2020)
obj?.property?.nested// Spread - expand
[...arr] // Array spread
{...obj} // Object spread
// Rest - collect
function sum(...numbers) { } // Rest parameters
const [first, ...rest] = arr; // Destructuring restif (condition) {
// code
} else if (condition2) {
// code
} else {
// code
}const status = age >= 18 ? "Adult" : "Minor";switch (value) {
case 1:
// code
break;
case 2:
// code
break;
default:
// code
}// For
for (let i = 0; i < 10; i++) { }
// For...of (ES6) - arrays, strings
for (const item of array) { }
// For...in (ES6) - objects
for (const key in object) { }
// While
while (condition) { }
// Do-while
do {
// runs at least once
} while (condition);
// forEach
array.forEach((item, index) => { });-
break- Exit loop -
continue- Skip iteration
function greet(name) {
return "Hello, " + name;
}
// Arrow function (ES6)
const greet = (name) => "Hello, " + name;
const greet = name => "Hello, " + name; // One param, no parens// Default parameters
function greet(name = "Guest") { }
// Rest parameters
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}// Common higher-order functions
array.map(item => item * 2);
array.filter(item => item > 5);
array.reduce((acc, item) => acc + item, 0);
array.find(item => item.id === 1);
array.some(item => item > 5);
array.every(item => item > 0);function counter() {
let count = 0;
return function() {
return ++count;
};
}
const increment = counter();const arr = [1, 2, 3];
const arr2 = new Array(5); // Empty array of length 5
const arr3 = Array.from("hello"); // ["h","e","l","l","o"]
const arr4 = Array.of(1, 2, 3); // [1,2,3]arr.push(item) // Add to end
arr.pop() // Remove from end
arr.unshift(item) // Add to start
arr.shift() // Remove from start
arr.splice(index, count) // Remove/add
arr.sort((a, b) => a - b) // Sort
arr.reverse() // Reversearr.map(fn) // Transform
arr.filter(fn) // Filter
arr.reduce(fn, init) // Reduce
arr.slice(start, end) // Copy portion
arr.concat(arr2) // Join
arr.includes(item) // Check existence
arr.indexOf(item) // Find index
arr.find(fn) // Find first match
arr.findIndex(fn) // Find index
arr.flat() // Flatten array
arr.flatMap(fn) // Map then flattenconst [first, second, ...rest] = [1, 2, 3, 4, 5];
// first=1, second=2, rest=[3,4,5]const obj = { name: "Alice", age: 25 };
const obj2 = new Object();
const obj3 = Object.create(null);obj.name // Dot notation
obj["name"] // Bracket notationObject.keys(obj) // ["name", "age"]
Object.values(obj) // ["Alice", 25]
Object.entries(obj) // [["name","Alice"],["age",25]]
Object.assign({}, obj)// Copy/mergeconst { name, age } = obj;
const { name: userName } = obj; // Rename
const { name, ...rest } = obj; // Restconst obj2 = { ...obj, city: "NYC" };const obj = {
name: "Alice",
greet() {
console.log(this.name); // "Alice"
},
arrow: () => {
console.log(this); // Window/global (not obj!)
}
};class Person {
// Constructor
constructor(name, age) {
this.name = name;
this.age = age;
}
// Method
greet() {
return `Hello, ${this.name}`;
}
// Getter
get info() {
return `${this.name}, ${this.age}`;
}
// Static method
static create(name, age) {
return new Person(name, age);
}
}class Student extends Person {
constructor(name, age, grade) {
super(name, age); // Call parent constructor
this.grade = grade;
}
// Override
greet() {
return `Hi, I'm ${this.name}`;
}
}class Person {
#name; // Private field (ES2022)
get name() { return this.#name; }
set name(value) { this.#name = value; }
}document.getElementById("id")
document.querySelector(".class")
document.querySelectorAll("div")
element.innerHTML = "<p>Content</p>"
element.textContent = "Text only"
element.getAttribute("class")
element.setAttribute("class", "active")const div = document.createElement("div");
div.className = "container";
div.textContent = "Hello";
document.body.appendChild(div);
element.remove()
element.replaceWith(newElement)element.style.color = "red"
element.style.backgroundColor = "blue"
element.classList.add("active")
element.classList.remove("active")
element.classList.toggle("active")
element.classList.contains("active")element.addEventListener("click", (event) => { });
element.onclick = handler;
// Common events
// click, dblclick, mouseenter, mouseleave
// keydown, keyup
// submit, change, input
// load, DOMContentLoadedconst promise = new Promise((resolve, reject) => {
// async operation
if (success) resolve(result);
else reject(error);
});
promise
.then(result => { })
.catch(error => { })
.finally(() => { });async function fetchData() {
try {
const response = await fetch(url);
const data = await response.json();
return data;
} catch (error) {
console.error(error);
}
}Promise.all([p1, p2, p3]) // All resolve
Promise.race([p1, p2, p3]) // First to settle
Promise.allSettled([p1,p2,p3]) // All settled (ES2020)
Promise.any([p1,p2,p3]) // First to fulfill (ES2021)fetch(url, {
method: "GET", // POST, PUT, DELETE
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
})
.then(res => res.json())
.then(data => { })
.catch(err => { });try {
// Code that might fail
riskyOperation();
} catch (error) {
console.error(error.message);
} finally {
// Always runs
}throw new Error("Something went wrong");
throw new TypeError("Invalid type");class MyError extends Error {
constructor(message) {
super(message);
this.name = "MyError";
}
}-
ReferenceError- Variable doesn't exist -
TypeError- Wrong type operation -
SyntaxError- Invalid code -
RangeError- Value out of range
const regex = /pattern/flags;
const regex2 = new RegExp("pattern", "flags");g - Global
i - Case insensitive
m - Multiline
s - Dotall
u - Unicode
"string".match(/pattern/g) // Find matches
"string".replace(/old/, "new") // Replace
"string".split(/pattern/) // Split
regex.test("string") // Test match
regex.exec("string") // Get match info/\d+/ // One or more digits
/\w+/ // Word characters
/\s+/ // Whitespace
/^[a-z]+$/ // Only letters
/\bword\b/ // Whole word
/^[a-zA-Z0-9]+$/ // AlphanumericlocalStorage.setItem("key", "value");
localStorage.getItem("key");
localStorage.removeItem("key");
localStorage.clear();
localStorage.setItem("obj", JSON.stringify(obj));
JSON.parse(localStorage.getItem("obj"));- Same API as localStorage
- Cleared when tab closes
const request = indexedDB.open("DBName", version);
request.onupgradeneeded = (event) => {
const db = event.target.result;
db.createObjectStore("store", { keyPath: "id" });
};
request.onsuccess = (event) => {
const db = event.target.result;
// Use db
};str.length
str.charAt(index)
str.substring(start, end)
str.slice(start, end)
str.toUpperCase()
str.toLowerCase()
str.trim()
str.split(separator)
str.includes(substr)
str.startsWith(substr)
str.endsWith(substr)
str.replace(old, new)
str.match(regex)
str.indexOf(substr)
str.concat(other)arr.length
arr.push(item)
arr.pop()
arr.shift()
arr.unshift(item)
arr.splice(start, deleteCount, items)
arr.slice(start, end)
arr.map(fn)
arr.filter(fn)
arr.reduce(fn, init)
arr.find(fn)
arr.findIndex(fn)
arr.includes(item)
arr.indexOf(item)
arr.sort(fn)
arr.reverse()
arr.forEach(fn)
arr.flat()Object.keys(obj)
Object.values(obj)
Object.entries(obj)
Object.assign(target, source)
Object.freeze(obj)
Object.seal(obj)
Object.hasOwn(obj, prop) // ES2022- Start with letter, underscore, or dollar sign
- Can contain letters, numbers, underscores, dollar signs
- Case sensitive
- Cannot use reserved keywords
break, case, catch, continue, debugger, default, delete,
do, else, enum, export, extends, false, finally, for,
function, if, import, in, instanceof, new, null, return,
super, switch, this, throw, true, try, typeof, var, void,
while, with, yield, class, const, let, static, of
// No semicolons required (ASI)
// But recommended!
// IIFE (old way)
(function() { })();
// Module pattern
export function myFunc() { }
import { myFunc } from "./module";- No
thisbinding - No
argumentsobject - Cannot be used as methods with
this - Return shorthand:
x => x * 2
// undefined - declared but not assigned
let x;
console.log(x); // undefined
// null - explicitly assigned nothing
let y = null;
console.log(y); // null// typeof [] returns "object"
Array.isArray([]) // true// Problem: this in callback
const obj = {
name: "Alice",
greet() {
setTimeout(function() {
console.log(this.name); // undefined!
}, 1000);
}
};
// Solutions:
// 1. Arrow function
setTimeout(() => console.log(this.name), 1000);
// 2. Bind
setTimeout(function() { console.log(this.name); }.bind(this), 1000);
// 3. Save this
const self = this;
setTimeout(function() { console.log(self.name); }, 1000);// Problem
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // Prints 3,3,3
}
// Solution - use let
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // Prints 0,1,2
}// Wrong
[1,2] === [1,2] // false!
// Correct
JSON.stringify([1,2]) === JSON.stringify([1,2]) // true
[1,2].every((val, i) => val === [1,2][i]) // true-
var- Function-scoped, hoisted -
let- Block-scoped -
const- Block-scoped, immutable reference
- push, pop, shift, unshift, splice, sort, reverse
- map, filter, reduce, find, slice, concat, includes
- getElementById, querySelector, querySelectorAll
- pending, fulfilled, rejected
- Arrow functions
- Classes
- Destructuring
- Spread/Rest
- Template literals
- Modules (import/export)
- async/await
- Know the difference - var vs let vs const
- Master arrays - map, filter, reduce are essential
- Understand this - Arrow functions don't bind this
- Promises vs async/await - Know both
- DOM methods - Querying and event handling
- Type coercion - == vs ===
- Falsy values - Know them all
- Closures - Understand scope
- Classes - Inheritance with extends
- Error handling - Try-catch-finally
Good luck on your exam! 🎯