[Go to site: main page, start]

0% found this document useful (0 votes)
5 views27 pages

JavaScript 1week Refresher Guide

The JavaScript 1-Week Refresher Guide is designed for experienced developers to quickly refresh their knowledge before transitioning to React 19. It covers core concepts over seven days, including foundations, functions, objects, asynchronous programming, modern ES6 features, DOM manipulation, and preparation for React. Each day includes key topics, code examples, and a practice checklist to reinforce learning.

Uploaded by

massablaisetamfu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views27 pages

JavaScript 1week Refresher Guide

The JavaScript 1-Week Refresher Guide is designed for experienced developers to quickly refresh their knowledge before transitioning to React 19. It covers core concepts over seven days, including foundations, functions, objects, asynchronous programming, modern ES6 features, DOM manipulation, and preparation for React. Each day includes key topics, code examples, and a practice checklist to reinforce learning.

Uploaded by

massablaisetamfu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JavaScript

1-WEEK REFRESHER GUIDE

From Foundations to React 19 Readiness

Designed for developers who know JS and want to


sharpen their memory before diving into React 19.

7 Days Core Concepts Modern ES6+ React-Ready


■ How to Use This Guide
This guide is structured as a 7-day sprint designed for experienced JavaScript developers who want a fast,
targeted memory refresh — not a beginner tutorial. Each day covers a themed cluster of concepts,
includes concise code examples, key reminders, and ends with a practice checklist.

Day Theme Key Topics

1 Foundations & Scope Variables, types, coercion, scope, hoisting, strict mode

2 Functions & Closures Arrow fns, closures, IIFE, currying, higher-order fns

3 Objects & Prototypes Objects, prototypes, classes, inheritance, this, OOP patterns

4 Async JavaScript Event loop, callbacks, Promises, async/await, error handling

5 Modern ES6–ES2024 Destructuring, spread, iterators, generators, modules, WeakMap

6 The DOM & Events DOM manipulation, event delegation, forms, storage, fetch

7 Patterns & React Prep Design patterns, functional JS, performance, React 19 bridge

■ Tip: Spend ~2–3 hours per day. Read, type out the code examples yourself, then check off the daily
checklist. Don't copy-paste — muscle memory matters.

■ Note: All examples use modern JavaScript (ES2020+). Code is formatted for readability — minor
whitespace changes are fine in your own practice.

Prep → React 19 JavaScript 1-Week Refresher Guide • Page 2 © 2026


DAY Variables • Types • Coercion •
1 Foundations & Scope Hoisting

1.1 Variables: var, let, const


The three declaration keywords differ in scope, hoisting, and mutability. Modern JS prefers const by
default and let when reassignment is needed. Avoid var in new code.
// var — function-scoped, hoisted as undefined
var x = 1;
function demo() {
[Link](x); // undefined (hoisted, not initialized)
var x = 10;
}

// let — block-scoped, NOT hoisted to usable value


let count = 0;
count = 1; // OK

// const — block-scoped, binding cannot be reassigned


const PI = 3.14159;
const user = { name: "Ada" };
[Link] = "Grace"; // OK — object contents are mutable
// user = {}; // TypeError — reassignment forbidden

■■ Watch out: var declarations inside blocks (if, for) leak into the enclosing function. This is a classic bug
source. Always use let/const.

1.2 JavaScript Types


JavaScript has 8 data types: 7 primitives + Object. Primitives are immutable and compared by value;
objects are compared by reference.

Type typeof Example values

undefined "undefined" uninitialized variables

null "object" null ← intentional quirk!

boolean "boolean" true, false

number "number" 42, 3.14, NaN, Infinity

bigint "bigint" 9007199254740993n

string "string" "hello", `template`

symbol "symbol" Symbol('id')

object "object" {}, [], new Date()

1.3 Type Coercion & Equality

Prep → React 19 JavaScript 1-Week Refresher Guide • Page 3 © 2026


JavaScript coerces types automatically in many situations. Understanding when and how helps you avoid
subtle bugs.
// == (loose equality) — triggers coercion
0 == false // true
"" == false // true
null == undefined // true
null == 0 // false ← surprising!

// === (strict equality) — no coercion, always prefer this


0 === false // false
"5" === 5 // false

// Falsy values — all coerce to false in boolean context


// false, 0, -0, 0n, "", '', ``, null, undefined, NaN

// Truthy — everything else, including:


Boolean([]) // true
Boolean({}) // true
Boolean("0") // true ← a non-empty string!

// Safe type checks


typeof value === "string"
[Link](value)
value === null
value instanceof Date

