Skip to content

JavaScript Notes

Mattscreative edited this page Mar 9, 2026 · 2 revisions

JavaScript Study Notes - Exam Preparation Guide

Quick reference for all JavaScript topics. Use for tests and quizzes!


Table of Contents

  1. Variables & Data Types
  2. Operators
  3. Control Flow
  4. Functions
  5. Arrays
  6. Objects
  7. Classes (ES6+)
  8. DOM Manipulation
  9. Async Programming
  10. Error Handling
  11. Regular Expressions
  12. Storage APIs
  13. Common Methods Quick Reference
  14. Syntax Rules Summary
  15. Common Errors

1. Variables & Data Types

Variable Declaration

var old = "old way";     // Function-scoped, hoisted
let block = "new way";   // Block-scoped
const constant = "cannot change"; // Block-scoped, immutable reference

Primitive Types

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)

Type Checking

typeof "hello"    // "string"
typeof 42         // "number"
typeof true       // "boolean"
typeof undefined  // "undefined"
typeof null       // "object" (BUG!)
typeof {}         // "object"
typeof []         // "object" (arrays are objects!)

Type Conversion

// 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

2. Operators

Arithmetic

+   -   *   /   %   // Basic
++  --                // Increment/decrement
+=  -=  *=  /=  %=    // Compound assignment
**                    // Exponentiation (ES2016)

Comparison

==   !=    // Loose equality (type coercion)
===  !==   // Strict equality (no coercion)

"5" == 5    // true
"5" === 5   // false

Logical

&&  // AND
||  // OR
!   // NOT

// Short-circuit
const name = userInput || "Guest";  // Default value

Nullish

// Nullish coalescing (ES2020)
value ?? "default"    // Only null/undefined

// Optional chaining (ES2020)
obj?.property?.nested

Spread & Rest

// Spread - expand
[...arr]        // Array spread
{...obj}        // Object spread

// Rest - collect
function sum(...numbers) { }  // Rest parameters
const [first, ...rest] = arr; // Destructuring rest

3. Control Flow

If-Else

if (condition) {
    // code
} else if (condition2) {
    // code
} else {
    // code
}

Ternary

const status = age >= 18 ? "Adult" : "Minor";

Switch

switch (value) {
    case 1:
        // code
        break;
    case 2:
        // code
        break;
    default:
        // code
}

Loops

// 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) => { });

Loop Control

  • break - Exit loop
  • continue - Skip iteration

4. Functions

Declaration

function greet(name) {
    return "Hello, " + name;
}

// Arrow function (ES6)
const greet = (name) => "Hello, " + name;
const greet = name => "Hello, " + name;  // One param, no parens

Parameters

// Default parameters
function greet(name = "Guest") { }

// Rest parameters
function sum(...numbers) {
    return numbers.reduce((a, b) => a + b, 0);
}

Callback

// 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);

Closure

function counter() {
    let count = 0;
    return function() {
        return ++count;
    };
}
const increment = counter();

5. Arrays

Creation

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]

Methods (Mutating)

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()       // Reverse

Methods (Non-Mutating)

arr.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 flatten

Destructuring

const [first, second, ...rest] = [1, 2, 3, 4, 5];
// first=1, second=2, rest=[3,4,5]

6. Objects

Creation

const obj = { name: "Alice", age: 25 };
const obj2 = new Object();
const obj3 = Object.create(null);

Access

obj.name      // Dot notation
obj["name"]   // Bracket notation

Methods

Object.keys(obj)      // ["name", "age"]
Object.values(obj)    // ["Alice", 25]
Object.entries(obj)   // [["name","Alice"],["age",25]]
Object.assign({}, obj)// Copy/merge

Destructuring

const { name, age } = obj;
const { name: userName } = obj;  // Rename
const { name, ...rest } = obj;   // Rest

Spread

const obj2 = { ...obj, city: "NYC" };

this Keyword

const obj = {
    name: "Alice",
    greet() {
        console.log(this.name);  // "Alice"
    },
    arrow: () => {
        console.log(this);  // Window/global (not obj!)
    }
};

7. Classes (ES6)

Declaration

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);
    }
}

