JavaScript, the DOM and client-side validation notes — Unit 2
Free unit-wise study notes on javascript, the dom and client-side validation for Web Technology, Semester 5 of B.Tech — Computer Science & Engineering — key concepts, examples, important questions and a revision checklist for semester exams.
JavaScript, the DOM and client-side validation
Notebook — 20 pages
Page 1
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 2 —
1. Introduction to JavaScript
JavaScript (JS) is a high-level, interpreted programming language primarily used to add interactivity and logic to web pages. It is the only programming language native to web browsers.
⇒1.1 Characteristics of JavaScript
Dynamic Typing: Variables do not have fixed types. A variable holding a string can later hold a number.
Interpreted (JIT): Modern browsers use Just-In-Time (JIT) compilers (like V8 in Chrome) to compile JS into machine code milliseconds before execution.
Object-Oriented (Prototype-based): JS uses objects and inheritance, but it relies on Prototypes rather than classical Classes.
Single-Threaded & Non-Blocking: JS runs on a single main thread, but uses an Event Loop to handle asynchronous operations (like network requests) without freezing the UI.
Page 2
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 2 —
2. Variables and Data Types
⇒2.1 Declaring Variables
Modern JS (ES6+) provides three ways to declare variables:
`var`: The old way. Function-scoped, prone to hoisting bugs. Avoid using it.
`let`: Block-scoped. Used for variables that will change their value later (e.g., loop counters).
`const`: Block-scoped. Used for variables that should never be reassigned. (Best practice: use `const` by default, switch to `let` only if needed).
⇒2.2 Primitive Data Types
Type
Example
Description
String
`'Hello'`
Text data enclosed in quotes.
Number
`42`, `3.14`
Integer and floating-point numbers.
Boolean
`true`, `false`
Logical entities.
Undefined
`undefined`
A variable declared but not assigned a value.
Null
`null`
Intentional absence of any object value.
Symbol
`Symbol('id')`
Unique and immutable identifier (ES6).
Page 3
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 2 —
3. Functions and Scope
Functions are reusable blocks of code designed to perform a particular task.
⇒3.1 Function Syntax
// Function Declaration (Hoisted)
function add(a, b) {
return a + b;
}
// Arrow Function (ES6 - Not Hoisted, concise)
const multiply = (a, b) => a * b;
⇒3.2 Scope
Scope determines the accessibility (visibility) of variables.
Global Scope: Variables declared outside any function are accessible everywhere.
Function/Local Scope: Variables declared inside a function are not accessible from outside it.
Block Scope: Variables declared with `let` or `const` inside a `{ }` block (like an `if` statement) are only accessible within that block.
Page 4
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 2 —
4. Arrays and Objects
Arrays and Objects are the primary reference data types used to store collections of data.
⇒4.1 Arrays
Ordered lists of values. In JS, arrays can hold mixed data types.
const fruits = ['Apple', 'Banana', 'Orange'];
fruits.push('Mango'); // Adds to end
console.log(fruits[0]); // 'Apple'
⇒4.2 Objects (JSON-like)
Collections of key-value pairs. Keys are strings, values can be any data type (including other objects or functions).
Modern JS relies heavily on functional programming paradigms. Higher-order functions are functions that take other functions as arguments (callbacks).
⇒5.1 The Holy Trinity: Map, Filter, Reduce
`.map()`: Creates a new array populated with the results of calling a provided function on every element. (Used for transforming data).
`.filter()`: Creates a new array with all elements that pass the test implemented by the provided function. (Used for removing unwanted data).
`.reduce()`: Executes a reducer function on each element, resulting in a single output value (e.g., summing all numbers in an array).
const nums = [1, 2, 3, 4];
const doubled = nums.map(n => n * 2); // [2, 4, 6, 8]
const evens = nums.filter(n => n % 2 === 0); // [2, 4]
const sum = nums.reduce((total, n) => total + n, 0); // 10
Page 6
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 2 —
6. The Document Object Model (DOM)
The DOM is an API for HTML documents. When a browser loads a web page, it creates a hierarchical, tree-like structure of objects representing the HTML tags. JavaScript uses the DOM to read and manipulate the page dynamically.
⇒6.1 DOM Tree Structure
The `window` object represents the browser tab. The `document` object is a property of the window and represents the HTML page itself.
`document` (Root)
├── `<html>`
│ ├── `<head>` (title, meta)
│ └── `<body>` (h1, p, div)
Every HTML tag is an 'Element Node'. The text inside tags are 'Text Nodes'. JavaScript can access, modify, delete, or create any of these nodes.
Page 7
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 2 —
7. DOM Traversal and Selection
To manipulate the page, JS first needs to 'find' the target HTML elements.
⇒7.1 Selecting Elements
`document.getElementById('myId')`: Fast, returns a single element.
`document.getElementsByClassName('myClass')`: Returns a live HTMLCollection of all matching elements.
`document.querySelector('.myClass')`: Modern standard. Uses CSS syntax. Returns the first matching element.
`document.querySelectorAll('.myClass')`: Returns a static NodeList of all matching elements. (Can use `.forEach()` on this).
⇒7.2 Traversing the Tree
Once you have an element, you can navigate relative to it:
`element.parentElement`
`element.children`
`element.nextElementSibling`
`element.previousElementSibling`
Page 8
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 2 —
8. DOM Manipulation
Once selected, elements can be dynamically modified.
⇒8.1 Modifying Content and Attributes
`element.textContent = 'New text'`: Safely changes the text inside the element.
`element.innerHTML = '<b>Bold</b>'`: Replaces the HTML inside. (Dangerous: Vulnerable to XSS attacks if using user input).
`element.setAttribute('src', 'image.jpg')`: Modifies HTML attributes.
`element.classList.add('active')`: The best way to change styles dynamically is by adding/removing CSS classes, rather than manipulating `element.style` directly.
⇒8.2 Creating and Removing Elements
// Create a new paragraph
const p = document.createElement('p');
p.textContent = 'I am new!';
// Append it to the body
document.body.appendChild(p);
// Remove an element
p.remove();
Page 9
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 2 —
9. Event Handling
Events are 'things' that happen to HTML elements (e.g., a user clicks a button, a key is pressed, the page finishes loading). JS can 'listen' for these events and execute code in response.
⇒9.1 Event Listeners
The modern, preferred way to handle events is using `addEventListener`.
const btn = document.querySelector('#submitBtn');
btn.addEventListener('click', function(event) {
console.log('Button was clicked!');
// 'event' object contains details about the click (mouse coordinates, target element)
});
When an event occurs on an element (e.g., a click on a `<button>`), it first runs the handlers on it, then runs the handlers on its parent (e.g., a `<div>`), then all the way up to the `document`. This ripple effect is called bubbling.
You can stop bubbling by calling `event.stopPropagation()` inside the handler.
⇒10.2 Event Delegation
Instead of attaching an event listener to 100 individual `<li>` items, you attach a single event listener to the parent `<ul>`. Because of bubbling, clicks on the `<li>` will travel up to the `<ul>`. You then use `event.target` to figure out exactly which child was clicked.
Massively improves performance (less memory used by listeners).
Automatically handles new child elements added dynamically later.
Page 11
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 2 —
11. Client-Side Validation
Form validation ensures that the user has provided required data in the correct format before submitting it to the server. Client-side validation happens in the browser.
⇒11.1 Why do it?
Provides instant feedback to the user, improving UX.
Saves server bandwidth by preventing bad data from being transmitted.
CRITICAL RULE: Client-side validation is easily bypassed (users can disable JS or modify DOM). It is for UX only. You MUST re-validate everything on the server.
⇒11.2 Built-in HTML5 Validation
Using attributes like `required`, `minlength`, `max`, and `pattern` (Regex). The browser handles the UI tooltips automatically.
Page 12
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 2 —
12. Custom JavaScript Validation
When HTML5 validation isn't complex enough (e.g., checking if 'Password' and 'Confirm Password' fields match), JavaScript is required.
⇒12.1 The Validation Flow
const form = document.querySelector('form');
form.addEventListener('submit', function(event) {
const password = document.querySelector('#pwd').value;
const confirm = document.querySelector('#confirm').value;
if (password !== confirm) {
// Prevent the form from submitting to the server
event.preventDefault();
// Show custom error message to user
showError('Passwords do not match');
}
});
⇒12.2 Regular Expressions (Regex)
Regex is a powerful syntax for defining search patterns in strings. JS uses the `.test()` method to validate input against a Regex pattern (e.g., verifying a string looks exactly like a phone number format).
Page 13
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 2 —
13. The Web Storage API
The Web Storage API allows JS to store key/value pairs in the browser locally, much more intuitively and with larger capacity (5MB) than cookies (4KB).
⇒13.1 LocalStorage vs SessionStorage
`localStorage`: Data persists permanently, even if the browser is closed and reopened. (Good for saving user preferences like Dark Mode).
`sessionStorage`: Data is wiped the moment the browser tab is closed. (Good for sensitive temporary data like multi-step form progress).
⇒13.2 Usage
// Save data (must be a string)
localStorage.setItem('theme', 'dark');
// Read data
const currentTheme = localStorage.getItem('theme');
// Remove data
localStorage.removeItem('theme');
Page 14
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 2 —
14. JSON Parsing and Storage
Because Web Storage and Network APIs only transmit text strings, complex JS objects must be converted to strings before storage/transmission.
⇒14.1 Serialization and Deserialization
`JSON.stringify(object)`: Converts a JS object/array into a JSON string.
`JSON.parse(string)`: Parses a JSON string back into a live JS object/array.
⇒14.2 Storing Objects in LocalStorage
const user = { name: 'Alice', role: 'admin' };
// Must stringify before saving
localStorage.setItem('user', JSON.stringify(user));
// Must parse after retrieving
const retrieved = JSON.parse(localStorage.getItem('user'));
console.log(retrieved.name); // 'Alice'
Page 15
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 2 —
15. Modern JavaScript (ES6+ Features)
ECMAScript 6 (2015) was a massive update to the language. Modern JS development relies heavily on these features for clean, maintainable code.
⇒15.1 Template Literals
Using backticks (`` ` ``) allows multi-line strings and string interpolation, replacing messy string concatenation.
Used in function declarations to pack an indefinite number of arguments into a single array.
function sum(...numbers) {
// 'numbers' is an array of all passed arguments
return numbers.reduce((a, b) => a + b, 0);
}
Page 17
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 2 —
17. JavaScript Modules (ESM)
Before ES6, JS had no native module system; all scripts loaded via `<script>` tags shared a single massive global scope, leading to variable collisions. ES Modules (ESM) fix this.
⇒17.1 Exporting and Importing
Code in a module is isolated. You explicitly `export` what you want to share, and `import` it elsewhere.
// math.js
export const PI = 3.14;
export function add(a, b) { return a + b; }
// app.js
import { PI, add } from './math.js';
console.log(add(10, PI));
⇒17.2 `<script type="module">`
To use modules directly in a browser, you must tell the browser that the script is a module, which automatically prevents its variables from leaking into the global scope and enables CORS restrictions.
Page 18
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 2 —
18. Asynchronous JavaScript (Intro)
Because JS is single-threaded, if a task takes 5 seconds (like fetching data from a database), the entire browser tab would freeze. Asynchronous programming solves this.
⇒18.1 Callbacks (The Old Way)
A callback is a function passed as an argument to an async function. The async function executes the callback when it finally finishes.
setTimeout(function() {
console.log('Executes after 2 seconds without freezing UI');
}, 2000);
Problem: 'Callback Hell' (Pyramid of Doom) occurs when you have multiple dependent async operations, resulting in deeply nested, unreadable code.
Page 19
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 2 —
19. Promises
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation. It solves Callback Hell.
⇒19.1 Promise States
Pending: Initial state, neither fulfilled nor rejected.
Fulfilled: Operation completed successfully.
Rejected: Operation failed.
⇒19.2 Using Promises (.then and .catch)
Instead of passing callbacks into the function, you chain `.then()` for success and `.catch()` for errors.
Introduced in ES8, `async/await` is syntactic sugar on top of Promises. It makes asynchronous code look and behave exactly like synchronous code, making it infinitely easier to read.
⇒20.1 Syntax
`async`: Placed before a function, it ensures the function always returns a Promise.
`await`: Can only be used inside an `async` function. It pauses the execution of that specific function until the Promise settles, while the rest of the application remains unblocked.
async function loadUser() {
try {
// Pauses here until fetch is done
const response = await fetch('/api/user');
const data = await response.json();
console.log(data);
} catch (error) {
// Replaces the .catch() block
console.log('Request failed');
}
}