■■ Watch out: Never use == for comparisons. Use === always. The only exception some allow is null ==
undefined to check for both at once.

1.4 Scope & Hoisting


// Lexical (static) scope — determined at write time
const globalVar = "global";
function outer() {
const outerVar = "outer";
function inner() {
const innerVar = "inner";
[Link](globalVar, outerVar, innerVar); // all accessible
}
// [Link](innerVar); // ReferenceError
}

// Temporal Dead Zone (TDZ) — let/const before declaration


{
// [Link](myLet); // ReferenceError — TDZ
let myLet = "hello";
[Link](myLet); // "hello"
}

// Function hoisting (the whole function is hoisted)


greet(); // works!
function greet() { [Link]("Hello"); }

// Expression is NOT hoisted fully


// greet2(); // TypeError

Prep → React 19 JavaScript 1-Week Refresher Guide • Page 4 © 2026


const greet2 = () => [Link]("Hi");

■ Tip: Think of TDZ as 'the variable exists but you cannot touch it yet'. It prevents the class of bugs that var
hoisting caused.

■ Day 1 Practice Checklist


■ Explain var vs let vs const from memory ■ Describe hoisting for var, let, function

■ List all 8 JS types without looking ■ Explain the Temporal Dead Zone

■ Explain why typeof null === 'object' ■ Write a scope chain example 3 levels deep

■ Write 5 examples of falsy values ■ Convert a var-heavy snippet to let/const

Prep → React 19 JavaScript 1-Week Refresher Guide • Page 5 © 2026


DAY Arrow Fns • Closures • HOFs •
2 Functions & Closures Currying

2.1 Function Types & Arrow Functions


// Function declaration
function add(a, b) { return a + b; }

// Function expression
const multiply = function(a, b) { return a * b; };

// Arrow function — concise, lexical 'this'


const square = (n) => n * n;
const greet = name => `Hello, ${name}!`;
const noop = () => {};
const getPair = (a, b) => ({ key: a, val: b }); // wrap object in ()

// Key difference: arrow fns have NO own 'this', 'arguments', or 'new'


function Timer() {
[Link] = 0;
// WRONG: setInterval(function() { [Link]++ }, 1000) — 'this' is undefined/windo
w
setInterval(() => { [Link]++; }, 1000); // 'this' inherited from Timer
}

// Default parameters
function connect(host = "localhost", port = 3000) {
return `${host}:${port}`;
}

// Rest parameters
function sum(...nums) {
return [Link]((acc, n) => acc + n, 0);
}
sum(1, 2, 3, 4); // 10

2.2 Closures
A closure is a function that remembers the variables from its outer scope even after that scope has
finished executing. This is one of JS's most powerful (and most-asked-about) features.
// Basic closure
function makeCounter(start = 0) {
let count = start;
return {
increment() { return ++count; },
decrement() { return --count; },
value() { return count; }
};
}
const c = makeCounter(10);
[Link](); // 11
[Link](); // 12

Prep → React 19 JavaScript 1-Week Refresher Guide • Page 6 © 2026


[Link](); // 12

// Classic loop closure bug & fix


// BUG — all click handlers share the same 'i'
for (var i = 0; i < 3; i++) {
setTimeout(() => [Link](i), 100); // prints 3, 3, 3
}

// FIX 1 — use let (block scope creates new binding each iteration)
for (let i = 0; i < 3; i++) {
setTimeout(() => [Link](i), 100); // 0, 1, 2
}

// FIX 2 — IIFE to capture value


for (var i = 0; i < 3; i++) {
((j) => setTimeout(() => [Link](j), 100))(i); // 0, 1, 2
}

// Memoization via closure


function memoize(fn) {
const cache = new Map();
return function(...args) {
const key = [Link](args);
if ([Link](key)) return [Link](key);
const result = [Link](this, args);
[Link](key, result);
return result;
};
}

■ Tip: Closures are the mechanism behind React hooks! useState stores state in a closure that React
manages. Understanding closures deeply will make hooks intuitive.

2.3 Higher-Order Functions


// Functions that take or return functions
const double = x => x * 2;
const isEven = x => x % 2 === 0;

[1,2,3,4,5].filter(isEven).map(double); // [4, 8]

// reduce — the Swiss Army knife


const sum = arr => [Link]((acc, n) => acc + n, 0);
const flatten= arr => [Link]((acc, v) => [Link](v), []);
const groupBy = (arr, fn) => [Link]((acc, item) => {
const key = fn(item);
(acc[key] = acc[key] || []).push(item);
return acc;
}, {});

