BEUVAULT Course Unit 6 · Advanced JavaScript & Events
Course 100219 · Web Designing

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

Objects & Types:

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 via parseInt().
  • Boolean: Represents logical true or false.
  • Array: A special type of object used to store ordered lists. (e.g., let arr = [1, 2, 3];).
Scope: Determines the accessibility of variables.
- 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

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

> Waiting for execution...

2. Array Methods — Complete Reference

Arrays are the most commonly used data structure in JavaScript. The Array prototype provides powerful methods for data transformation.

push()
Add to end
arr.push(4)
pop()
Remove from end
arr.pop()
shift()
Remove from start
arr.shift()
unshift()
Add to start
arr.unshift(1)
map()
Transform each element
arr.map(x=>x*2)
filter()
Keep matching elements
arr.filter(x=>x>2)
reduce()
Accumulate to single value
arr.reduce((a,b)=>a+b, 0)
find()
First match
arr.find(x=>x===3)
forEach()
Iterate
arr.forEach(fn)
includes()
Check existence
arr.includes(2)
indexOf()
Find index
arr.indexOf(3)
slice()
Extract portion
arr.slice(1,3)
splice()
Add/remove at index
arr.splice(1,1)
sort()
Sort in place
arr.sort()
join()
Convert to string
arr.join(", ")
concat()
Merge arrays
arr.concat([4,5])
Live Method Tester

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.

CategoryMethodDescriptionExample
String.lengthCharacter 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"
NumberparseInt()String → integerparseInt("42") → 42
parseFloat()String → floatparseFloat("3.14") → 3.14
.toFixed()Format decimal places(3.14159).toFixed(2) → "3.14"
isNaN()Check if not-a-numberisNaN("abc") → true

4. Event Propagation — Capturing vs Bubbling

When an event fires on a nested element, it travels through three phases:

  1. Capturing — Event travels from window down to the target element.
  2. Target — Event reaches the element that was clicked.
  3. 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().

Event Propagation: Capturing vs Bubbling

Click the Target button below to see event propagation in action:

Outer Div (Capturing → Bubbling)
Inner Div
Click Me (Target)
// Event propagation log — click the target above
HTMLCSSJS
// 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:

click
Mouse click
dblclick
Double click
mouseover
Mouse enters
mouseout
Mouse leaves
mousedown
Button pressed
mouseup
Button released
keydown
Key pressed
keyup
Key released
submit
Form submitted
change
Value changed
input
Typing in field
focus
Element focused
blur
Element lost focus
load
Page loaded
scroll
Scrolling
resize
Window resized

6. Event Handling & Form Validation

Theory & Concepts:
  • 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 try block. If it fails, the engine throws control to the catch block, 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

Academic Portal Access

Click the button below to trigger the onclick event and spawn the responsive modal DOM node.

Validation Output

HTMLCSSJS
<!-- 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.

Event Object Explorer

Interact with the box on the right — move the mouse, click, or focus & type.

Properties update instantly; the log records each event in order.

Move • Click • Type here

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.

addEventListener Playground

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.

DOM Manipulation Playground

The right panel shows the live innerHTML of the box after each action.

Target element

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.

DOM Traversal Explorer

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

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.

Live Form Events

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.

try / catch / finally Lab

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.

throw & Custom Errors

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.

Object & Property Playground

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.

this Keyword Explorer

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.

Event Delegation Demo

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:

Example
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

FeaturelocalStoragesessionStorageCookiesIndexedDB
Capacity5-10 MB5-10 MB4 KBUnlimited (250 MB+)
PersistenceUntil clearedTab closePer expiryUntil cleared
Sent to serverNoNoYes (every request)No
Data typeString onlyString onlyString onlyAny structured data
Sync/AsyncSyncSyncSyncAsync (promise-based)
Use casePreferences, cacheForm draftsAuth tokensOffline 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.