Unit 1: Client Side Scripting — Continued Notes
1.6 JavaScript Arrow Function
Definition
An arrow function is a shorter way to write a function in JavaScript, introduced in ES6 (ECMAScript 2015), using the => symbol instead of the function keyword.
Arrow functions trim the visual clutter of a regular function — no function keyword, often no return, sometimes no parentheses. They are not just shorthand though; they also behave differently when it comes to this.
Detailed Explanation
In JavaScript, a regular function looks like this:
// Regular function — traditional syntax
function add(a, b) {
return a + b;
}
console.log(add(3, 4)); // Output: 7
An arrow function rewrites this more compactly:
// Arrow function — concise syntax using =>
const add = (a, b) => a + b;
// No 'function' keyword, no 'return', no curly braces for single expression
console.log(add(3, 4)); // Output: 7
Syntax Rules — Step by Step
Step 1 — Full form (with body block): used when there are multiple statements.
const greet = (name) => {
let message = "Hello, " + name;
return message; // 'return' is required when using { }
};
console.log(greet("Anita")); // Output: Hello, Anita
Step 2 — Concise form (single expression): curly braces and return are both dropped. The expression result is returned automatically.
const square = (n) => n * n;
console.log(square(5)); // Output: 25
Step 3 — Single parameter: parentheses around the parameter can be omitted.
const double = n => n * 2;
console.log(double(6)); // Output: 12
Step 4 — No parameters: empty parentheses are required.
const sayHi = () => "Hi there!";
console.log(sayHi()); // Output: Hi there!
Factorial Using Arrow Function (Exam Q — 2022)
Factorial of n (written n!) means: n × (n−1) × (n−2) × ... × 1. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120.
// Arrow function to calculate factorial using recursion
const factorial = (n) => {
if (n === 0 || n === 1) {
return 1; // Base case: 0! = 1, 1! = 1
}
return n * factorial(n - 1); // Recursive call: n! = n × (n-1)!
};
// Test the function
console.log(factorial(5)); // Output: 120
console.log(factorial(0)); // Output: 1
console.log(factorial(7)); // Output: 5040
Arrow functions work with recursion the same way regular functions do. The only difference is syntax.
Key Difference: Arrow Function vs Regular Function
The most important behavioral difference is how this works. Regular functions define their own this based on how they are called. Arrow functions do not have their own this — they inherit it from the surrounding scope.
| Feature | Regular Function | Arrow Function |
|---|---|---|
| Syntax | function name() {} | const name = () => {} |
Has own this | Yes | No (inherits from enclosing scope) |
| Can be used as constructor | Yes (new Func()) | No |
Has arguments object | Yes | No |
| Best for | Methods, constructors | Callbacks, array methods |
| Return (single expression) | Explicit return needed | Implicit return, no return |
Common Mistake
Students write arrow functions with curly braces but forget to add return. When curly braces are present, the implicit return is gone — you must write return explicitly. const f = (x) => { x * 2 } returns undefined. Correct: const f = (x) => { return x * 2; } or const f = (x) => x * 2.
Summary
- Arrow functions use
=>syntax and replace thefunctionkeyword for cleaner, shorter code. - Single-expression arrow functions have implicit return — no need for
returnor curly braces. - Single parameters can omit parentheses; zero parameters require empty
(). - Arrow functions do not have their own
this— they inherit it from the surrounding context. - Arrow functions cannot be used as constructors and have no
argumentsobject.
Test Yourself
- What is arrow function? Write JavaScript code to calculate factorial of given number using arrow function. (2022)
- What is JS arrow function? Explain use of forEach() and map() method in JavaScript. (2026)
- Write an arrow function that accepts a number and returns whether it is even or odd.
Hints:
- Arrow function uses
=>syntax introduced in ES6. Factorial:const factorial = (n) => (n <= 1) ? 1 : n * factorial(n-1);— recursive, base case at 0 or 1. - Arrow function is a concise function syntax using
=>. forEach iterates array, performs action per element, returns undefined. map transforms each element and returns a new array. const checkEvenOdd = n => (n % 2 === 0) ? "Even" : "Odd";
1.7 JavaScript map() Method
Definition
The map() method creates a new array by applying a given function to every element of the original array, leaving the original array unchanged.
map() is a transformer: give it an array and a rule, and it returns a brand-new array where every item has been changed by that rule. The original stays untouched.
Detailed Explanation
Syntax:
// map() syntax
let newArray = originalArray.map(function(element, index, array) {
return transformedElement;
});
// Arrow function shorthand (most common way)
let newArray = originalArray.map(element => transformedElement);
Parameters inside the callback:
element— current item being processed (required)index— position of the current item (optional)array— the original array being iterated (optional)
Code Examples — Step by Step
Example 1 — Double each number:
let numbers = [1, 2, 3, 4, 5];
// map() applies the arrow function to every element
let doubled = numbers.map(n => n * 2);
console.log(doubled); // Output: [2, 4, 6, 8, 10]
console.log(numbers); // Output: [1, 2, 3, 4, 5] — original unchanged
Example 2 — Convert names to uppercase:
let names = ["anita", "rohan", "sita"];
// map() runs toUpperCase() on each string element
let upperNames = names.map(name => name.toUpperCase());
console.log(upperNames); // Output: ["ANITA", "ROHAN", "SITA"]
Example 3 — Extract one property from an array of objects:
let students = [
{ name: "Anita", grade: 85 },
{ name: "Rohan", grade: 72 },
{ name: "Sita", grade: 90 }
];
// map() pulls out only the 'name' property from each object
let studentNames = students.map(student => student.name);
console.log(studentNames); // Output: ["Anita", "Rohan", "Sita"]
forEach() vs map() — Key Difference
| Feature | forEach() | map() |
|---|---|---|
| Returns | undefined (nothing) | A new array |
| Modifies original | Can (if you write code to do it) | Never |
| Use for | Side effects (print, DOM update, sum) | Transforming data into a new array |
| Chainable | No | Yes (can chain .filter(), .reduce()) |
| Return inside callback | Return value is ignored | Return value becomes the new element |
let nums = [1, 2, 3];
// forEach — side effect only, returns undefined
nums.forEach(n => console.log(n * 2)); // Prints 2, 4, 6 but returns nothing
// map — returns a new array
let result = nums.map(n => n * 2);
console.log(result); // [2, 4, 6] — stored in result
Summary
- map() iterates every element of an array and returns a new array with each element transformed.
- The original array is never modified — map() always creates a new one.
- The callback function receives (element, index, array) — element is mandatory, others optional.
- Unlike forEach(), map() returns a value — the new array — making it chainable.
- Use map() when you need a transformed copy; use forEach() when you only need side effects.
Test Yourself
- Explain event handling in JavaScript. Difference between map and forEach method in JavaScript. (2025)
- What is JS arrow function? Explain use of forEach() and map() method in JavaScript. (2026)
- Write a map() function that takes an array of temperatures in Celsius and returns a new array in Fahrenheit (F = C × 9/5 + 32).
Hints:
- forEach: iterates array, runs callback, returns undefined. map: iterates array, returns NEW array of transformed elements. Key difference: map returns a value; forEach does not.
- Arrow function = concise ES6 syntax using
=>. forEach = iterate for side effects. map = iterate and transform, returns new array. let fahrenheit = celsius.map(c => c * 9/5 + 32);
1.8 JavaScript DOM Manipulation
Definition
The Document Object Model (DOM) is a programming interface that represents an HTML document as a tree of objects, allowing JavaScript to read, modify, add, or remove elements and content on a web page dynamically.
The DOM is the bridge between your HTML and JavaScript. When the browser loads an HTML page, it converts every tag into a JavaScript object — a node in a tree. JavaScript can grab any node and change its text, style, attributes, or even delete it or create new ones — all without reloading the page.
Detailed Explanation
When a browser parses this HTML:
<body>
<h1 id="title">Hello World</h1>
<p class="info">Welcome to my page</p>
</body>
It creates a tree where <body> is the parent node, <h1> and <p> are child nodes, and the text inside each is a text node. JavaScript uses the global document object to navigate and change this tree.
Accessing DOM Elements — All Methods
Method 1 — getElementById(): selects one element by its id attribute.
// HTML: <h1 id="title">Hello World</h1>
let heading = document.getElementById("title");
console.log(heading.textContent); // Output: Hello World
Method 2 — getElementsByClassName(): returns an HTMLCollection (array-like list) of all elements with a specific class.
// HTML: <p class="info">First</p> <p class="info">Second</p>
let paras = document.getElementsByClassName("info");
console.log(paras[0].textContent); // Output: First
console.log(paras.length); // Output: 2
Method 3 — getElementsByName(): selects elements by their name attribute (commonly used with form inputs).
// HTML: <input type="text" name="username">
let inputs = document.getElementsByName("username");
console.log(inputs[0].value); // Gets the value typed by the user
Method 4 — querySelector(): returns the first element matching a CSS selector.
// Selects the first paragraph with class "info"
let firstPara = document.querySelector(".info");
// Selects the element with id "title"
let title = document.querySelector("#title");
// Selects the first <li> inside a <ul>
let firstItem = document.querySelector("ul li");
Method 5 — querySelectorAll(): returns a NodeList of all elements matching the CSS selector.
// Selects ALL elements with class "info"
let allParas = document.querySelectorAll(".info");
// Loop through the NodeList
allParas.forEach(para => {
console.log(para.textContent);
});
| Method | Selector Type | Returns | Live? |
|---|---|---|---|
getElementById() | id | Single element or null | — |
getElementsByClassName() | class name | HTMLCollection (live) | Yes |
getElementsByName() | name attribute | NodeList (live) | Yes |
querySelector() | CSS selector | First match or null | No |
querySelectorAll() | CSS selector | NodeList (static) | No |
Modifying DOM Elements
Change text content:
let heading = document.getElementById("title");
heading.textContent = "New Heading Text"; // Plain text only
heading.innerHTML = "<em>Italic Text</em>"; // Allows HTML tags inside
Change CSS styles:
let para = document.querySelector(".info");
para.style.color = "red";
para.style.fontSize = "20px";
para.style.backgroundColor = "yellow";
Change attributes:
let img = document.querySelector("img");
img.setAttribute("src", "new-image.jpg"); // Sets an attribute
img.getAttribute("src"); // Gets current value
img.removeAttribute("alt"); // Removes the attribute
Creating and Removing Elements Dynamically (Exam Q — 2026)
<!-- HTML structure -->
<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
</ul>
<button onclick="addItem()">Add Item</button>
<button onclick="removeItem()">Remove Last Item</button>
// Step 1: Get the unordered list element
let list = document.getElementById("myList");
let counter = 3; // Track item number
// Function to ADD a new <li> element
function addItem() {
// Step 2: Create a new <li> element
let newItem = document.createElement("li");
// Step 3: Set its text content
newItem.textContent = "Item " + counter;
counter++;
// Step 4: Append (add at end) to the <ul>
list.appendChild(newItem);
}
// Function to REMOVE the last <li> element
function removeItem() {
// Step 5: Get the last child of the list
let lastItem = list.lastElementChild;
// Step 6: Remove it only if the list is not empty
if (lastItem) {
list.removeChild(lastItem);
counter--;
}
}
onmouseover and onmouseout Example (Exam Q — 2023)
<!-- HTML: Image with description paragraph -->
<div>
<img id="myImage" src="photo.jpg" width="200"
onmouseover="changeDesc()"
onmouseout="resetDesc()">
<p id="desc">Original description of the image.</p>
</div>
// Change paragraph text when mouse hovers over the image
function changeDesc() {
document.getElementById("desc").textContent =
"You are hovering! This is the hover description.";
}
// Reset text when mouse leaves the image
function resetDesc() {
document.getElementById("desc").textContent =
"Original description of the image.";
}
Highlight Words Over 8 Characters (Exam Q — 2024)
<!-- HTML -->
<p id="myPara">JavaScript is an incredibly powerful and versatile programming language used worldwide.</p>
<button onclick="highlightLong()">Highlight Long Words</button>
function highlightLong() {
// Step 1: Get the paragraph text
let para = document.getElementById("myPara");
let words = para.textContent.split(" "); // Split into individual words
// Step 2: For each word, wrap in <span> with red background if over 8 chars
let newContent = words.map(word => {
if (word.length > 8) {
// Wrap the long word in a span with red background
return '<span style="background-color:red; color:white;">' + word + '</span>';
}
return word; // Short words stay as they are
});
// Step 3: Join words back and set as innerHTML
para.innerHTML = newContent.join(" ");
}
Summary
- The DOM represents HTML as a tree of objects that JavaScript can access and modify.
- Five main selection methods: getElementById, getElementsByClassName, getElementsByName, querySelector, querySelectorAll.
- Elements can be modified via textContent, innerHTML, style, and setAttribute.
- createElement() + appendChild() adds new elements; removeChild() deletes them.
- DOM manipulation enables dynamic pages without page reloads — the core of interactive web apps.
Test Yourself
- What are different ways to include JavaScript in HTML document? Create a HTML page containing a division with image and its description in paragraph. Write a JavaScript function to change the value of description in the paragraph during onmouseover and onmouseout on the image. (2023)
- What is JavaScript Event? Explain different methods that are available to access DOM element using id, class, name and selector with suitable example. (2024)
- Write the code to create and remove new list item into Unordered list dynamically into JavaScript DOM. (2026)
- Write a JS program to highlight all of the words over eight characters long in the paragraph text (with a red background). (2024)
Hints:
- JS can be included: inline (onclick=""), internal (<script> in <head>/<body>), external (<script src="file.js">). For onmouseover: getElementById("desc").textContent = "hover text"; onmouseout resets it.
- Five DOM access methods: getElementById (by id), getElementsByClassName (by class, returns collection), getElementsByName (by name attr), querySelector (first CSS match), querySelectorAll (all CSS matches, NodeList).
- createElement("li") creates the node. appendChild() adds it. lastElementChild + removeChild() removes it. See full code example above.
- Split paragraph into words array, use map() to wrap words with length > 8 in a <span style="background:red">, join and set as innerHTML.
1.9 JavaScript Event Handling
Definition
A JavaScript event is an action or occurrence detected by the browser — such as a mouse click, key press, or page load — that JavaScript can respond to by running a specified function called an event handler.
Events are the way a web page listens to the user. The browser is always watching: when you click something, type something, or move your mouse, the browser fires an event. Event handling is your code saying "when that happens, do this."
Detailed Explanation
JavaScript uses the event-driven programming model. Instead of running top-to-bottom continuously, JavaScript waits, listens for events, and executes the right handler when an event fires.
Common JavaScript Events
| Event | Triggered When |
|---|---|
onclick | User clicks an element |
ondblclick | User double-clicks an element |
onmouseover | Mouse pointer enters an element |
onmouseout | Mouse pointer leaves an element |
onkeydown | A key is pressed down |
onkeyup | A key is released |
onchange | Value of input/select changes |
onsubmit | Form is submitted |
onload | Page or image finishes loading |
onfocus | Element receives focus (clicked/tabbed into) |
onblur | Element loses focus |
Three Ways to Attach Event Handlers
Method 1 — Inline HTML event attributes: the handler is written directly in the HTML tag.
<!-- onclick attribute runs the function directly -->
<button onclick="alert('Button clicked!')">Click Me</button>
<!-- Calling a function defined in <script> -->
<button onclick="greetUser()">Greet</button>
<script>
function greetUser() {
alert("Hello, User!");
}
</script>
Method 2 — DOM property assignment: assign a function to an element's event property in JavaScript.
<button id="myBtn">Click Me</button>
<script>
// Get the button element, then assign the handler via property
let btn = document.getElementById("myBtn");
btn.onclick = function() {
alert("Button was clicked!");
};
</script>
Method 3 — addEventListener() (recommended): the modern, flexible way. Multiple listeners can be attached to one event.
<button id="myBtn">Click Me</button>
<script>
let btn = document.getElementById("myBtn");
// addEventListener(eventType, handlerFunction)
btn.addEventListener("click", function() {
alert("First handler fired!");
});
// A second listener on the same button — both will fire
btn.addEventListener("click", function() {
console.log("Second handler also ran.");
});
// To remove a listener, the function must be named
function handleClick() {
alert("Removable handler.");
}
btn.addEventListener("click", handleClick);
btn.removeEventListener("click", handleClick); // Removed
</script>
Background Color Change on Radio Button Click (Exam Q — 2023)
<!-- HTML: Radio buttons for color selection -->
<form>
<input type="radio" name="color" value="green" onclick="changeColor('green')"> Green<br>
<input type="radio" name="color" value="red" onclick="changeColor('red')"> Red<br>
<input type="radio" name="color" value="blue" onclick="changeColor('blue')"> Blue<br>
<input type="radio" name="color" value="black" onclick="changeColor('black')"> Black
</form>
// Event handler: receives the selected color and applies it to the body
function changeColor(color) {
document.body.style.backgroundColor = color;
}
Background Color Change Every Second Using setInterval (Exam Q — 2022)
// Array of colors to cycle through
let colors = ["red", "green", "blue", "yellow", "purple", "orange"];
let index = 0; // Tracks current color position
// setInterval(callback, delay) — runs callback every 'delay' milliseconds
setInterval(function() {
document.body.style.backgroundColor = colors[index];
index = (index + 1) % colors.length; // Cycle back to 0 after last color
}, 1000); // 1000ms = 1 second
The Event Object
When an event fires, the browser automatically passes an event object to the handler containing details about what happened.
document.addEventListener("keydown", function(event) {
// event.key — which key was pressed
// event.type — type of event ("keydown")
// event.target — element that triggered the event
console.log("Key pressed: " + event.key);
});
document.getElementById("myBtn").addEventListener("click", function(event) {
console.log("Clicked element: " + event.target.id);
event.preventDefault(); // Prevents default browser action (e.g., form submit)
});
Summary
- JavaScript events are user or browser actions (click, keypress, load) that trigger event handler functions.
- Three ways to attach handlers: inline HTML attribute, DOM property assignment, addEventListener().
- addEventListener() is preferred — it allows multiple handlers on the same event and supports removeEventListener().
- The event object passed to handlers contains details: event.type, event.target, event.key, and event.preventDefault().
- setInterval() can be used to run code repeatedly at timed intervals (e.g., color change every second).
Test Yourself
- Write a HTML code to design a form with three radio buttons green, red, blue and black. Write a JavaScript code that will change the background color of the page when user clicks on particular button. (2023)
- What is NaN in JavaScript? Write JavaScript code to change background color of web page every second. (2022)
- Explain event handling in JavaScript. Difference between map and forEach method in JavaScript. (2025)
- What are the three ways to attach an event handler in JavaScript? Which one is recommended and why?
Hints:
- Radio buttons with onclick="changeColor('green')" etc. Handler function: document.body.style.backgroundColor = color;
- NaN = Not a Number, result of invalid math (e.g., "abc" * 2). Color change: use setInterval() with 1000ms delay, cycle through a colors array using index % colors.length.
- Event handling = listening for user actions (click, keypress) and running a handler. addEventListener is the modern approach. map returns new array; forEach returns undefined — main difference.
- Inline HTML attribute (onclick=""), DOM property (element.onclick = fn), addEventListener(). addEventListener is preferred: allows multiple handlers, supports removal, separates JS from HTML.
1.10 Client-Side Form Validation
Definition
Form validation is the process of checking that user-submitted form data meets required criteria — such as correct format, required fields, and valid values — before sending that data to a server.
Validation is the gatekeeper of your form. Before data travels anywhere, validation checks: Is the field empty? Is the email format correct? Is the password long enough? Client-side validation catches errors instantly in the browser; server-side catches them on the server after submission.
Why Validation is Needed
- Prevents incomplete or malformed data from reaching the server or database.
- Gives the user immediate feedback without waiting for a server response.
- Reduces server load — invalid submissions never leave the browser.
- Improves user experience through real-time, inline error messages.
Client-Side vs Server-Side Validation
| Feature | Client-Side Validation | Server-Side Validation |
|---|---|---|
| Where it runs | In the browser (JavaScript) | On the web server (PHP, Python, etc.) |
| Speed | Instant — no network request | Slower — requires round trip to server |
| Can be bypassed | Yes — JavaScript can be disabled | No — user cannot bypass server code |
| Security | Not secure alone | Secure and mandatory |
| User experience | Excellent — real-time feedback | Poorer — must wait for server response |
| Best practice | Use for UX only | Always required for security |
The verdict from exams (2026): best practice is to use both. Client-side validation for instant feedback; server-side validation as the security layer, because client-side JavaScript can always be disabled or bypassed by a malicious user.
Form Validation — Complete Example
<!-- HTML Form -->
<form onsubmit="return validateForm()">
<label>Name:</label>
<input type="text" id="name" placeholder="Enter your name"><br><br>
<label>Email:</label>
<input type="text" id="email" placeholder="Enter your email"><br><br>
<label>Password:</label>
<input type="password" id="password" placeholder="Min 6 characters"><br><br>
<label>Age:</label>
<input type="number" id="age" placeholder="Enter your age"><br><br>
<span id="errorMsg" style="color:red;"></span><br>
<button type="submit">Submit</button>
</form>
function validateForm() {
// Step 1: Get field values and trim whitespace
let name = document.getElementById("name").value.trim();
let email = document.getElementById("email").value.trim();
let password = document.getElementById("password").value;
let age = document.getElementById("age").value;
let errorMsg = document.getElementById("errorMsg");
// Step 2: Check if name is empty
if (name === "") {
errorMsg.textContent = "Name is required.";
return false; // return false stops form submission
}
// Step 3: Check email format using regular expression
// Regex explanation: must have characters, @, domain, dot, extension
let emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email)) {
errorMsg.textContent = "Enter a valid email address.";
return false;
}
// Step 4: Check password length
if (password.length < 6) {
errorMsg.textContent = "Password must be at least 6 characters.";
return false;
}
// Step 5: Check age is a valid positive number
if (age === "" || age < 1 || age > 120) {
errorMsg.textContent = "Enter a valid age (1–120).";
return false;
}
// Step 6: All checks passed — allow form submission
errorMsg.textContent = "";
alert("Form submitted successfully!");
return true; // return true allows submission
}
Common Mistake
Students forget that return false inside onsubmit is what actually prevents the form from submitting. If you just show an alert but return nothing (or return true), the form still submits. Always return false when validation fails, and ensure onsubmit="return validateForm()" includes the return keyword.
Summary
- Form validation checks user input for correctness before the data is processed or sent to a server.
- Client-side validation is fast and improves user experience but can be bypassed — never rely on it alone for security.
- Server-side validation is mandatory for security since it cannot be disabled by the user.
- In JavaScript validation,
return falsein the onsubmit handler stops form submission;return trueallows it. - Common checks: empty fields, email format (regex), minimum length, numeric range.
Test Yourself
- Why do we need validation? Explain with examples which validation is best among client side and server-side validation. Write JavaScript program that use countries array to display 50 countries into tabular format with 4 countries in a row. (2026)
- Write a complete JavaScript form validation example checking name, email, and password fields.
Hints:
- Validation needed to ensure correct, complete data. Client-side: fast, UX-friendly, bypassable. Server-side: secure, slower, mandatory. Best = use BOTH. Countries in table: loop through array, every 4 items start <tr>, close </tr> after 4 items or at end.
- Get values, check empty with === "", check email with regex /^[^\s@]+@[^\s@]+\.[^\s@]+$/, check password.length < 6, return false on failure, return true on success. Use onsubmit="return validate()".
1.11 JavaScript Regular Expressions
Definition
A regular expression (regex) is a pattern of characters used to search, match, or manipulate strings — commonly used in JavaScript for input validation and text processing.
A regex is a search pattern written in a special syntax. Instead of looking for the exact word "hello", you can write a pattern that matches any email, any phone number, or any word that starts with a capital letter. It is the most powerful tool for string matching.
Detailed Explanation
In JavaScript, a regular expression is created in two ways:
// Method 1 — Literal syntax (between forward slashes)
let pattern1 = /hello/;
// Method 2 — Constructor syntax
let pattern2 = new RegExp("hello");
Regex Flags
| Flag | Meaning | Example |
|---|---|---|
i | Case-insensitive | /hello/i matches "Hello", "HELLO" |
g | Global — find all matches (not just first) | /hello/g |
m | Multi-line matching | /^hello/m |
Common Regex Patterns
| Pattern | Matches |
|---|---|
\d | Any digit (0–9) |
\w | Any word character (a-z, A-Z, 0-9, _) |
\s | Any whitespace (space, tab) |
. | Any character except newline |
^ | Start of string |
$ | End of string |
+ | One or more of preceding |
* | Zero or more of preceding |
? | Zero or one of preceding |
{n} | Exactly n of preceding |
[abc] | Any one of a, b, or c |
[^abc] | Any character NOT a, b, or c |
JavaScript Regex Methods
let str = "Hello World 2026";
let pattern = /\d+/; // Matches one or more digits
// test() — returns true or false
console.log(pattern.test(str)); // true — digits found
// match() — returns array of matches
console.log(str.match(/\d+/g)); // ["2026"]
// replace() — replaces matches with new string
console.log(str.replace("World", "Nepal")); // "Hello Nepal 2026"
// split() — splits string at pattern
console.log("a,b,c".split(",")); // ["a", "b", "c"]
Practical Validation with Regex
// Email validation
function validateEmail(email) {
// ^ = start, [^\s@]+ = one or more non-space non-@ chars,
// @ = literal @, \. = literal dot, $ = end
let pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return pattern.test(email);
}
console.log(validateEmail("anita@example.com")); // true
console.log(validateEmail("notanemail")); // false
// Phone number validation (10 digits)
function validatePhone(phone) {
let pattern = /^\d{10}$/; // Exactly 10 digits, nothing else
return pattern.test(phone);
}
console.log(validatePhone("9841234567")); // true
console.log(validatePhone("123")); // false
// Reverse name (Exam Q — 2023 style: first and last name reversed)
function reverseName() {
let fullName = prompt("Enter your first and last name:");
let parts = fullName.trim().split(" "); // Split at space
let reversed = parts[1] + " " + parts[0];
document.write("Reversed Name: " + reversed);
}
Summary
- Regular expressions are patterns used to match, search, and manipulate strings in JavaScript.
- Created with literal syntax
/pattern/flagsornew RegExp("pattern"). - Key methods: test() returns boolean, match() returns array, replace() substitutes, split() divides.
- Common use: validating emails, phone numbers, and formatted inputs in form validation.
- Flags
i(case-insensitive) andg(global, find all) are the most commonly used.
Test Yourself
- What is the need for client side scripting? Write a JavaScript which accepts user's first and last name and print them in reverse order with space between them. (2023)
- Write a regex pattern to validate: (a) an email address (b) a 10-digit phone number.
Hints:
- Client-side scripting makes pages interactive without server round trips. Name reversal: split input on space to get [first, last], output last + " " + first.
- (a)
/^[^\s@]+@[^\s@]+\.[^\s@]+$/— must have chars, @, domain, dot, extension. (b)/^\d{10}$/— exactly 10 digits, start to end.
1.12 JavaScript Arrays — Operations and Programs
Definition
A JavaScript array is an ordered, indexed collection of values stored in a single variable, where each value (element) can be of any data type and is accessed by its numeric position (index) starting from zero.
Array Operations and Common Methods
let fruits = ["Apple", "Banana", "Cherry"];
// Access by index (starts at 0)
console.log(fruits[0]); // "Apple"
console.log(fruits[2]); // "Cherry"
// Length property
console.log(fruits.length); // 3
// Add to end — push()
fruits.push("Mango"); // ["Apple", "Banana", "Cherry", "Mango"]
// Remove from end — pop()
fruits.pop(); // Removes "Mango"
// Add to start — unshift()
fruits.unshift("Grape"); // ["Grape", "Apple", "Banana", "Cherry"]
// Remove from start — shift()
fruits.shift(); // Removes "Grape"
// Find index of an element — indexOf()
console.log(fruits.indexOf("Banana")); // 1
// Join array into string — join()
console.log(fruits.join(", ")); // "Apple, Banana, Cherry"
// Slice (extract portion, non-destructive)
let sliced = fruits.slice(0, 2); // ["Apple", "Banana"]
// Sort alphabetically
fruits.sort(); // ["Apple", "Banana", "Cherry"]
// Reverse array
fruits.reverse(); // ["Cherry", "Banana", "Apple"]
Sum, Average, and Largest Number from n Integers (Exam Q — 2025)
// Step 1: Accept n integers from the user
let n = parseInt(prompt("How many numbers do you want to enter?"));
let numbers = []; // Empty array to store inputs
// Step 2: Loop n times to collect values
for (let i = 0; i < n; i++) {
let num = parseInt(prompt("Enter number " + (i + 1) + ":"));
numbers.push(num); // Add each number to the array
}
// Step 3: Calculate sum using a loop
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i]; // Add each element to sum
}
// Step 4: Calculate average
let average = sum / n;
// Step 5: Find the largest number
let largest = numbers[0]; // Assume first is largest
for (let i = 1; i < numbers.length; i++) {
if (numbers[i] > largest) {
largest = numbers[i]; // Update if current is larger
}
}
// Step 6: Display results
document.write("Numbers: " + numbers.join(", ") + "<br>");
document.write("Sum: " + sum + "<br>");
document.write("Average: " + average.toFixed(2) + "<br>");
document.write("Largest Number: " + largest);
Display 50 Countries in Tabular Format — 4 Per Row (Exam Q — 2026)
// Array of 50 country names (abbreviated for illustration)
let countries = [
"Nepal", "India", "China", "USA", "UK", "France", "Germany",
"Japan", "Brazil", "Canada", "Australia", "Italy", "Spain",
"Russia", "Mexico", "South Korea", "Indonesia", "Turkey",
"Saudi Arabia", "Argentina", "Pakistan", "Bangladesh",
"Nigeria", "Egypt", "Ethiopia", "Philippines", "Vietnam",
"Iran", "Thailand", "Tanzania", "Kenya", "Colombia",
"Myanmar", "Algeria", "Sudan", "Ukraine", "Iraq",
"Afghanistan", "Poland", "Morocco", "Malaysia", "Ghana",
"Peru", "Angola", "Mozambique", "Venezuela", "Cambodia",
"Zimbabwe", "Portugal", "Belgium"
];
// Build the table HTML
let tableHTML = "<table border='1'>";
// Loop through all countries
for (let i = 0; i < countries.length; i++) {
// Start a new row every 4 countries (when index is divisible by 4)
if (i % 4 === 0) {
tableHTML += "<tr>"; // Open a new table row
}
tableHTML += "<td>" + countries[i] + "</td>"; // Add country in a cell
// Close the row after every 4th country, or at the last item
if (i % 4 === 3 || i === countries.length - 1) {
tableHTML += "</tr>"; // Close the row
}
}
tableHTML += "</table>";
// Write the table to the page
document.body.innerHTML = tableHTML;
Summary
- Arrays store ordered collections; elements are accessed by zero-based index.
- push/pop add or remove from the end; unshift/shift add or remove from the start.
- For sum/average/largest: loop through the array, accumulate sum, track the max with a running variable.
- For tabular layout: use
i % 4 === 0to open a new row andi % 4 === 3or last index to close it.
Test Yourself
- Write a JavaScript program to accept n integers into an array, calculate and display the sum and average of the numbers; also find the largest number among them. (2025)
- Write JavaScript program that use countries array to display 50 countries into tabular format with 4 countries in a row. (2026)
Hints:
- Use prompt() in a loop to fill array. Sum: add all elements. Average: sum / n. Largest: start with arr[0], loop from index 1, update if arr[i] > largest.
- Loop through countries array. Use i % 4 === 0 to open <tr>, i % 4 === 3 (or i === last) to close </tr>. Each country in <td>.
1.13 JavaScript Calculator
Definition
A JavaScript calculator is a web-based tool built with HTML for the interface and JavaScript for the logic, performing arithmetic operations (addition, subtraction, multiplication, division) based on user input and displaying results dynamically.
Complete Calculator Code
<!-- HTML: Calculator interface -->
<!DOCTYPE html>
<html>
<head><title>JS Calculator</title></head>
<body>
<h2>Simple Calculator</h2>
<!-- Input fields for numbers -->
<input type="number" id="num1" placeholder="First number"><br><br>
<input type="number" id="num2" placeholder="Second number"><br><br>
<!-- Operation buttons -->
<button onclick="calculate('+')"> + </button>
<button onclick="calculate('-')"> - </button>
<button onclick="calculate('*')"> × </button>
<button onclick="calculate('/')"> ÷ </button>
<button onclick="clearResult()"> C </button>
<br><br>
<!-- Display result here -->
<p>Result: <span id="result">—</span></p>
</body>
</html>
// JavaScript logic for the calculator
function calculate(operator) {
// Step 1: Get values from the input fields
let num1 = parseFloat(document.getElementById("num1").value);
let num2 = parseFloat(document.getElementById("num2").value);
// Step 2: Check if both inputs are valid numbers
if (isNaN(num1) || isNaN(num2)) {
document.getElementById("result").textContent = "Please enter valid numbers.";
return; // Exit the function early
}
// Step 3: Perform the selected operation using switch
let answer;
switch (operator) {
case '+':
answer = num1 + num2;
break;
case '-':
answer = num1 - num2;
break;
case '*':
answer = num1 * num2;
break;
case '/':
// Step 4: Check for division by zero
if (num2 === 0) {
document.getElementById("result").textContent = "Cannot divide by zero!";
return;
}
answer = num1 / num2;
break;
default:
answer = "Invalid operator";
}
// Step 5: Display the result
document.getElementById("result").textContent = answer;
}
// Clear input fields and result
function clearResult() {
document.getElementById("num1").value = "";
document.getElementById("num2").value = "";
document.getElementById("result").textContent = "—";
}
Summary
- A JavaScript calculator takes two number inputs and performs an arithmetic operation selected by the user.
- parseFloat() converts input strings to decimal numbers; isNaN() checks for invalid input.
- switch-case handles which operation to perform cleanly and readably.
- Always handle the division-by-zero edge case — dividing by zero in JS returns
Infinity, not an error.
Test Yourself
- Write HTML and JavaScript code to create a calculator for performing basic arithmetic operations. (2025 / 2022)
- What happens in JavaScript if you divide a number by zero? How should a calculator handle it?
Hints:
- HTML: two number inputs, four operation buttons (onclick="calculate('+')"), result display span. JS: parseFloat() inputs, switch on operator, set result span's textContent.
- In JS, 5/0 = Infinity (not an error). A calculator should check if num2 === 0 before dividing and display "Cannot divide by zero!" message.
Extra: Topics Asked in Exams But Not Covered Above
These topics have appeared in past papers. They are not standalone syllabus items but appeared as exam questions requiring short answers.
NaN in JavaScript (2022 exam)
NaN stands for Not a Number. It is a special JavaScript value returned when a mathematical operation produces a result that is not a valid number.
console.log("hello" * 5); // NaN — cannot multiply text by number
console.log(0 / 0); // NaN — indeterminate form
console.log(parseInt("abc")); // NaN — cannot parse non-numeric string
// Check for NaN using isNaN()
console.log(isNaN("hello")); // true
console.log(isNaN(42)); // false
// NaN is not equal to itself — unique in JavaScript
console.log(NaN === NaN); // false — always false!
// That is why you must use isNaN(), not ===
Ways to Include JavaScript in HTML (2023 exam)
There are three methods to add JavaScript to an HTML document:
1. Inline JavaScript — written directly inside an HTML tag's event attribute.
<button onclick="alert('Hello!')">Click Me</button>
2. Internal JavaScript — placed inside a <script> tag in the <head> or <body>.
<head>
<script>
function greet() { alert("Hello!"); }
</script>
</head>
3. External JavaScript — stored in a separate .js file and linked with the src attribute.
<!-- In HTML head or before closing body tag -->
<script src="script.js"></script>
External files are preferred for large projects — they keep HTML clean, allow caching, and the same file can be reused across multiple pages.
PHP vs JavaScript — Main Difference (2025 exam)
| Feature | JavaScript | PHP |
|---|---|---|
| Execution location | Client-side (browser) | Server-side (web server) |
| Primary use | Interactive UI, DOM, events | Database access, server logic, generating HTML |
| Can access database directly | No (needs server API) | Yes (MySQL, PostgreSQL) |
| Visible to user | Yes (source is viewable) | No (runs on server, output is HTML) |
| Why use both? | JS handles UI interaction; PHP handles data processing and storage. Together they make a full, dynamic web application. | |
Features of JavaScript (2022 exam)
- Interpreted: code is executed line by line by the browser without prior compilation.
- Lightweight and fast: runs directly in the browser, no additional software needed.
- Event-driven: responds to user actions like clicks, keystrokes, and mouse movements.
- Object-based: uses objects (like
document,window) but does not require full class-based OOP. - Dynamic typing: variables do not need a declared type; type is determined at runtime.
- Cross-platform: runs in all major browsers on any operating system.
- Complements HTML and CSS: adds behavior to static content.
Exam Questions
- What is the need for client side scripting? Write a JavaScript which accepts user's first and last name and print them in reverse order with space between them. (2023)
- Write a HTML code to design a form with three radio buttons green, red, blue and black. Write a JavaScript code that will change the background color of the page when user clicks on particular button. (2023)
- What are different ways to include JavaScript in HTML document? Create a HTML page containing a division with image and its description in paragraph. Write a JavaScript function to change the value of description in the paragraph during onmouseover and onmouseout on the image. (2023)
- Explain features of JavaScript? (2022)
- What is NaN in JavaScript? Write JavaScript code to change background color of web page every second. (2022)
- What is arrow function? Write JavaScript code to calculate factorial of given number using arrow function. (2022)
- Write HTML and JavaScript code to create a calculator for performing basic arithmetic operations. (2025 / 2022)
- Write JS program to highlight all of the words over eight characters long in the paragraph text (with a red background). (2024)
- What is JavaScript? Explain different types of JavaScript with proper example. (2024)
- What is JavaScript Event? Explain different methods that are available to access DOM element using id, class, name and selector with suitable example. (2024)
- Write a JavaScript program to accept n integers into an array, calculate and display the sum and average of the numbers; also find the largest number among them. (2025)
- PHP and JavaScript are both programming languages that generate dynamic results for web pages. What is their main difference, and why would you use both of them? (2025)
- Explain event handling in JavaScript. Difference between map and forEach method in JavaScript. (2025)
- Write the code to create and remove new list item into Unordered list dynamically into JavaScript DOM. (2026)
- What is JS arrow function? Explain use of forEach() and map() method in JavaScript. (2026)
- Why do we need validation? Explain with examples which validation is best among client side and server-side validation. Write JavaScript program that use countries array to display 50 countries into tabular format with 4 countries in a row. (2026)
Whole Chapter Summary
Arrow Functions: ES6 shorthand using =>. Single expressions get implicit return. No own this. Use for callbacks and short transformations. Factorial = classic exam example.
map() Method: Transforms every element of an array and returns a NEW array. The original is untouched. Takes a callback (element, index, array). Return value of callback becomes the new element. Key distinction from forEach: map returns a value.
DOM Manipulation: The DOM is the JavaScript interface to the HTML document tree. Five selection methods (getElementById, getElementsByClassName, getElementsByName, querySelector, querySelectorAll). Elements can be modified via textContent, innerHTML, style, and attributes. createElement + appendChild adds elements; removeChild removes them.
Event Handling: Events are browser-detected actions. Handlers attached three ways: inline attribute, DOM property, addEventListener(). addEventListener is modern best practice — multiple handlers, removable. setInterval runs code repeatedly on a timer. The event object carries details about what happened.
Form Validation: Validates user input before processing. Client-side = fast but bypassable. Server-side = secure and mandatory. Use both. onsubmit handler must return false to prevent submission on error, return true to allow.
Regular Expressions: Pattern-based string matching. Key methods: test(), match(), replace(). Essential for email and phone validation. Flags i (ignore case) and g (global all matches) are most common.
Array Operations and Programs: push/pop for end, unshift/shift for start. For sum/average/largest: accumulate in loop. For tabular display: use modulo (% 4) to manage row breaks.
Calculator: Two inputs + switch-case + division-by-zero guard + result display. parseFloat() for decimal support. isNaN() for invalid input check.
NaN / JS Inclusion / PHP vs JS: NaN = Not a Number from invalid math. JS added inline, internal, or external. JS is client-side; PHP is server-side — both needed for full dynamic web apps.
Last-Minute Revision Sheet
| Concept | Trigger Phrase | Recall Cue |
|---|---|---|
| Arrow function | ES6 => shorthand | No function keyword · implicit return (no {}) · no own this |
| Arrow factorial | const f = (n) => | n <= 1 ? 1 : n * f(n-1) · base case at 0 or 1 |
| map() | transforms → new array | returns NEW array · original untouched · return value matters |
| forEach() | iterate → side effects | returns undefined · cannot chain · use for print/DOM updates |
| map vs forEach | key difference | map → returns array · forEach → returns nothing |
| DOM | document tree interface | JS object model of HTML · read + modify without reload |
| getElementById | by id="" | single element · null if not found |
| querySelector | CSS selector · first match | ".class" "#id" "tag" · most flexible |
| querySelectorAll | CSS selector · all matches | returns static NodeList · use .forEach() to loop |
| createElement | create + appendChild | create node → set text → append to parent |
| removeChild | lastElementChild then remove | get child first → pass to removeChild() |
| Events | user action → handler fires | click, keydown, mouseover, submit, load, change |
| addEventListener | modern event attachment | multiple handlers · removable · preferred over inline |
| setInterval | repeat every N ms | setInterval(fn, 1000) → 1 second · use index % length to cycle |
| Form validation | check before submit | return false = block · return true = allow · onsubmit="return fn()" |
| Client vs Server validation | UX vs security | client = fast, bypassable · server = secure, mandatory · use BOTH |
| Regex test() | /pattern/.test(str) | true/false · use for email, phone validation |
| Email regex | /^[^\s@]+@[^\s@]+\.[^\s@]+$/ | no spaces, @, domain, dot, extension |
| NaN | Not a Number | invalid math result · check with isNaN() · NaN !== NaN |
| Array sum/avg/max | loop + accumulate | sum += arr[i] · avg = sum/n · largest: start arr[0], update if bigger |
| Table 4 per row | i % 4 logic | i%4===0 → open tr · i%4===3 or last → close tr · country in td |
| Calculator | parseFloat + switch | isNaN check → switch(op) → division-by-zero guard → show result |
| JS inclusion | inline / internal / external | onclick attr · <script> tag · <script src=""> — external preferred |
| JS vs PHP | client vs server | JS = browser, UI · PHP = server, DB · use both for full app |
| Background change (radio) | onclick → changeColor() | document.body.style.backgroundColor = color |
| Background change (timer) | setInterval + array cycle | index++ then % colors.length to wrap around |