// Currying — transform f(a,b,c) into f(a)(b)(c)


const curry = fn => {
const arity = [Link];
return function curried(...args) {
return [Link] >= arity

Prep → React 19 JavaScript 1-Week Refresher Guide • Page 7 © 2026


? fn(...args)
: (...more) => curried(...args, ...more);
};
};

const add3 = curry((a, b, c) => a + b + c);


add3(1)(2)(3); // 6
add3(1, 2)(3); // 6
const add10 = add3(10); // partial application
add10(5)(3); // 18

2.4 The 'this' Keyword


// 'this' depends on HOW a function is called, not where it's defined
// 1. Method call — 'this' is the object
const obj = { name: "JS", greet() { return [Link]; } };
[Link](); // "JS"

// 2. Plain call — 'this' is undefined (strict) or global


function who() { return this; }
who(); // undefined in strict mode

// 3. Explicit binding
function say(greeting) { return `${greeting}, ${[Link]}`; }
[Link]({ name: "Ada" }, "Hello"); // "Hello, Ada"
[Link]({ name: "Ada" }, ["Hi"]); // "Hi, Ada"
const boundSay = [Link]({ name: "Grace" });
boundSay("Hey"); // "Hey, Grace"

// 4. Constructor call — 'this' is the new instance


function Person(name) { [Link] = name; }
const p = new Person("Alan"); // [Link] === "Alan"

// 5. Arrow — inherits 'this' from enclosing scope (no own 'this')

■ Day 2 Practice Checklist


■ Write a counter factory using closures ■ Demonstrate all 5 ways 'this' is set

■ Fix the classic for-loop closure bug ■ Build a pipeline() fn composing 3 functions

■ Implement memoize() from scratch ■ Use map, filter, reduce on a real dataset

■ Write curry() and test partial application ■ Explain why arrow fns can't be constructors

Prep → React 19 JavaScript 1-Week Refresher Guide • Page 8 © 2026


DAY OOP • Classes • Prototype Chain •
3 Objects & Prototypes this

3.1 Object Fundamentals


// Object literal
const person = {
firstName: "Alan",
lastName: "Turing",
get fullName() { return `${[Link]} ${[Link]}`; },
set fullName(val) {
[[Link], [Link]] = [Link](" ");
},
introduce() { return `I am ${[Link]}`; }
};

// Property descriptors
[Link](person, "id", {
value: 1,
writable: false, // read-only
enumerable: false, // won't show in for..in or [Link]
configurable: false
});

// Object methods
[Link](person); // ["firstName", "lastName"]
[Link](person); // ["Alan", "Turing"]
[Link](person); // [["firstName","Alan"], ...]
[Link](obj); // deep immutability (shallow — nested still mutable)
[Link]({}, src); // shallow clone

// Computed property names


const prefix = "get";
const api = {
[`${prefix}Name`]() { return "Ada"; },
[`${prefix}Age`]() { return 30; }
};

3.2 The Prototype Chain


Every JavaScript object has an internal link to another object called its prototype. Property lookups walk
up this chain until they reach null.
// Manual prototype chain
const animal = {
breathe() { return `${[Link]} breathes`; }
};
const dog = [Link](animal); // dog.__proto__ === animal
[Link] = "Rex";
[Link] = function() { return "Woof!"; };
[Link](); // "Rex breathes" — found on prototype

// Prototype chain: dog → animal → [Link] → null

Prep → React 19 JavaScript 1-Week Refresher Guide • Page 9 © 2026


// hasOwnProperty vs inherited
[Link]("name"); // true
[Link]("breathe"); // false

// Check prototype
[Link](dog) === animal; // true

3.3 ES6 Classes


class Shape {
#area = 0; // private field (ES2022)
static count = 0;

constructor(color) {
[Link] = color;
[Link]++;
}
describe() {
return `A ${[Link]} shape`;
}
static reset() { [Link] = 0; }
}

class Circle extends Shape {


constructor(radius, color) {
super(color); // must call super before using 'this'
[Link] = radius;
}
get area() { return [Link] * [Link] ** 2; }
describe() {
return `${[Link]()} (circle, r=${[Link]})`;
}
}

const c = new Circle(5, "red");


[Link](); // "A red shape (circle, r=5)"
[Link]; // 78.539...
[Link]; // 1 (inherited static)

■ Note: Classes in JS are syntactic sugar over the prototype system. Under the hood, class methods are
added to [Link]. There is no separate class object at runtime.

3.4 Object Patterns for React


