← BEUVAULT 100219 Course U1 U2 U3 U4 U5 U6

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

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

Enter a JavaScript expression below and click Run to see the result. Try these examples:

  • [1,2,3].map(x => x * 2)
  • [5,2,8,1].sort()
  • "hello world".toUpperCase()
  • (3.14159).toFixed(2)
[4, 6, 8, 10]

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().

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

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

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

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

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.