Unit 6: Advanced JavaScript
Objects, Scope, Event Handling, and Validation Forms
You need JavaScript fundamentals (Unit 5): variables, data types, conditionals, loops, and functions. If if/else, for, and function syntax feel unfamiliar, review Unit 5 first. You'll also need basic HTML forms (U3) and CSS selectors (U4).
- Use Array methods (push, pop, map, filter, reduce) to manipulate data
- Distinguish between global and local scope and handle ReferenceError with try/catch
- Explain event propagation (capturing phase, target phase, bubbling phase)
- Validate form data using JavaScript object construction and conditional checks
1. Objects, Data Types, and Scope
JavaScript treats almost everything as an Object. An object is a collection of key-value pairs.
String: Manipulated via methods like.length,.toUpperCase().Number: Handles integers and floats. Parsed viaparseInt().Boolean: Represents logicaltrueorfalse.Array: A special type of object used to store ordered lists. (e.g.,let arr = [1, 2, 3];).
- Global Scope: Variables declared outside any function. Accessible anywhere.
- Local (Function/Block) Scope: Variables declared inside a function or block (using
let/const). They are destroyed from memory once the block finishes executing.
Scope Visualizer Engine
let globalVar = "University";
function processData() {
let localVar = "Student";
console.log(globalVar); // Works!
console.log(localVar); // Works!
}
console.log(localVar); // ERROR!
Memory Execution Output
2. Array Methods — Complete Reference
Arrays are the most commonly used data structure in JavaScript. The Array prototype provides powerful methods for data transformation.
Live Method Tester
Pick a method from the dropdown — its example expression is dropped into the box. Tweak it however you like, then hit Run.
Output
3. String & Number Methods
Strings and Numbers come with built-in methods accessible via the dot operator.
| Category | Method | Description | Example |
|---|---|---|---|
| String | .length | Character count | "hello".length → 5 |
| .toUpperCase() | Convert to uppercase | "hi".toUpperCase() → "HI" | |
| .toLowerCase() | Convert to lowercase | "HI".toLowerCase() → "hi" | |
| .trim() | Remove whitespace | " a ".trim() → "a" | |
| .split() | Split into array | "a,b".split(",") → ["a","b"] | |
| .replace() | Replace substring | "a b".replace(" ","-") → "a-b" | |
| Number | parseInt() | String → integer | parseInt("42") → 42 |
| parseFloat() | String → float | parseFloat("3.14") → 3.14 | |
| .toFixed() | Format decimal places | (3.14159).toFixed(2) → "3.14" | |
| isNaN() | Check if not-a-number | isNaN("abc") → true |
4. Event Propagation — Capturing vs Bubbling
When an event fires on a nested element, it travels through three phases:
- Capturing — Event travels from
windowdown to the target element. - Target — Event reaches the element that was clicked.
- Bubbling — Event travels back up from target to
window.
By default, event listeners fire during the bubbling phase. To listen during capturing, pass { capture: true } as the third argument to addEventListener().
Click the Target button below to see event propagation in action:
// Capturing phase listeners (third argument: true)
outer.addEventListener('click', () => {
logEvent('CAPTURING: Outer div caught event on way DOWN', 'capture');
}, true);
inner.addEventListener('click', () => {
logEvent('CAPTURING: Inner div caught event on way DOWN', 'capture');
}, true);
// Target phase listener (default: bubbling phase)
target.addEventListener('click', () => {
logEvent('TARGET: The button itself received the click', 'target');
});
// Bubbling phase listeners (third argument omitted / false)
inner.addEventListener('click', () => {
logEvent('BUBBLING: Inner div caught event on way UP', 'bubble');
});
outer.addEventListener('click', () => {
logEvent('BUBBLING: Outer div caught event on way UP', 'bubble');
});
5. Common Event Types Reference
Events are categorized by the type of user interaction. Here are the most commonly used ones:
6. Event Handling & Form Validation
- Event Handling: Binding JavaScript functions to HTML DOM interactions. Examples:
onclick(mouse click),onsubmit(form submission),oninput(typing). - Error Handling (try...catch): Code can fail. Instead of the browser crashing silently, we wrap risky code in a
tryblock. If it fails, the engine throws control to thecatchblock, allowing us to handle the error gracefully. - Form Validation: Before sending data to a server (Unit 1), the client (Browser) must verify the data structure is correct. This saves server processing power and provides immediate user feedback.
Academic Portal Access
Click the button below to trigger the onclick event and spawn the responsive modal DOM node.
Validation Output
<!-- Pattern attribute for inline validation -->
<input type="text" pattern="[A-Za-z]{3,}" title="At least 3 letters">
// JavaScript validation with checkValidity() / reportValidity()
function validateForm() {
const name = document.getElementById('stuName').value.trim();
if (name.length < 3) {
document.getElementById('nameErr').style.display = 'block';
return false;
}
// HTML5 validation API
const input = document.getElementById('stuReg');
if (!input.checkValidity()) {
input.reportValidity();
return false;
}
return true;
}
7. The Event Object — Inspect Every Detail
Every handler receives an Event object describing what happened: type, target, pointer coordinates, modifier keys, and more. Move, click, and type inside the box to watch it update live.
Interact with the box on the right — move the mouse, click, or focus & type.
Properties update instantly; the log records each event in order.
8. addEventListener — Stacking & Removing Handlers
Unlike onclick = fn (which replaces any previous handler), addEventListener lets you attach many handlers to one element, and removeEventListener removes a specific one. Toggle handlers below and click the target.
Tip: with addEventListener('click', fn, { once:true }) a handler runs a single time then auto-removes.
9. DOM Manipulation — Create, Read, Update, Delete
JavaScript changes the page by mutating the DOM tree: createElement, textContent, style, setAttribute, appendChild, removeChild. Use the buttons to mutate the box and watch its HTML.
The right panel shows the live innerHTML of the box after each action.
10. DOM Traversal — Navigate the Tree
From any node you can walk the tree: parentElement, children, firstElementChild, nextElementSibling, previousElementSibling. Click a node below to inspect its relationships.
Click any node in the tree to inspect it.
- <ul id="trRoot">
- <li id="trA"> Item A
- <li id="trA1"> Sub A1
- <li id="trA2"> Sub A2
- <li id="trB"> Item B
- <li id="trA"> Item A
11. Form Events — input vs change vs focus/blur
input fires on every keystroke; change fires when the value is committed (on blur or selection); focus/blur fire when entering/leaving a field. Type and watch the firing order.
12. Error Handling — try / catch / finally
Wrap risky code in try; if it throws, catch receives the Error; finally always runs (good for cleanup). Run the presets to see each path.
The finally block runs whether or not an error occurs.
13. Throwing Custom Errors
Use throw to signal invalid states. Built-in subclasses (TypeError, RangeError) give meaningful .name values; catch reads .name and .message.
14. Objects — Properties, Keys & Membership
Objects bundle key-value pairs. Add/remove properties, list them with Object.keys(), and test membership with the in operator. Edit below and watch the object update.
15. The this Keyword
this is set by how a function is called: in a method it's the object; in a plain call it's the global (or undefined in strict mode); in an event handler it's the element; arrow functions inherit this from where they were defined.
Each button invokes the same conceptual code in a different calling context.
16. Event Delegation — One Listener, Many Children
Attach one listener to a parent and use e.target to find the clicked child. Children added later still work — no per-item wiring. Click items, then add a new one and click it.
One listener on the <ul> handles every <li>.
- Click me — Alpha
- Click me — Beta
- Click me — Gamma
Event Delegation
Instead of attaching a listener to every element, attach ONE listener to a parent and use e.target to determine which child was clicked. This works because events bubble up from target to parent:
document.getElementById("list").addEventListener("click", function(e) {
if (e.target.tagName === "LI") {
console.log("Clicked:", e.target.textContent);
}
});Benefits: works for dynamically added elements, uses less memory, and requires only one listener instead of hundreds. This pattern is essential for large lists, tables, and menus.
Web Storage vs Cookies vs IndexedDB
| Feature | localStorage | sessionStorage | Cookies | IndexedDB |
|---|---|---|---|---|
| Capacity | 5-10 MB | 5-10 MB | 4 KB | Unlimited (250 MB+) |
| Persistence | Until cleared | Tab close | Per expiry | Until cleared |
| Sent to server | No | No | Yes (every request) | No |
| Data type | String only | String only | String only | Any structured data |
| Sync/Async | Sync | Sync | Sync | Async (promise-based) |
| Use case | Preferences, cache | Form drafts | Auth tokens | Offline apps, blobs |
For most course data (quiz progress, theme, unit completion), localStorage is the right choice. Use IndexedDB when storing large datasets or binary data. Cookies should only be used for server-auth tokens.