Inheritance

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}`;
    }
}

Getters & Setters

class Person {
    #name;  // Private field (ES2022)
    
    get name() { return this.#name; }
    set name(value) { this.#name = value; }
}

8. DOM Manipulation

Selection

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")

Creation

const div = document.createElement("div");
div.className = "container";
div.textContent = "Hello";
document.body.appendChild(div);
element.remove()
element.replaceWith(newElement)

Styling

element.style.color = "red"
element.style.backgroundColor = "blue"
element.classList.add("active")
element.classList.remove("active")
element.classList.toggle("active")
element.classList.contains("active")

Events

element.addEventListener("click", (event) => { });
element.onclick = handler;

// Common events
// click, dblclick, mouseenter, mouseleave
// keydown, keyup
// submit, change, input
// load, DOMContentLoaded

9. Async Programming

Promises

const promise = new Promise((resolve, reject) => {
    // async operation
    if (success) resolve(result);
    else reject(error);
});

promise
    .then(result => { })
    .catch(error => { })
    .finally(() => { });

Async/Await

async function fetchData() {
    try {
        const response = await fetch(url);
        const data = await response.json();
        return data;
    } catch (error) {
        console.error(error);
    }
}

Promise Methods

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 API

fetch(url, {
    method: "GET",  // POST, PUT, DELETE
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(data)
})
    .then(res => res.json())
    .then(data => { })
    .catch(err => { });

10. Error Handling

Try-Catch

try {
    // Code that might fail
    riskyOperation();
} catch (error) {
    console.error(error.message);
} finally {
    // Always runs
}

Throw

throw new Error("Something went wrong");
throw new TypeError("Invalid type");

Custom Error

class MyError extends Error {
    constructor(message) {
        super(message);
        this.name = "MyError";
    }
}

Common Errors

  • ReferenceError - Variable doesn't exist
  • TypeError - Wrong type operation
  • SyntaxError - Invalid code
  • RangeError - Value out of range

11. Regular Expressions

Creation

const regex = /pattern/flags;
const regex2 = new RegExp("pattern", "flags");

Flags

g  - Global
i  - Case insensitive
m  - Multiline
s  - Dotall
u  - Unicode

Methods

"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

Common Patterns

/\d+/           // One or more digits
/\w+/           // Word characters
/\s+/           // Whitespace
/^[a-z]+$/      // Only letters
/\bword\b/      // Whole word
/^[a-zA-Z0-9]+$/ // Alphanumeric

12. Storage APIs

localStorage

localStorage.setItem("key", "value");
localStorage.getItem("key");
localStorage.removeItem("key");
localStorage.clear();
localStorage.setItem("obj", JSON.stringify(obj));
JSON.parse(localStorage.getItem("obj"));

sessionStorage

  • Same API as localStorage
  • Cleared when tab closes

IndexedDB

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
};

13. Common Methods Quick Reference

String Methods

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)

Array Methods

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 Methods

Object.keys(obj)
Object.values(obj)
Object.entries(obj)
Object.assign(target, source)
Object.freeze(obj)
Object.seal(obj)
Object.hasOwn(obj, prop)  // ES2022

14. Syntax Rules Summary

Variable Naming

  • Start with letter, underscore, or dollar sign
  • Can contain letters, numbers, underscores, dollar signs
  • Case sensitive
  • Cannot use reserved keywords

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

Code Structure

// No semicolons required (ASI)
// But recommended!

// IIFE (old way)
(function() { })();

// Module pattern
export function myFunc() { }
import { myFunc } from "./module";

Arrow Function Notes

  • No this binding
  • No arguments object
  • Cannot be used as methods with this
  • Return shorthand: x => x * 2

15. Common Errors

undefined vs null

// undefined - declared but not assigned
let x;
console.log(x);  // undefined

// null - explicitly assigned nothing
let y = null;
console.log(y);  // null

Array.isArray()

// typeof [] returns "object"
Array.isArray([])  // true

this Binding

// 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);

Async in Loop

// 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
}

Comparing Arrays

// 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

Quick Reference Card

Variable Keywords

  • var - Function-scoped, hoisted
  • let - Block-scoped
  • const - Block-scoped, immutable reference

Array Methods (Mutating)

  • push, pop, shift, unshift, splice, sort, reverse

Array Methods (Non-Mutating)

  • map, filter, reduce, find, slice, concat, includes

DOM Selection

  • getElementById, querySelector, querySelectorAll

Promise States

  • pending, fulfilled, rejected

ES6+ Features

  • Arrow functions
  • Classes
  • Destructuring
  • Spread/Rest
  • Template literals
  • Modules (import/export)
  • async/await

Exam Tips

  1. Know the difference - var vs let vs const
  2. Master arrays - map, filter, reduce are essential
  3. Understand this - Arrow functions don't bind this
  4. Promises vs async/await - Know both
  5. DOM methods - Querying and event handling
  6. Type coercion - == vs ===
  7. Falsy values - Know them all
  8. Closures - Understand scope
  9. Classes - Inheritance with extends
  10. Error handling - Try-catch-finally

Good luck on your exam! 🎯

Clone this wiki locally