1.12 Defining and Invoking Functions
Core Definition
A function in JavaScript is a named, reusable block of code designed to perform a specific task. It is defined once using the function keyword (or as an expression/arrow function) and invoked (called) by its name followed by parentheses, executing its body each time it is called.
Writing the same 10 lines of code in 15 different places is a maintenance disaster. A function is how you write it once, name it, and call that name wherever you need it. Change the function once and every call site benefits instantly.
Detailed Explanation
1. Function Declaration (Named Function)
The classic way. Hoisted by the JavaScript engine, meaning you can call it before its definition appears in the file.
function greet(name) { return "Hello, " + name + "!";}console.log(greet("Ram")); console.log(greet("Sita")); 2. Function Expression
A function stored inside a variable. Not hoisted — must be defined before it is called.
const square = function(n) { return n * n;};console.log(square(5)); console.log(square(9)); 3. Arrow Function (ES6+)
A compact syntax for function expressions. Especially useful for short callbacks and array methods.
const multiply = (a, b) => { return a * b;};const double = n => n * 2;console.log(multiply(4, 5)); console.log(double(7)); 4. Parameters vs Arguments
- Parameters: the named placeholders in the function definition:
function add(a, b) — here a and b are parameters. - Arguments: the actual values passed when calling the function:
add(3, 7) — here 3 and 7 are arguments.
5. Return Statement
return sends a value back to the caller and immediately stops function execution. A function without return returns undefined by default.
function add(a, b) { return a + b; console.log("This never runs"); }let result = add(10, 5); 6. Default Parameters (ES6+)
Assign a fallback value when no argument is passed.
function greet(name = "Student") { return "Hello, " + name;}console.log(greet()); console.log(greet("Hari")); 7. Function Scope
Variables declared inside a function exist only within that function. They are destroyed when the function returns. This is called local scope.
function demo() { let secret = "local only"; console.log(secret); }demo();console.log(secret); Comparison Table — Three Function Types:
Feature Declaration Expression Arrow Function Syntax function name() {} const f = function() {} const f = () => {} Hoisted? Yes No No this binding Dynamic Dynamic Inherits from parent scope Best used for General functions Callbacks, assignments Short callbacks, array methods
Common Mistake
Confusing parameters with arguments is one error; a larger one is calling a function expression before it is declared. greet() before const greet = function() {} throws a ReferenceError because expressions are not hoisted. Only declarations are. Also, forgetting return is a silent bug — the function runs but produces undefined, and the caller has no idea why the result is wrong.
Test Yourself
- What is the difference between a parameter and an argument?
- What does a function return if no
return statement is present? - Which function type is hoisted: declaration or expression?
- Write an arrow function that takes two numbers and returns their sum.
Answers: 1) Parameters are the named placeholders in the definition; arguments are the actual values passed at call time. 2) undefined. 3) Only declarations are hoisted. 4) const sum = (a, b) => a + b;
Summary
- Functions are defined once (declaration, expression, or arrow) and invoked by calling their name with ().
- Parameters are placeholders; arguments are the actual values sent in.
- return sends a value back to the caller and stops execution; omitting it returns undefined.
- Only function declarations are hoisted; expressions and arrow functions must be defined before use.
- Variables inside functions are local — invisible and inaccessible from outside.
One-Liner Revision
A function is defined once (via declaration, expression, or arrow syntax) and invoked by name; it optionally accepts parameters, performs a task, and returns a value.
1.13 Built-in Objects
Core Definition
Built-in objects in JavaScript are pre-constructed objects provided by the language itself, available in any JavaScript environment without importing anything. They supply ready-made properties and methods for common programming tasks: number handling, string manipulation, mathematical calculations, type conversion, and more.
You do not have to code a square-root function from scratch. JavaScript ships with Math.sqrt(), parseInt(), and dozens of other tools already built in. Built-in objects are like a pre-stocked toolbox that comes with the language — open it and use what you need.
Detailed Explanation
1. String Object
Wraps string primitives and provides methods for searching, extracting, transforming, and testing text.
Method What It Does Example Output length Number of characters "Hello".length 5 toUpperCase() Convert to uppercase "hello".toUpperCase() "HELLO" toLowerCase() Convert to lowercase "HELLO".toLowerCase() "hello" indexOf(s) First index of substring s "hello".indexOf("l") 2 includes(s) Returns true if s is found "hello".includes("ell") true slice(a, b) Extract from index a to b-1 "hello".slice(1, 3) "el" substring(a, b) Extract from a to b (no negatives) "hello".substring(0, 3) "hel" replace(a, b) Replace first match of a with b "hello".replace("l", "r") "herlo" split(sep) Split into array at separator "a,b,c".split(",") ["a","b","c"] trim() Remove leading/trailing whitespace " hi ".trim() "hi" charAt(i) Character at index i "hello".charAt(0) "h" startsWith(s) Checks if string starts with s "hello".startsWith("he") true
2. Number Object
Provides utilities for converting, checking, and formatting numbers.
let n = 3.14159;n.toFixed(2); n.toPrecision(4); Number("42"); Number(true); Number(false); Number("abc"); Number.isNaN(NaN); Number.isInteger(5); Number.isInteger(5.5); Number.MAX_VALUE; Number.MIN_VALUE; 3. Math Object
A static object (never instantiated with new) with mathematical constants and utility methods.
Property / Method What It Returns Example Output Math.PI π (3.14159...) Math.PI 3.14159... Math.E Euler's number (2.718...) Math.E 2.71828... Math.abs(x) Absolute value of x Math.abs(-7) 7 Math.sqrt(x) Square root of x Math.sqrt(16) 4 Math.pow(x, y) x raised to the power y Math.pow(2, 8) 256 Math.floor(x) Round down to nearest integer Math.floor(4.9) 4 Math.ceil(x) Round up to nearest integer Math.ceil(4.1) 5 Math.round(x) Round to nearest integer Math.round(4.5) 5 Math.max(a, b, ...) Largest of given values Math.max(3, 9, 1) 9 Math.min(a, b, ...) Smallest of given values Math.min(3, 9, 1) 1 Math.random() Random float in [0, 1) Math.random() e.g. 0.73 Math.trunc(x) Integer part (no rounding) Math.trunc(4.9) 4
Generating a random integer in a range:
let rand = Math.floor(Math.random() * 10) + 1;console.log(rand); 4. Boolean Object
Wraps a primitive boolean. Rarely used as an object directly, but its underlying concepts — truthy and falsy — are critical throughout JavaScript.
false, 0, "", null, undefined, NaNBoolean(0); Boolean(""); Boolean("0"); Boolean([]); 5. Global Utility Functions
These are not methods of an object, but built-in functions available anywhere:
Function Purpose Example Output parseInt(s) Parse string as integer parseInt("42px") 42 parseFloat(s) Parse string as float parseFloat("3.14abc") 3.14 isNaN(v) True if v is NaN isNaN("hello") true isFinite(v) True if v is a finite number isFinite(1/0) false String(v) Convert v to string String(100) "100" Number(v) Convert v to number Number("99") 99
Common Mistake
Two frequent errors: (1) writing new Math() — Math is not a constructor, it is a static object used directly as Math.sqrt(). (2) Assuming isNaN("hello") returns false — it returns true because the string cannot be coerced to a number. Always use Number.isNaN() instead of the global isNaN() for stricter, more predictable results.
Test Yourself
- What does
"JavaScript".slice(0, 4) return? - Write the expression to generate a random integer between 1 and 6 (like a dice roll).
- What is the difference between
Math.floor() and Math.ceil()? - What does
parseInt("50abc") return?
Answers: 1) "Java". 2) Math.floor(Math.random() * 6) + 1. 3) floor rounds down to the nearest integer; ceil rounds up. 4) 50 — parseInt reads leading numeric characters and stops at the first non-numeric character.
Summary
- Built-in objects are pre-built tools requiring no import: String, Number, Math, Boolean, and global functions.
- String provides length, slice, replace, split, trim, toUpperCase, indexOf, and more.
- Math is a static object — never use new Math() — with abs, sqrt, pow, floor, ceil, round, random.
- Global utilities like parseInt, parseFloat, isNaN, and Number handle type conversion.
- Empty array [] and "0" are truthy; 0, "", null, undefined, NaN, and false are falsy.
One-Liner Revision
JavaScript's built-in objects (String, Number, Math) and global functions (parseInt, isNaN) provide ready-made utilities for text, numbers, and math without any setup.
1.14 Date Object
Core Definition
The JavaScript Date object is a built-in object that stores and manipulates dates and times. It represents a single point in time as the number of milliseconds elapsed since the Unix Epoch (January 1, 1970, 00:00:00 UTC), and exposes methods to read, set, and format date-time components.
Every moment in JavaScript's concept of time is secretly a very large number — the count of milliseconds since midnight on 1 January 1970. The Date object wraps that number and gives you human-friendly methods to work with years, months, days, hours, and minutes.
Detailed Explanation
Creating Date Objects:
let now = new Date(); let d1 = new Date("2025-01-15"); let d2 = new Date(2025, 0, 15); let d3 = new Date(2025, 0, 15, 10, 30, 0); let epoch = new Date(0); console.log(now.toString()); Important: In the constructor, months are zero-indexed. January = 0, February = 1, ... December = 11.
Getting Date Components (Getters):
Method What It Returns Example Output getFullYear() 4-digit year 2025 getMonth() Month (0–11) 5 (for June) getDate() Day of month (1–31) 23 getDay() Day of week (0=Sun, 6=Sat) 1 (Monday) getHours() Hour (0–23) 14 getMinutes() Minutes (0–59) 30 getSeconds() Seconds (0–59) 45 getMilliseconds() Milliseconds (0–999) 500 getTime() Milliseconds since epoch 1750000000000
Setting Date Components (Setters):
let d = new Date();d.setFullYear(2030);d.setMonth(11); d.setDate(25);console.log(d); Formatting and Displaying Dates:
let d = new Date();d.toString(); d.toDateString(); d.toTimeString(); d.toLocaleDateString(); d.toLocaleTimeString(); d.toISOString(); Practical Example — Age Calculator:
function calculateAge(birthYear) { let currentYear = new Date().getFullYear(); return currentYear - birthYear;}console.log(calculateAge(2000)); Date.now(): a static method returning the current timestamp in milliseconds — no new Date() needed. Useful for measuring elapsed time.
let start = Date.now();let elapsed = Date.now() - start;console.log("Elapsed: " + elapsed + "ms");
Common Mistake
Months are zero-indexed in the Date constructor but day-of-month (getDate()) is 1-indexed. This asymmetry catches everyone: new Date(2025, 6, 1) is July 1, not June 1. Also, getDay() returns the weekday (0=Sunday), not the day of the month — that is getDate(). These two are among the most common interview and exam confusion points.
Test Yourself
- What does
new Date(2025, 0, 1) represent? - What is the difference between
getDate() and getDay()? - Write code to display only the current year in the console.
- What does
getTime() return?
Answers: 1) January 1, 2025 (month index 0 = January). 2) getDate() returns day of month (1–31); getDay() returns day of week (0=Sun to 6=Sat). 3) console.log(new Date().getFullYear()); 4) Milliseconds since the Unix Epoch (Jan 1, 1970).
Summary
- new Date() creates a date object representing a moment in time as milliseconds since Unix Epoch.
- Months in the constructor are 0-indexed (Jan = 0, Dec = 11).
- Getters: getFullYear(), getMonth(), getDate(), getDay(), getHours(), getTime().
- Setters: setFullYear(), setMonth(), setDate() modify the stored date.
- Date.now() returns the current timestamp (ms) without creating an object.
One-Liner Revision
The Date object stores time as milliseconds since Jan 1, 1970; months are 0-indexed in its constructor; use getFullYear/Month/Date for reading and setters for modification.
1.15 Interacting With The Browser — Windows and Frames
Core Definition
The Window object is the top-level global object in a browser environment representing the browser's open window or tab. It provides properties and methods to control the browser window, display dialog boxes, manage timing, and navigate between URLs. A frame (via <iframe>) is an embedded sub-window within a page, also represented as a Window object.
Imagine the browser window as the stage of a theater. The Window object is the stage manager — it controls what is shown, can open new curtains (windows/popups), set timers for scene changes, and communicate between the main stage and smaller side stages (frames).
Detailed Explanation
1. Window Dialog Methods
These three methods pause script execution and display a browser dialog box:
alert("This is a warning!");let result = confirm("Are you sure you want to delete?");if (result) { console.log("Deleted.");} else { console.log("Cancelled.");}let name = prompt("Enter your name:", "Default Value");console.log("Hello, " + name);
2. Window Properties
Property Returns window.innerWidth Width of the viewport in pixels window.innerHeight Height of the viewport in pixels window.outerWidth Total browser window width (including chrome) window.screenX / screenY Browser window position on screen window.location URL object — read or change the current URL window.document The Document object of the current page window.history Browser history object window.navigator Browser info (name, version, OS)
3. Window Navigation and Control
let newWin = window.open("https://example.com", "_blank", "width=600,height=400");newWin.close();window.location.href = "https://example.com";window.location.reload();window.history.back();window.history.forward();
4. Timing Functions
These are technically window methods, used to schedule code execution:
let id1 = setTimeout(function() { console.log("Runs after 2 seconds");}, 2000);let id2 = setInterval(function() { console.log("Runs every 1 second");}, 1000);clearTimeout(id1);clearInterval(id2);
5. Frames and iframes
An <iframe> (inline frame) embeds an external document within the current page. Each iframe has its own Window object, accessible via window.frames[i] or by the iframe element's contentWindow property.
<iframe src="child.html" name="myFrame" id="fr1"></iframe><script> let frameWin = document.getElementById("fr1").contentWindow; frameWin.document.body.style.backgroundColor = "lightblue"; window.frames["myFrame"].location.href = "newpage.html";</script>
Common Mistake
Many browsers block window.open() when it is not triggered by a direct user action (like a click). Calling it on page load or inside a timer will likely be caught by the popup blocker and silently fail. Always open windows inside user event handlers. Also, iframes from a different domain are subject to the Same-Origin Policy — JavaScript cannot access their content from the parent page.
Summary
- The Window object is the global browser object providing dialog methods (alert, confirm, prompt).
- Key properties: innerWidth/Height, location, document, history, navigator.
- window.open() creates a new tab/window; window.location.href changes the URL.
- setTimeout runs code once after a delay; setInterval runs it repeatedly.
- Iframes embed sub-windows; each has its own Window, accessible via contentWindow.
One-Liner Revision
The Window object controls the browser tab via dialogs, navigation, timing functions (setTimeout/setInterval), and provides access to embedded frames via iframes.
1.16 Document Object Model (DOM)
Core Definition
The Document Object Model (DOM) is a cross-platform, language-independent programming interface that represents an HTML or XML document as a tree of objects. Each HTML element becomes a node in this tree, and JavaScript can access, modify, add, or remove any node, enabling dynamic, real-time updates to the page without reloading.
When the browser loads an HTML file, it does not just display it — it builds a family tree out of it. The <html> element is the root, <head> and <body> are its children, and every tag inside is a branch. The DOM is that tree. JavaScript interacts with the page by navigating and editing that tree.
Detailed Explanation
DOM Tree Structure:
Document └── html ├── head │ └── title → "My Page" └── body ├── h1 → "Hello" └── p → "World"
1. Selecting / Accessing Elements
Method Selects Returns getElementById("id") Single element by id attribute Element or null getElementsByClassName("cls") All elements with class HTMLCollection (live) getElementsByTagName("tag") All elements of given tag HTMLCollection (live) querySelector("selector") First element matching CSS selector Element or null querySelectorAll("selector") All elements matching CSS selector NodeList (static)
let heading = document.getElementById("title");let boxes = document.querySelectorAll(".box");let firstP = document.querySelector("p");
2. Modifying Element Content
let el = document.getElementById("demo");el.innerHTML = "<strong>Bold Text</strong>"; el.textContent = "Plain text only"; el.innerText = "Visible text"; 3. Modifying Styles and Attributes
let box = document.getElementById("box");box.style.color = "red";box.style.backgroundColor = "yellow";box.style.fontSize = "20px";box.setAttribute("class", "highlight");box.getAttribute("id"); box.removeAttribute("class");box.classList.add("active"); box.classList.remove("active"); box.classList.toggle("hidden"); 4. Creating and Inserting Elements
let newPara = document.createElement("p");newPara.textContent = "This is a new paragraph.";newPara.setAttribute("class", "info");document.body.appendChild(newPara); let parent = document.getElementById("container");parent.insertBefore(newPara, parent.firstChild); 5. Removing Elements
let el = document.getElementById("old-section");el.remove(); let parent = document.getElementById("wrapper");parent.removeChild(el);
6. Traversing the DOM Tree
let el = document.getElementById("item");el.parentNode; el.childNodes; el.children; el.firstElementChild; el.lastElementChild; el.nextElementSibling; el.previousElementSibling; Let's Break It Down
Consider a government organizational chart: the President is the root, ministries are children, departments are their children, and so on. The DOM works identically — the document is the root, and every HTML element is a node on the chart. JavaScript is the HR manager who can change anyone's title (textContent), move departments around (appendChild, insertBefore), fire people (remove()), or hire new ones (createElement).
Common Mistake
Using innerHTML to insert user-provided text is a major security vulnerability called Cross-Site Scripting (XSS) — malicious HTML or script tags in the input execute in the page. Always use textContent for plain text. Also, getElementsByClassName returns a live HTMLCollection — if you add or remove elements that match the class, the collection updates automatically, which can cause infinite loops if you are iterating and modifying simultaneously.
Test Yourself
- What is the difference between
innerHTML and textContent? - Which method selects a single element by its CSS selector?
- Write code to change the background color of the element with id "header" to blue.
- What is the difference between
querySelector and querySelectorAll?
Answers: 1) innerHTML parses and renders HTML tags; textContent inserts raw text only (no HTML rendering). 2) querySelector(). 3) document.getElementById("header").style.backgroundColor = "blue"; 4) querySelector returns the first matching element; querySelectorAll returns all matching elements as a NodeList.
Summary
- The DOM represents the HTML page as a navigable tree of node objects.
- Selection: getElementById, querySelector (single), querySelectorAll (all).
- Content: innerHTML (parses HTML), textContent (plain text only, safer).
- Attributes and styles: setAttribute, classList.add/remove/toggle, el.style.property.
- Creating nodes: createElement + appendChild/insertBefore; deleting: el.remove().
One-Liner Revision
The DOM is the browser's tree representation of HTML; JavaScript traverses and mutates it via selection (getElementById, querySelector), modification (innerHTML, style), and creation (createElement, appendChild).
1.17 Event Handling
Core Definition
Event handling is the mechanism by which JavaScript responds to user actions or browser events — such as clicks, key presses, mouse movements, or form submissions — by executing a designated event handler (callback function) when the event fires on a specific element.
A webpage without event handling is a static brochure. Event handling is what makes the page respond: the button highlights when you hover it, the form shows an error when you submit incorrectly, the image changes when you click it. Every interaction is an event; the function that runs in response is the handler.
Detailed Explanation
Three Ways to Attach Event Handlers:
Method 1: Inline HTML Attribute (oldest)
<button onclick="alert('Clicked!')">Click Me</button><input type="text" onkeyup="validateField(this)">
Direct but mixes HTML and JS — hard to maintain. Useful for simple demos.
Method 2: DOM Property (on-event)
let btn = document.getElementById("myBtn");btn.onclick = function() { alert("Button clicked!");};btn.onmouseover = function() { btn.style.color = "red";};
Cleaner separation, but allows only one handler per event per element — assigning a new one replaces the old one.
Method 3: addEventListener (modern, recommended)
let btn = document.getElementById("myBtn");btn.addEventListener("click", function() { alert("Clicked via addEventListener!");});btn.addEventListener("click", function() { console.log("A second handler on the same click event!");});Removing an Event Listener:
function handleClick() { console.log("Clicked");}btn.addEventListener("click", handleClick);btn.removeEventListener("click", handleClick); The Event Object
When an event fires, the browser passes an Event object to the handler automatically. It contains information about the event.
document.addEventListener("keydown", function(event) { console.log("Key pressed: " + event.key); console.log("Key code: " + event.keyCode);});document.addEventListener("click", function(event) { console.log("Clicked at X: " + event.clientX + ", Y: " + event.clientY); console.log("Target element: " + event.target.tagName);});
Common Event Types:
Category Event Fires When... Mouse click Mouse button pressed and released Mouse dblclick Double-clicked Mouse mouseover Mouse enters element Mouse mouseout Mouse leaves element Mouse mousemove Mouse moves over element Keyboard keydown Key pressed (fires first) Keyboard keyup Key released Keyboard keypress Key held (deprecated) Form submit Form submitted Form change Input value changed and lost focus Form input Value changes in real time Form focus / blur Element gains / loses focus Page load Page and all resources fully loaded Page DOMContentLoaded HTML parsed (before images/CSS) Page resize Browser window resized Page scroll Page is scrolled
event.preventDefault() and event.stopPropagation():
document.getElementById("myForm").addEventListener("submit", function(event) { event.preventDefault(); console.log("Form validation running...");});document.getElementById("child").addEventListener("click", function(event) { event.stopPropagation(); });
Event Propagation — Bubbling and Capturing:
When an event fires on a nested element, it travels through the DOM in two phases:
- Capturing phase: from document root down to the target element.
- Bubbling phase: from the target element back up to the root.
By default, addEventListener operates in the bubbling phase (third parameter false). Pass true to use the capturing phase.
Common Mistake
Forgetting event.preventDefault() on form submission is the number one form-related bug — the page reloads before validation can reject bad data. Also, passing an anonymous function to removeEventListener does nothing, because each function literal creates a new object reference. To remove a listener, the exact same named function reference must be passed to both add and remove.
Test Yourself
- What advantage does addEventListener have over the on-event property method?
- What does
event.preventDefault() do? - What is event bubbling?
- Write code that logs a message when a button with id "btn" is clicked.
Answers: 1) It allows multiple handlers on the same event — on-event property overwrites previous handlers. 2) It cancels the browser's default action for the event (e.g., prevents form submission or link navigation). 3) After an event fires on a target element, it automatically propagates upward through parent elements until it reaches the document root. 4) document.getElementById("btn").addEventListener("click", () => console.log("Clicked!"));
Summary
- Events are user/browser actions; handlers are functions that respond to them.
- Three attachment methods: inline HTML, on-event property, addEventListener (recommended).
- addEventListener supports multiple handlers per event; on-event overwrites the previous.
- The Event object carries information: event.target, event.key, event.clientX, etc.
- preventDefault() blocks default browser action; stopPropagation() stops bubbling.
One-Liner Revision
addEventListener is the preferred way to attach event handlers; the Event object provides context; preventDefault() cancels defaults, and stopPropagation() halts bubbling.
1.18 Forms
Core Definition
An HTML form is a container for user input elements (text fields, checkboxes, radio buttons, dropdowns, buttons) that collects data to be submitted to a server or processed by JavaScript. JavaScript interacts with form elements via the DOM to read, validate, and manipulate their values before or instead of server submission.
Forms are the primary communication channel between users and web applications — login screens, search boxes, registration pages, feedback forms. JavaScript gives you control over every keystroke, every selection, and the submission action itself, enabling real-time validation and smarter user experiences.
Detailed Explanation
HTML Form Basics:
<form id="regForm" action="/submit" method="POST"> <label for="username">Name:</label> <input type="text" id="username" name="username" placeholder="Enter name"> <label for="email">Email:</label> <input type="email" id="email" name="email"> <label for="age">Age:</label> <input type="number" id="age" name="age" min="1" max="120"> <label> <input type="checkbox" id="agree" name="agree"> I agree to terms </label> <input type="submit" value="Register"></form>
Accessing Form Elements with JavaScript:
let name = document.getElementById("username").value;let form = document.getElementById("regForm");let email = form.elements["email"].value;let agreed = document.getElementById("agree").checked; let radios = document.querySelectorAll('input[name="gender"]');let selectedGender;radios.forEach(r => { if (r.checked) selectedGender = r.value; });
Dropdown (select) Elements:
<select id="course"> <option value="">-- Select Course --</option> <option value="bca">BCA</option> <option value="bba">BBA</option></select><script>let sel = document.getElementById("course");console.log(sel.value); console.log(sel.selectedIndex); console.log(sel.options[sel.selectedIndex].text); </script>
Handling Form Submission with JavaScript:
document.getElementById("regForm").addEventListener("submit", function(event) { event.preventDefault(); let username = document.getElementById("username").value.trim(); let email = document.getElementById("email").value.trim(); if (username === "") { alert("Name is required!"); return; } if (!email.includes("@")) { alert("Enter a valid email address!"); return; } console.log("Form submitted:", username, email); });
Dynamically Modifying Forms:
document.getElementById("username").value = "Ram";document.getElementById("age").disabled = true;document.getElementById("username").focus();document.getElementById("regForm").reset();
Common Mistake
Reading element.value without calling .trim() first causes validation to pass for input containing only spaces. Always trim before checking for empty strings. Also, forgetting event.preventDefault() means the page reloads on submission before any validation code can run — the most common form bug in beginner projects.
Test Yourself
- How do you read the value from a text input with id "email"?
- How do you check whether a checkbox is selected?
- Why is
event.preventDefault() important in a form submit handler? - What method resets all form fields to their default values?
Answers: 1) document.getElementById("email").value. 2) document.getElementById("checkboxId").checked returns true/false. 3) It prevents the default page reload, giving JavaScript a chance to validate before submission. 4) formElement.reset().
Summary
- Forms collect user input; JavaScript reads values via .value and .checked properties.
- Always trim() string values before validation to catch whitespace-only inputs.
- Attach a submit event listener and call event.preventDefault() to control submission.
- Form fields can be disabled, focused, reset, or pre-filled programmatically via the DOM.
One-Liner Revision
JavaScript reads and validates form data via .value and .checked properties; event.preventDefault() on submit blocks page reload, enabling client-side validation before any server call.
1.19 Cookies
Core Definition
A cookie is a small piece of text data (up to 4 KB) that the browser stores on the user's computer, associated with a specific domain. Cookies are set and read via document.cookie in JavaScript and are automatically sent to the server with every HTTP request to the matching domain, making them the classic mechanism for session management, user preferences, and tracking.
Websites are stateless by nature — every page request is a stranger. Cookies are how a website remembers who you are between visits. Your login session, language preference, and shopping cart persistence all typically rely on cookies stored in your browser.
Detailed Explanation
Setting a Cookie:
document.cookie = "username=Ram";document.cookie = "username=Ram; expires=Thu, 31 Dec 2025 23:59:59 UTC; path=/";document.cookie = "theme=dark; path=/";document.cookie = "lang=en; path=/";document.cookie = "font=large; path=/";
Important: document.cookie = does not overwrite all existing cookies. Each assignment adds or updates one cookie at a time, identified by its name.
Reading Cookies:
console.log(document.cookie);function getCookie(name) { let cookies = document.cookie.split("; "); for (let c of cookies) { let [key, value] = c.split("="); if (key.trim() === name) return value; } return null;}console.log(getCookie("username")); console.log(getCookie("missing")); Deleting a Cookie:
Set the cookie's expires to a date in the past. The browser immediately discards it.
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
Cookie Attributes:
Attribute Purpose expires Expiry date/time in UTC. Without it, cookie is a session cookie (deleted on browser close). max-age Lifetime in seconds. 0 or negative deletes the cookie immediately. path URL path the cookie is valid for. "/" means the whole site. domain Which domain can access the cookie. Defaults to the setting domain. secure Cookie is only sent over HTTPS connections. HttpOnly Set server-side; JS cannot read HttpOnly cookies (protects against XSS). Not settable via JS.
Cookie Limitations:
- Maximum size: ~4 KB per cookie.
- Typically 20–50 cookies per domain limit.
- Cookies are sent with every HTTP request — even for images and scripts — adding network overhead.
- Modern alternatives:
localStorage (5–10 MB, not sent to server) and sessionStorage (tab-lifetime).
Common Mistake
document.cookie = "name=value" is easily mistaken for setting the entire cookie string. In reality, it adds or updates one cookie while leaving all others intact. Reading document.cookie returns ALL cookies as a single string — you must parse it to extract one value. Never store sensitive data (passwords, credit card numbers) in cookies; they are readable by JavaScript and transmitted in HTTP headers.
Test Yourself
- How do you set a cookie that expires in the future?
- What is a session cookie, and when is it deleted?
- How do you delete a cookie using JavaScript?
- What does
document.cookie return when read?
Answers: 1) Include the expires=date attribute when setting the cookie. 2) A session cookie has no expires attribute and is deleted when the browser is closed. 3) Set the same cookie with an expires date in the past. 4) All cookies for the current domain as a single semicolon-separated string of name=value pairs.
Summary
- Cookies store small text data (max 4 KB) in the browser, tied to a domain.
- Set via document.cookie = "name=value; expires=...; path=/"; each assignment adds/updates one cookie.
- Read by parsing the full document.cookie string; delete by setting a past expiry.
- Key attributes: expires, max-age, path, domain, secure, HttpOnly.
- Session cookies vanish on browser close; persistent cookies last until their expiry date.
One-Liner Revision
Cookies are browser-stored key-value strings (4 KB max) managed via document.cookie; setting an expires date creates a persistent cookie, while omitting it creates a session cookie deleted on browser close.
1.20 Handling Regular Expressions
Core Definition
A regular expression (regex) is a sequence of characters that defines a search pattern. In JavaScript, a regex is represented as a RegExp object and is used to test, search, extract, or replace substrings within strings based on defined pattern rules rather than exact text matches.
Checking whether a string is a valid email, phone number, or zip code with a bunch of if statements would take 20 lines and still miss edge cases. A regular expression handles it in one line by specifying exactly what pattern the string must match — like a very precise template the input is tested against.
Detailed Explanation
Creating Regular Expressions:
let pattern1 = /hello/;let pattern2 = /hello/i; let pattern3 = /hello/gi; let pattern4 = new RegExp("hello", "i");
Regex Flags:
Flag Name Effect g Global Find all matches, not just the first i Case-insensitive Match regardless of upper/lower case m Multiline ^ and $ match start/end of each line
Regex Metacharacters and Syntax:
Pattern Matches Example . Any single character (except newline) /h.t/ matches "hot", "hit" \d Any digit (0–9) /\d+/ matches "123" \D Any non-digit /\D+/ matches "abc" \w Word character [a-zA-Z0-9_] /\w+/ matches "hello_1" \W Non-word character /\W/ matches "@", "!" \s Whitespace (space, tab, newline) /\s+/ matches spaces \S Non-whitespace /\S+/ matches non-spaces ^ Start of string /^Hello/ matches start $ End of string /end$/ matches at end * 0 or more occurrences /ab*c/ matches "ac", "abc", "abbc" + 1 or more occurrences /ab+c/ matches "abc", "abbc" ? 0 or 1 occurrence /ab?c/ matches "ac", "abc" {n} Exactly n occurrences /\d{4}/ matches "2025" {n,m} Between n and m occurrences /\d{2,4}/ matches 2 to 4 digits [abc] Any one of a, b, c /[aeiou]/ matches any vowel [^abc] Any character NOT in the set /[^0-9]/ matches non-digits (ab) Capturing group /(ab)+/ matches "ababab" a|b a or b /cat|dog/ matches "cat" or "dog"
JavaScript Regex Methods:
let str = "Hello World 123";let pattern = /\d+/;/\d+/.test(str); /^Hello/.test(str); str.match(/\d+/); str.match(/\d+/g); "aabbcc".match(/[a-c]+/g); str.replace(/World/, "JavaScript"); "aabbcc".replace(/b/g, "X"); str.search(/\d+/); str.search(/\d+/); "one1two2three".split(/\d/); Practical Regex Patterns (commonly tested):
let emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;emailRegex.test("user@example.com"); emailRegex.test("notanemail"); let phoneRegex = /^\d{10}$/;phoneRegex.test("9841234567"); phoneRegex.test("984123"); let passRegex = /^(?=.*\d).{8,}$/;passRegex.test("pass1234"); passRegex.test("password"); let userRegex = /^[a-zA-Z0-9_]{3,16}$/;userRegex.test("ram_95"); userRegex.test("r!"); Common Mistake
Forgetting anchors ^ and $ in validation patterns is a critical error: without them, /\d{10}/ matches any string containing 10 consecutive digits — so "abc1234567890xyz" would pass a phone number check. Always anchor validation patterns with ^ at the start and $ at the end to match the entire input. Also, the . metacharacter matches any character including letters and digits, not a literal period — to match a real dot, escape it as \.
Test Yourself
- What does
/^\d{10}$/ match? - What is the difference between
test() and match()? - Write a regex that checks if a string contains only letters (a–z, A–Z).
- What does the
g flag do in a regex?
Answers: 1) Exactly a 10-digit number string (anchored start and end). 2) test() is a RegExp method returning true/false; match() is a String method returning an array of matches (or null). 3) /^[a-zA-Z]+$/. 4) Makes the pattern find all matches in the string, not just the first one.
Summary
- A regex is a character pattern used to search, validate, or replace text.
- Created as a literal /pattern/flags or via new RegExp("pattern", "flags").
- Key metacharacters: \d (digit), \w (word char), . (any char), ^ (start), $ (end), +, *, ?, {n,m}.
- Methods: test() (true/false), match() (array), replace() (string), search() (index), split() (array).
- Always anchor validation patterns with ^ and $ to test the full input, not a substring.
One-Liner Revision
Regular expressions define character patterns for searching and validating text; use test() to check a match, match() to extract it, and replace() to substitute — always anchor validation with ^ and $.
1.21 Client Side Validations
Core Definition
Client-side validation is the process of verifying user input in the browser, using JavaScript (and optionally HTML5 attributes), before the data is sent to the server. It provides immediate feedback to the user, prevents unnecessary server round-trips for obviously invalid data, and improves the overall form user experience.
Imagine submitting a job application form and waiting 10 seconds for the server to tell you that you forgot to enter your email. Client-side validation catches that in milliseconds, right in the browser, before anything leaves your device. It is the fast, friendly first guard — though server-side validation must always remain the final authority.
Detailed Explanation
Why Client-Side Validation (and its limits):
- Instant feedback: Errors appear immediately without a page reload or server request.
- Reduced server load: Blatantly invalid data never reaches the server.
- Better UX: Inline error messages guide the user as they fill the form.
- NOT a security boundary: JavaScript can be disabled or bypassed. A malicious user can send any data directly to the server. Server-side validation is always mandatory. Client-side is a UX layer, not a security layer.
HTML5 Built-in Validation Attributes (no JavaScript required):
Attribute Effect Example required Field must not be empty <input required> type="email" Must match basic email format <input type="email"> type="number" Must be numeric <input type="number"> min / max Numeric minimum/maximum value min="1" max="100" minlength / maxlength String length constraints minlength="6" pattern Must match a regex pattern pattern="[0-9]{10}"
JavaScript Validation — Complete Working Example:
<form id="regForm"> <input type="text" id="name" placeholder="Full Name"> <span id="nameErr" style="color:red;"></span><br> <input type="text" id="email" placeholder="Email Address"> <span id="emailErr" style="color:red;"></span><br> <input type="password" id="pass" placeholder="Password"> <span id="passErr" style="color:red;"></span><br> <input type="text" id="phone" placeholder="Phone (10 digits)"> <span id="phoneErr" style="color:red;"></span><br> <button type="submit">Register</button></form><script>document.getElementById("regForm").addEventListener("submit", function(e) { e.preventDefault(); let isValid = true; let name = document.getElementById("name").value.trim(); if (name === "") { document.getElementById("nameErr").textContent = "Name is required."; isValid = false; } else if (name.length < 3) { document.getElementById("nameErr").textContent = "Name must be at least 3 characters."; isValid = false; } else { document.getElementById("nameErr").textContent = ""; } let email = document.getElementById("email").value.trim(); let emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (!emailRegex.test(email)) { document.getElementById("emailErr").textContent = "Enter a valid email address."; isValid = false; } else { document.getElementById("emailErr").textContent = ""; } let pass = document.getElementById("pass").value; if (pass.length < 8) { document.getElementById("passErr").textContent = "Password must be at least 8 characters."; isValid = false; } else { document.getElementById("passErr").textContent = ""; } let phone = document.getElementById("phone").value.trim(); let phoneRegex = /^\d{10}$/; if (!phoneRegex.test(phone)) { document.getElementById("phoneErr").textContent = "Phone number must be exactly 10 digits."; isValid = false; } else { document.getElementById("phoneErr").textContent = ""; } if (isValid) { alert("Form submitted successfully!"); }});</script>
Real-Time Inline Validation (on input event):
document.getElementById("email").addEventListener("input", function() { let val = this.value.trim(); let errEl = document.getElementById("emailErr"); let emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; errEl.textContent = emailRegex.test(val) ? "" : "Invalid email format";});
Common Validation Checks and Their Regex Patterns:
Field Rule Regex Required text Not empty after trim value.trim() !== "" Email Contains @ and domain /^[^\s@]+@[^\s@]+\.[^\s@]+$/ Phone (NP) Exactly 10 digits /^\d{10}$/ Password Min 8 chars, 1 digit /^(?=.*\d).{8,}$/ Username 3–16 alphanumeric/_ /^[a-zA-Z0-9_]{3,16}$/ Zip / PIN code Exactly 5 digits (US) /^\d{5}$/ URL Starts with http/https /^https?:\/\/.+/
Common Mistake
Treating client-side validation as a security control is a fundamental error. Any technically inclined user can open browser DevTools, disable JavaScript, or craft a raw HTTP request — bypassing all your JavaScript validation entirely. Client-side validation exists for user experience only. Always re-validate every field on the server before using the data or storing it in a database.
Test Yourself
- What is the difference between client-side and server-side validation?
- Why must server-side validation always be present even if client-side validation exists?
- Write a JavaScript function that returns true if a phone number is exactly 10 digits.
- What HTML5 attribute makes a form field mandatory without any JavaScript?
Answers: 1) Client-side runs in the browser for instant UX feedback; server-side runs on the server as the authoritative security check. 2) JavaScript can be disabled or bypassed — client-side validation provides no security guarantee. 3) function isValidPhone(p) { return /^\d{10}$/.test(p); } 4) The required attribute.
Summary
- Client-side validation checks form data in the browser for immediate feedback before submission.
- HTML5 attributes (required, pattern, min, max, minlength) provide zero-JS validation.
- JavaScript validation uses the submit event + event.preventDefault() + conditional checks with regex.
- Real-time validation uses the input event to give feedback as the user types.
- Client-side validation is a UX tool only — server-side validation is always the security boundary.
One-Liner Revision
Client-side validation checks inputs in the browser for instant UX feedback, but server-side validation is always required for security since JavaScript can be bypassed.
Unit 1 — Whole Chapter Summary
Topic Core Takeaway 1.1 Introduction to JavaScript Lightweight, interpreted, event-driven scripting language that runs in the browser to add interactive behavior to HTML pages. 1.2 Need for Client-Side Scripting Eliminates unnecessary server round-trips; enables instant validation, UI feedback, and dynamic content updates locally in the browser. 1.3 Formatting & Coding Conventions camelCase for variables/functions, PascalCase for classes, ALL_CAPS for constants; always use semicolons and consistent indentation. 1.4 JavaScript Files External .js files are linked via <script src="">, enabling code reuse, browser caching, and clean separation from HTML. 1.5 Comments 1.6 Embedding JavaScript Three methods: inline event attributes, internal <script> block, external file — external is the recommended best practice. 1.7 Script Tag defer runs post-parse in order; async runs immediately on download in any order; scripts with src must be empty. 1.8 NoScript Tag Provides fallback HTML content displayed only when JavaScript is unavailable or disabled. 1.9 Operators Arithmetic, assignment, comparison (always prefer ===), logical, and ternary operators; typeof returns the type as a string. 1.10 Control Structures if/else if/else for range decisions; switch for exact-value matching; for/while/do...while for repetition; break exits, continue skips. 1.11 Arrays & forEach Zero-indexed ordered collections; forEach iterates every element via a callback but cannot be stopped early with break. 1.12 Functions Defined once (declaration/expression/arrow), invoked by name(); parameters accept arguments; return sends back a value. 1.13 Built-in Objects String, Number, Math (static — never use new), Boolean, plus global functions (parseInt, isNaN) provide ready-made utilities. 1.14 Date Object Stores time as ms since Unix Epoch; months are 0-indexed in the constructor; getFullYear/getMonth/getDate read components. 1.15 Windows & Frames Window is the global browser object; dialog methods are alert/confirm/prompt; setTimeout/setInterval control timing; iframes embed sub-windows. 1.16 Document Object Model The browser's tree of HTML nodes; selected via getElementById/querySelector; content changed via innerHTML or textContent; createElement builds new nodes. 1.17 Event Handling addEventListener attaches multiple handlers per event; the Event object provides context; preventDefault() cancels defaults; stopPropagation() halts bubbling. 1.18 Forms Read values via .value and .checked; always trim() text; use submit + preventDefault() to validate before sending data. 1.19 Cookies 4 KB browser-stored key-value strings; document.cookie adds/updates one cookie per assignment; deleting requires setting a past expiry. 1.20 Regular Expressions Patterns that match text; test() returns true/false; match() returns array; always anchor validation patterns with ^ and $. 1.21 Client-Side Validation Browser-based UX layer for instant feedback; uses submit event + regex; NOT a security boundary — server-side validation is mandatory.
Key Formulas and Points Sheet
Rule / Pattern / Formula Meaning / Use /^[^\s@]+@[^\s@]+\.[^\s@]+$/ Email format validation regex /^\d{10}$/ Exactly 10-digit phone number validation /^(?=.*\d).{8,}$/ Password: min 8 chars, at least 1 digit /^[a-zA-Z0-9_]{3,16}$/ Alphanumeric username, 3–16 chars Math.floor(Math.random() * N) + 1 Random integer from 1 to N (inclusive) new Date().getFullYear() Returns the current 4-digit year element.style.property = "value" Change a CSS property via JS DOM element.addEventListener("event", fn) Attach an event handler (preferred method) event.preventDefault() Cancel the browser's default action for an event document.cookie = "name=value; expires=...; path=/" Set a persistent cookie document.cookie = "name=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/" Delete a cookie == vs === == allows type coercion; === compares value AND type strictly — always use === Months in Date: 0-indexed Jan=0, Feb=1, ... Dec=11 — date (getDate) is 1-indexed Falsy values false, 0, "", null, undefined, NaN — everything else is truthy
Last-Minute Revision Sheet
Concept Trigger Phrase Recall Cue JavaScript interpreted + browser Lightweight, event-driven, object-based, no compilation Client-side scripting need no server trip Instant feedback, reduced load, validation, UI control Coding conventions camel, Pascal, CAPS variables=camelCase, classes=PascalCase, constants=ALL_CAPS External JS file src + .js + cache <script src="file.js"></script> — no code inside if src set Comments Script placement defer vs async defer = ordered post-parse; async = immediate any-order NoScript tag JS disabled fallback Only visible when JS unavailable === vs == strict equality === checks type too; 5 === "5" → false Ternary one-line if-else condition ? valueIfTrue : valueIfFalse typeof null known quirk Returns "object" — historical JS bug do...while runs at least once Body executes before condition is checked Array index zero-based First = [0]; Last = [length - 1] forEach vs for no break in forEach forEach always runs all; use for loop to break early Function hoisting declaration only Expressions/arrows must be defined before use Math object static, no new Math.sqrt(), Math.random(), Math.floor() — never new Math() Date months 0-indexed Jan=0, Dec=11; getDate() is 1-indexed (different!) Window dialogs alert/confirm/prompt alert=message; confirm=yes/no→bool; prompt=input→string setTimeout vs setInterval once vs repeat setTimeout runs once; setInterval repeats until cleared DOM selection query selectors getElementById→one; querySelectorAll→NodeList; getByClass→live innerHTML vs textContent parses vs raw innerHTML renders tags (XSS risk); textContent is safe plain text addEventListener multiple handlers On-event property allows one; addEventListener allows many preventDefault() stop default Prevents form reload, link navigation, etc. stopPropagation() stop bubbling Prevents event from rising to parent elements Form .value always trim() Spaces-only string passes length check without trim Cookies 4 KB browser text document.cookie adds one; past expiry deletes; session=no expiry Regex anchors ^ and $ Without them, pattern matches a substring, not the whole input test() vs match() bool vs array test() on RegExp → true/false; match() on String → array Client-side validation UX not security JS can be bypassed; server must always re-validate