// Spread operator for immutable updates (critical in React!)
const state = { user: "Ada", count: 0, theme: "dark" };
const newState = { ...state, count: [Link] + 1 };
// state is unchanged — newState is a new object

// Destructuring with defaults & rename


const { user: userName = "Guest", count = 0, missing = "default" } = state;

// Optional chaining — avoid null checks


const city = user?.address?.city ?? "Unknown";

Prep → React 19 JavaScript 1-Week Refresher Guide • Page 10 © 2026


const firstTag = post?.tags?.[0] ?? "none";

// Nullish coalescing vs OR
const a = 0 || "fallback"; // "fallback" — 0 is falsy
const b = 0 ?? "fallback"; // 0 — only null/undefined trigger ??

// Object shorthand (used constantly in React)


const x = 1, y = 2;
const point = { x, y }; // { x: 1, y: 2 }
function makeUser(name, age) { return { name, age }; }

■ Day 3 Practice Checklist


■ Draw the prototype chain for an array ■ Use optional chaining on nested data

■ Use [Link] to set up inheritance ■ Immutably update a nested object with spread

■ Write a class with private fields (#) ■ Explain how class methods relate to .prototype

■ Extend a class and call super() ■ Use [Link] and test its limits

Prep → React 19 JavaScript 1-Week Refresher Guide • Page 11 © 2026


DAY Event Loop • Promises •
4 Async JavaScript async/await • Error Handling

4.1 The Event Loop


JavaScript is single-threaded. The event loop allows it to handle async operations without blocking. Know
the execution order: call stack → microtask queue → macrotask queue.
[Link]("1 — sync"); // 1st

setTimeout(() => [Link]("2 — macro"), 0); // 3rd

[Link]().then(() => [Link]("3 — micro")); // 2nd

[Link]("4 — sync"); // still sync, before any async

// Output order: 1, 4, 3, 2
// Call stack runs fully first, then microtasks (Promises),
// then macrotasks (setTimeout, setInterval, I/O)

// Microtasks: [Link]/catch/finally, queueMicrotask, MutationObserver


// Macrotasks: setTimeout, setInterval, setImmediate, I/O, UI render

■ Tip: Interview favorite: 'What logs first — [Link]().then or setTimeout(fn, 0)?' Answer: the
Promise, because microtasks drain before macrotasks.

4.2 Promises
// Creating a Promise
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

const fetchUser = (id) => new Promise((resolve, reject) => {


if (id <= 0) reject(new Error("Invalid ID"));
else resolve({ id, name: "Ada" });
});

// Chaining
fetchUser(1)
.then(user => ({ ...user, role: "admin" }))
.then(user => [Link](user))
.catch(err => [Link]([Link]))
.finally(() => [Link]("Done"));

// Combinators — know all four!


// [Link] — resolves when ALL resolve, rejects if ANY reject
const [a, b] = await [Link]([fetchUser(1), fetchUser(2)]);

// [Link] — always resolves with status of each


const results = await [Link]([p1, p2, failingP]);
[Link](r => [Link] === "fulfilled"
? [Link]([Link]) : [Link]([Link]));

// [Link] — resolves/rejects with the FIRST settled

Prep → React 19 JavaScript 1-Week Refresher Guide • Page 12 © 2026


// [Link] — resolves with first FULFILLED (ignores rejections)

4.3 async / await


// async functions always return a Promise
async function loadData(url) {
try {
const response = await fetch(url);
if (![Link]) throw new Error(`HTTP ${[Link]}`);
const data = await [Link]();
return data;
} catch (error) {
[Link]("Fetch failed:", [Link]);
throw error; // re-throw so callers can handle it
}
}

// Parallel vs sequential
// SEQUENTIAL (slower — each awaits the previous)
const u1 = await fetchUser(1);
const u2 = await fetchUser(2);

// PARALLEL (faster — fire both at once)


const [user1, user2] = await [Link]([fetchUser(1), fetchUser(2)]);

// For-await-of with async iterators


async function processStream(stream) {
for await (const chunk of stream) {
process(chunk);
}
}

// Top-level await (in ES modules / React components via bundlers)


const config = await loadConfig();

■■ Watch out: Always wrap await calls in try/catch or attach .catch() to the returned Promise. Unhandled
rejections crash [Link] and cause silent failures in browsers.

4.4 Error Handling Patterns


// Custom error classes
class AppError extends Error {
constructor(message, statusCode = 500) {
super(message);
[Link] = "AppError";
[Link] = statusCode;
}
}

// Retry with exponential backoff


async function fetchWithRetry(url, retries = 3, delay = 300) {
for (let i = 0; i < retries; i++) {
try {
return await fetch(url).then(r => [Link]());
} catch (err) {

Prep → React 19 JavaScript 1-Week Refresher Guide • Page 13 © 2026


if (i === retries - 1) throw err;
await new Promise(r => setTimeout(r, delay * 2 ** i));
}
}
}

// Result pattern (avoids exceptions for expected failures)


async function safeLoad(url) {
try {
const data = await fetch(url).then(r => [Link]());
return { ok: true, data };
} catch (error) {
return { ok: false, error };
}
}
const { ok, data, error } = await safeLoad("/api/users");

■ Day 4 Practice Checklist


■ Predict output: sync, Promise, setTimeout ■ Write a custom Error subclass

■ Implement [Link] from scratch ■ Explain microtask vs macrotask queue

■ Convert callback code to async/await ■ Use [Link] for fault-tolerant fetches

■ Add retry logic to a fetch call ■ Handle errors at every level of a chain

Prep → React 19 JavaScript 1-Week Refresher Guide • Page 14 © 2026


DAY Destructuring • Iterators •
5 Modern ES6–ES2024 Generators • Modules

5.1 Destructuring & Spread


// Array destructuring
const [first, , third, ...rest] = [1, 2, 3, 4, 5];
// first=1, third=3, rest=[4,5]

// Swap without temp variable


let a = 1, b = 2;
[a, b] = [b, a]; // a=2, b=1

// Object destructuring with rename & default


const { name: username = "Guest", age = 0, address: { city } = {} } = user;

// Function parameter destructuring


function render({ title, items = [], => {} }) {
// ...
}

// Spread uses
const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [...arr1, ...arr2, 5]; // [1,2,3,4,5]

const base = { a: 1, b: 2 };
const extended = { ...base, c: 3, b: 99 }; // b overridden: { a:1, b:99, c:3 }

// Clone (shallow)
const clonedArr = [...original];
const clonedObj = { ...original };

5.2 Iterators & Generators


// Custom iterator (implements iteration protocol)
function range(start, end, step = 1) {
return {
[[Link]]() {
let current = start;
return {
next() {
if (current < end) {
const value = current;
current += step;
return { value, done: false };
}
return { value: undefined, done: true };
}
};
}
};
}

Prep → React 19 JavaScript 1-Week Refresher Guide • Page 15 © 2026


for (const n of range(0, 10, 2)) [Link](n); // 0,2,4,6,8
const nums = [...range(1, 4)]; // [1, 2, 3]

// Generator function — pause/resume with yield


function* fibonacci() {
let [a, b] = [0, 1];
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
const fib = fibonacci();
[Link]().value; // 0
[Link]().value; // 1
[Link]().value; // 1

// Async generator
async function* paginate(url) {
let page = 1;
while (true) {
const data = await fetch(`${url}?page=${page}`).then(r => [Link]());
if (![Link]) return;
yield data;
page++;
}
}

5.3 Maps, Sets, WeakMap, WeakSet


// Map — any key type, ordered, iterable
const map = new Map();
[Link]({ id: 1 }, "user-data"); // object as key!
[Link]("key", 42);
[Link]; // 2
[Link]("key"); // true
for (const [k, v] of map) [Link](k, v);
const obj = [Link]([Link]()); // Map → object

// Set — unique values, iterable


const set = new Set([1, 2, 2, 3, 3]);
[Link]; // 3
[Link](4).add(4); // chaining, still 4 unique
const unique = [...new Set(array)]; // dedup array

// WeakMap — keys must be objects, not iterable, GC-friendly


const cache = new WeakMap();
function process(obj) {
if ([Link](obj)) return [Link](obj);
const result = heavyCompute(obj);
[Link](obj, result); // auto-cleaned when obj is GC'd
return result;
}

// WeakSet — store objects without preventing GC

Prep → React 19 JavaScript 1-Week Refresher Guide • Page 16 © 2026


const seen = new WeakSet();
function trackVisit(el) { [Link](el); }

5.4 ES Modules
// Named exports
export const PI = 3.14;
export function add(a, b) { return a + b; }
export class Vector { /* ... */ }

// Default export (one per module)


export default function main() { /* ... */ }

// Import styles
import defaultFn from "./[Link]";
import { PI, add } from "./[Link]";
import { add as sum } from "./[Link]"; // rename
import * as math from "./[Link]"; // namespace

// Dynamic import (lazy loading — essential in React!)


const { heavy } = await import("./[Link]");
const module = await import(`./locales/${lang}.js`);

// Re-export (barrel files)


export { add, multiply } from "./[Link]";
export { default as Vector } from "./[Link]";

■ Tip: In React projects, barrel files ([Link] that re-exports) are common. Dynamic import() is used for
code splitting with [Link]().

5.5 Lesser-Known But Important Features


// Tagged template literals
function highlight(strings, ...values) {
return [Link]((acc, str, i) =>
acc + str + (values[i] ? `${values[i]}` : ""), "");
}
const name = "Ada";
highlight`Hello, ${name}! Welcome to ${"JS"}.`;

// Symbol — unique property keys


const id = Symbol("id");
const user = { [id]: 123, name: "Grace" };
user[id]; // 123
[Link](user); // ["name"] — Symbols are non-enumerable

// Proxy & Reflect


const validator = new Proxy({}, {
set(target, key, value) {
if (typeof value !== "number") throw new TypeError("Numbers only");
return [Link](target, key, value);
}
});
[Link] = 95; // OK
// [Link] = "A"; // TypeError

Prep → React 19 JavaScript 1-Week Refresher Guide • Page 17 © 2026


// Logical assignment operators (ES2021)
a ||= "default"; // a = a || "default"
b &&= transform(b); // b = b && transform(b)
c ??= "fallback"; // c = c ?? "fallback" (only null/undefined)

■ Day 5 Practice Checklist


■ Destructure nested objects with defaults ■ Deduplicate an array using Set

■ Build a custom iterable range() ■ Set up a barrel file with re-exports

■ Write a generator for infinite sequences ■ Use dynamic import() for lazy loading

■ Convert a plain object to Map and back ■ Implement a Proxy-based validator

Prep → React 19 JavaScript 1-Week Refresher Guide • Page 18 © 2026


DAY DOM • Events • Fetch • Storage •
6 The DOM & Browser APIs Web APIs

6.1 DOM Manipulation


// Selecting elements
[Link]("app");
[Link](".card"); // first match
[Link]("[Link]"); // NodeList (iterable)

// Creating & inserting


const el = [Link]("div");
[Link] = "Hello";
[Link] = "card";
[Link] = "42"; //
[Link](el);

// Modern insertion methods


[Link]("beforeend", el); // safest
[Link](sibling);
[Link](sibling);
[Link](newEl);
[Link]();

// Attribute vs property
[Link]("disabled", "");
[Link]("disabled");
[Link]("disabled");
[Link]("class");

// classList
[Link]("active", "visible");
[Link]("hidden");
[Link]("expanded");
[Link]("old", "new");
[Link]("active"); // true

6.2 Event Handling & Delegation


// addEventListener options
[Link]("click", handler, {
once: true, // auto-removes after first call
capture: false, // bubble phase (default)
passive: true // hints no preventDefault (better scroll perf)
});

// Event delegation — attach ONE listener to parent


[Link]("#list").addEventListener("click", (e) => {
const item = [Link]("[Link]");
if (!item) return;
[Link]("Clicked item:", [Link]);
});

Prep → React 19 JavaScript 1-Week Refresher Guide • Page 19 © 2026


// Custom events
const ev = new CustomEvent("user:login", {
detail: { userId: 42, role: "admin" },
bubbles: true,
cancelable: true
});
[Link](ev);
[Link]("user:login", e => [Link]([Link]));

// Prevent default & stop propagation


[Link]("submit", (e) => {
[Link](); // stop page reload
[Link](); // stop bubbling
});

6.3 Fetch & Network


// Complete fetch pattern
async function api(method, url, body = null) {
const options = {
method,
headers: { "Content-Type": "application/json",
"Authorization": `Bearer ${token}` },
...(body && { body: [Link](body) })
};
const res = await fetch(url, options);
if (![Link]) {
const err = await [Link]().catch(() => ({}));
throw new Error([Link] || `HTTP ${[Link]}`);
}
return [Link] === 204 ? null : [Link]();
}

// AbortController — cancel requests


const controller = new AbortController();
const { signal } = controller;
fetch("/api/data", { signal })
.then(r => [Link]())
.catch(e => [Link] === "AbortError" ? null : [Link](e));

setTimeout(() => [Link](), 5000); // timeout

// FormData
const form = [Link]("form");
const data = new FormData(form);
[Link]("extra", "value");
fetch("/upload", { method: "POST", body: data }); // no Content-Type header needed

6.4 Web Storage & Other Browser APIs


// localStorage (persists), sessionStorage (tab-scoped)
[Link]("user", [Link]({ name: "Ada" }));
const user = [Link]([Link]("user") ?? "null");
[Link]("user");

Prep → React 19 JavaScript 1-Week Refresher Guide • Page 20 © 2026


[Link]();

// Intersection Observer (lazy loading, infinite scroll)


const io = new IntersectionObserver((entries) => {
[Link](entry => {
if ([Link]) {
[Link] = [Link];
[Link]([Link]);
}
});
}, { threshold: 0.1, rootMargin: "200px" });
[Link]("img[data-src]").forEach(img => [Link](img));

// ResizeObserver
const ro = new ResizeObserver(entries => {
for (const { contentRect } of entries) {
[Link]([Link]);
}
});
[Link]([Link](".sidebar"));

// Web Workers (off-main-thread heavy compute)


const worker = new Worker("[Link]");
[Link]({ data: bigArray });
[Link] = e => [Link]("Result:", [Link]);

■ Day 6 Practice Checklist


■ Build a todo list using only DOM APIs ■ Implement lazy image loading with IntersectionObserver

■ Use event delegation for dynamic items ■ Persist app state to localStorage with JSON

■ Write a generic api() fetch wrapper ■ Create and listen to a custom event

■ Add abort/timeout to a fetch call ■ Use querySelectorAll + classList to toggle themes

Prep → React 19 JavaScript 1-Week Refresher Guide • Page 21 © 2026


DAY Design Patterns • FP •
7 Patterns & React 19 Prep Performance • React Bridge

7.1 Essential Design Patterns


// Module pattern (encapsulation)
const Store = (() => {
let _state = {};
const _listeners = new Set();
return {
getState: () => ({ ..._state }),
setState(update) {
_state = { ..._state, ...update };
_listeners.forEach(fn => fn(_state));
},
subscribe(fn) {
_listeners.add(fn);
return () => _listeners.delete(fn); // unsubscribe
}
};
})();

// Observer pattern
class EventEmitter {
#events = new Map();
on(event, fn) { (this.#[Link](event) ?? this.#[Link](event, new Set()).get(ev
ent)).add(fn); }
off(event, fn) { this.#[Link](event)?.delete(fn); }
emit(event, data) { this.#[Link](event)?.forEach(fn => fn(data)); }
}

// Singleton
class Config {
static #instance;
static getInstance() { return (Config.#instance ??= new Config()); }
#settings = {};
set(k, v) { this.#settings[k] = v; }
get(k) { return this.#settings[k]; }
}

7.2 Functional Programming Patterns


// Immutability helpers
const append = (arr, item) => [...arr, item];
const prepend = (arr, item) => [item, ...arr];
const remove = (arr, i) => [...[Link](0, i), ...[Link](i + 1)];
const updateAt = (arr, i, fn) => [Link]((el, idx) => idx === i ? fn(el) : el);
const updateKey = (obj, key, fn) => ({ ...obj, [key]: fn(obj[key]) });

// Function composition
const compose = (...fns) => x => [Link]((v, f) => f(v), x);
const pipe = (...fns) => x => [Link]((v, f) => f(v), x);

Prep → React 19 JavaScript 1-Week Refresher Guide • Page 22 © 2026


const process = pipe(
str => [Link](),
str => [Link](),
str => [Link](/\s+/g, "-")
);
process(" Hello World "); // "hello-world"

// Transducers (compose array transformations efficiently)


const xform = arr =>
arr
.filter(x => x > 0)
.map(x => x * 2)
.reduce((acc, x) => acc + x, 0);

7.3 Performance Patterns


// Debounce — delay execution until idle
function debounce(fn, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => [Link](this, args), delay);
};
}
const => fetchResults(query), 300);

// Throttle — max once per interval


function throttle(fn, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
[Link](this, args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
}
[Link]("scroll", throttle(updateScroll, 100));

// Virtual list concept (render only visible items)


function getVisibleItems(items, scrollTop, containerHeight, itemHeight) {
const start = [Link](scrollTop / itemHeight);
const end = [Link]([Link], start + [Link](containerHeight / itemHeight) +
1);
return { start, end, items: [Link](start, end) };
}

// requestAnimationFrame for smooth updates


function animate(update) {
let id;
const loop = (timestamp) => { update(timestamp); id = requestAnimationFrame(loop); };
id = requestAnimationFrame(loop);
return () => cancelAnimationFrame(id);
}

Prep → React 19 JavaScript 1-Week Refresher Guide • Page 23 © 2026


7.4 ■ JavaScript → React 19 Bridge
Everything you reviewed this week maps directly to React 19 concepts. Here's the critical mapping:

JS Concept React 19 Usage

Closures useState, useCallback, useRef internals; all hooks use closures

async/await + Promises Server Components, useTransition, Suspense data fetching

Immutability patterns setState, useReducer — never mutate state directly

Event delegation React's synthetic event system (single root listener)

Modules (import/export) Component files, lazy(), code splitting

Destructuring Props: function Card({ title, items = [] }) {}

Spread operator Props: <Component {...props} />, state updates

WeakMap/WeakRef React's internal fiber tree memory management

Generators/Iterators Streaming RSC, async iterators for data streams

Proxy Reactivity in signals-like patterns (experimental)

[Link] React key prop, list rendering optimization

7.5 React 19 New Features — What JS You Need


// React 19: use() hook — reads Promises/Context synchronously
// Requires: async/await, Promises, Suspense boundaries
import { use, Suspense } from "react";
function UserCard({ userPromise }) {
const user = use(userPromise); // suspends if pending
return {[Link]};
}

// React 19: Server Actions — async functions on the server


// Requires: async functions, FormData, error handling
async function saveUser(formData) {
"use server";
const name = [Link]("name");
await [Link]({ name });
}

// React 19: useOptimistic — optimistic UI


// Requires: understanding of state management, closures
const [optimisticItems, addOptimistic] = useOptimistic(items,
(state, newItem) => [...state, { ...newItem, pending: true }]
);

// React 19: useFormStatus — track form submission state


// Requires: understanding of context, async form handling
import { useFormStatus } from "react-dom";
function Submit() {

Prep → React 19 JavaScript 1-Week Refresher Guide • Page 24 © 2026


const { pending } = useFormStatus();
return {pending ? "Saving..." : "Save"};
}

■ Tip: React 19's biggest shift: async by default. Server Components run async, actions are async, use()
handles Promises. Your Day 4 async mastery is the most critical prep for React 19.

■ Day 7 Practice Checklist


■ Implement a simple pub/sub EventEmitter ■ Implement a basic Singleton class

■ Build a debounce and throttle from scratch ■ Map each JS topic to a React 19 use case

■ Write compose() and pipe() utilities ■ Build a mini state manager (like Zustand)

■ Create an immutable state update helper ■ Write a component using async/await patterns

Prep → React 19 JavaScript 1-Week Refresher Guide • Page 25 © 2026


■ Quick Reference Card

Array Methods Cheat Sheet


Method Returns Mutates? Use Case

map(fn) new array No Transform every element

filter(fn) new array No Keep elements passing test

reduce(fn, init) single value No Accumulate to one value

find(fn) element | undefined No First match

findIndex(fn) number No Index of first match

some(fn) boolean No Any match?

every(fn) boolean No All match?

flat(depth) new array No Flatten nested arrays

flatMap(fn) new array No map() + flat(1)

forEach(fn) undefined No Side effects only

sort(fn) same array YES ■■ Sort in place

splice(i,n,...) removed items YES ■■ Insert/remove in place

push/pop new length / el YES ■■ Stack operations

includes(val) boolean No Check membership

[Link]() new array N/A Convert iterable

Common Gotchas to Never Forget


Gotcha Wrong Right

typeof null typeof null === "null" ✗ typeof null === "object" ✓

NaN check NaN === NaN → false ✗ [Link](NaN) → true ✓

Array check typeof [] === "array" ✗ [Link]([]) → true ✓

Async forEach [Link](async fn) ✗ (no await) for await or [Link]([Link](async fn)) ✓

Object spread clone = obj ✗ (reference) clone = { ...obj } ✓ (shallow copy)

parseInt radix parseInt("08") ✗ (octal risk) parseInt("08", 10) ✓

== null check val === null || val === undefined val == null (catches both) ✓

The 'Must Know' Checklist Before React 19


■ Explain the prototype chain in 60 seconds ■ Handle async errors at every boundary

Prep → React 19 JavaScript 1-Week Refresher Guide • Page 26 © 2026


■ Write any Promise combinator from memory ■ Know which array methods mutate vs return new

■ Describe the event loop execution order ■ Use ES modules (import/export) fluently

■ Destructure complex nested objects confidently ■ Implement debounce without looking it up

■ Use optional chaining and nullish coalescing ■ Explain 'this' in arrow vs regular functions

■ Build a closure-based counter/store ■ Write immutable state update patterns

■ You're ready for React 19!


Start with: React docs → [Link] | React 19 changelog → [Link]/blog

Prep → React 19 JavaScript 1-Week Refresher Guide • Page 27 © 2026

You might also like