UNIT 4 INTERACTIVE WEB DESIGN USING JAVASCRIPT 9
Java Script - adding Techniques, Variables and Operators, Conditional and Control Statements Data Types
and Functions. Events - Form Validation, Page Redirect, Java Script Exception Handling, Document Object
Model (DOM)
JavaScript (JS) is a programming language that runs in web browsers and on servers. Along
with HTML, which provides the structure of a webpage, and CSS, which handles the styling and
layout, JavaScript forms the third essential component of front-end web development. It can can
change HTML and CSS dynamically.
Adding Techniques:
1) Inline script : Java script is added inside the tag.
Example:
<button onclick="alert('Hello!')">Click</button>
2) Internal script : Java script is added using style tag.
Example:
<html>
<head>
<title>Internal JavaScript Example</title>
</head>
<body>
<h2>Click the Button Below</h2>
<button onclick="showMessage()">Click Me</button>
<script>
function showMessage() {
alert("Welcome to JavaScript!");
}
</script>
</body>
</html>
3) External script :Java Script is written in separate file and added with HTML.
Example:
HTML file:
<html>
<head>
<title>External JavaScript Example</title>
<script src="[Link]"></script>
</head>
<body>
<h2>Click the Button Below</h2>
<button onclick="showMessage()">Click Me</button>
</body>
</html>
JS file:
[Link]
function showMessage()
alert("Hello! This message comes from an external JavaScript file.");
Variables and Operators:
A variable is a name used to store data values.
It acts like a container that holds information which can be changed or reused later.
Declaring Variables
In JavaScript, variables can be declared using var, let, or const:
Keyword Description Example
var Old way to declare variables (function-scoped) var x = 10;
let Modern way (block-scoped) – preferred let name = "John";
const Used for constants (cannot be changed) const pi = 3.14;
Example:
<html>
<head>
<title>Variable Declaration Example</title>
</head>
<body>
<h2>JavaScript Variable Example</h2>
<script>
// Declaring variables
var name = "John"; // using var
let age = 25; // using let
const country = "India"; // using const
// Displaying the values
[Link]("<b>Name:</b> " + name + "<br>");
[Link]("<b>Age:</b> " + age + "<br>");
[Link]("<b>Country:</b> " + country);
</script>
</body>
</html>
OUTPUT:
Name: John
Age: 25
Country: India
Operators:
Operators are symbols that perform operations on variables and values — such as
addition, subtraction, comparison, or logic checks.
[Link] Operators:- Used to perform basic mathematical operations.
Operator Description Example Result
+ Addition 5 + 2 7
- Subtraction 5 - 2 3
* Multiplication 5 * 2 10
/ Division 5 / 2 2.5
% Modulus (remainder) 5 % 2 1
[Link] Operators:- Used to assign or update values.
Operator Example Same As
= x = 5 Assign value 5
+= x += 3 x = x + 3
-= x -= 3 x = x – 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
3. Comparison Operators:- Used to compare two values (result is true or false).
Operator Description Example Result
== Equal to 5 == "5" true
Operator Description Example Result
=== Equal value and type 5 === "5" false
!= Not equal 5 != 8 true
> Greater than 8 > 5 true
< Less than 3 < 5 true
>= Greater or equal 5 >= 5 true
<= Less or equal 3 <= 5 true
4. Logical Operators:
Operator Description Example Result
&& AND x > 0 && x < 10 true only if both are true
|| || x > 0 || x < 10 OR
! NOT !true False
5. String Operator:-The + operator can also join (concatenate) strings.
let first = "Hello";
let last = "World";
[Link](first + " " + last); // Output: Hello World
Example Program:
<html>
<head>
<title>Operators Example</title>
</head>
<body>
<h2>JavaScript Operators Example</h2>
<script>
let a = 10;
let b = 3;
// Arithmetic Operators
[Link]("<b>Arithmetic Operators:</b><br>");
[Link]("a + b = " + (a + b) + "<br>");
[Link]("a - b = " + (a - b) + "<br>");
[Link]("a * b = " + (a * b) + "<br>");
[Link]("a / b = " + (a / b) + "<br>");
[Link]("a % b = " + (a % b) + "<br><br>");
// Assignment Operator
[Link]("<b>Assignment Operator:</b><br>");
let c = a;
c += b;
[Link]("c after c += b is: " + c + "<br><br>");
// Comparison Operators
[Link]("<b>Comparison Operators:</b><br>");
[Link]("a == b : " + (a == b) + "<br>");
[Link]("a != b : " + (a != b) + "<br>");
[Link]("a > b : " + (a > b) + "<br>");
[Link]("a < b : " + (a < b) + "<br><br>");
// Logical Operators
[Link]("<b>Logical Operators:</b><br>");
[Link]("(a > 5 && b < 5) : " + (a > 5 && b < 5) + "<br>");
[Link]("(a < 5 || b < 5) : " + (a < 5 || b < 5) + "<br>");
[Link]("!(a == b) : " + !(a == b) + "<br>");
</script>
</body>
</html>
OUTPUT:
Arithmetic Operators:
a + b = 13
a-b=7
a * b = 30
a / b = 3.3333333333333335
a%b=1
Assignment Operator:
c after c += b is: 13
Comparison Operators:
a == b : false
a != b : true
a > b : true
a < b : false
Logical Operators:
(a > 5 && b < 5) : true
(a < 5 || b < 5) : true
!(a == b) : true
Conditional and Control Statements:
Conditional and control statements are used to make decisions and control the
flow of a program based on certain conditions.
Types of conditional statements:
Statement Description
If Executes a block of code if a condition is true
if...else Executes one block if true, another if false
if...else if...else Checks multiple conditions
Switch Executes one block based on matching value
1. if Statement
Syntax:
if (condition) {
// code to execute if condition is true
}
<html>
<head>
<title>if Statement Example</title>
</head>
<body>
<script>
let age = 20;
if (age >= 18) {
[Link]("You are eligible to vote!");
</script>
</body>
</html>
Output:
You are eligible to vote!
2. if...else Statement
Syntax:
if (condition) {
// code if true
} else {
// code if false
Example:
<html>
<head>
<title>if...else Example</title>
</head>
<body>
<script>
let marks = 45;
if (marks >= 50) {
[Link]("You passed the exam!");
} else {
[Link]("You failed the exam!");
</script>
</body>
</html>
Output:
You failed the exam!
3. if...else if...else Statement:
Used when there are multiple conditions to check.
Example:
<html>
<head>
<title>if...else if Example</title>
</head>
<body>
<script>
let score = 85;
if (score >= 90) {
[Link]("Grade A");
} else if (score >= 75) {
[Link]("Grade B");
} else if (score >= 50) {
[Link]("Grade C");
} else {
[Link]("Fail");
</script>
</body></html>
Output:
Grade B
4. switch Statement
Used when you have many possible values for a single variable.
<html>
<head>
<title>Switch Example</title>
</head>
<body>
<script>
let day = 3;
let dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
default:
dayName = "Weekend";
[Link]("Today is: " + dayName);
</script>
</body>
</html>
Output:
Today is: Wednesday
Control Statements (Loops)
Looping statements help repeat tasks multiple times — they control the flow of execution.
Loop Description
For Repeats code a fixed number of times
While Repeats while a condition is true
do...while Runs at least once, then checks condition
Example: (for loop)
<html>
<head>
<title>for Loop Example</title>
</head>
<body>
<script>
[Link]("<b>Numbers from 1 to 5:</b><br>");
for (let i = 1; i <= 5; i++) {
[Link](i + "<br>");
</script>
</body>
</html>
OUTPUT:
Numbers from 1 to 5:
Example: (While loop)
<html>
<head>
<title>While Loop Example</title>
</head>
<body>
<script>
let i = 1; // starting value
[Link]("<b>Numbers from 1 to 5 (using while loop):</b><br>");
while (i <= 5) {
[Link](i + "<br>");
i++; // increase value
</script>
</body>
</html>
Example: (do-while loop)
<!DOCTYPE html>
<html>
<head>
<title>Do While Loop Example</title>
</head>
<body>
<script>
let i = 1; // starting value
[Link]("<b>Numbers from 1 to 5 (using do...while loop):</b><br>");
do {
[Link](i + "<br>");
i++;
} while (i <= 5);
</script>
</body>
</html>
Data Types and Functions:
Data types specify what kind of data a variable can hold — like numbers, text, or
true/false values.
Category Data Type Example Description
Text values enclosed in
Primitive Data Types String "Hello"
quotes
Numeric values (integer or
Number 10, 5.5
decimal)
Boolean true, false Represents truth values
Category Data Type Example Description
Variable declared but not
Undefined let a;
assigned
Represents empty or no
Null let b = null;
value
BigInt 12345678901234567890n Used for very large integers
Unique identifier (advanced
Symbol Symbol("id")
use)
Non-Primitive (Reference) Collection of key–value
Object {name: "John", age: 25}
Data Types pairs
["red", "green",
Array "blue"] Ordered list of values
Function function greet() {} Block of reusable code
Example:
<html>
<head>
<title>JavaScript Data Types</title>
</head>
<body>
<h2>JavaScript Data Types Example</h2>
<script>
// Primitive Data Types
let name = "John"; // String
let age = 25; // Number
let isStudent = true; // Boolean
let city; // Undefined
let salary = null; // Null
// Non-Primitive Data Types
let person = {name: "John", age: 25}; // Object
let colors = ["Red", "Green", "Blue"]; // Array
function greet() { // Function
return "Hello from function!";
// Displaying values
[Link]("<b>Primitive Data Types:</b><br>");
[Link]("Name: " + name + "<br>");
[Link]("Age: " + age + "<br>");
[Link]("Is Student: " + isStudent + "<br>");
[Link]("City: " + city + "<br>");
[Link]("Salary: " + salary + "<br><br>");
[Link]("<b>Non-Primitive Data Types:</b><br>");
[Link]("Person: " + [Link] + ", " + [Link] + "<br>");
[Link]("Colors: " + colors + "<br>");
[Link]("Function Output: " + greet());
</script>
</body>
</html>
OUTPUT:
Primitive Data Types:
Name: John
Age: 25
Is Student: true
City: undefined
Salary: null
Non-Primitive Data Types:
Person: John, 25
Colors: Red, Green, Blue
Function Output: Hello from function!
Functions:
A function is a block of code that performs a specific task.
Instead of writing the same code again and again, we write it once in a function
and reuse it whenever needed.
Syntax:
[Link] define function:
function functionName() {
// code to execute
[Link] call the function:
functionName();
Example:
[Link] without parameters:
<html>
<head>
<title>Simple Function Example</title>
</head>
<body>
<h2>Simple Function Example</h2>
<script>
// Function Definition
function greet() {
[Link]("Hello, welcome to JavaScript!");
// Function Call
greet();
</script>
</body>
</html>
Output:
Hello, welcome to JavaScript!
[Link] with parameters:
<html>
<head>
<title>Function with Parameters</title>
</head>
<body>
<h2>Function with Parameters</h2>
<script>
function greetUser(name) {
[Link]("Hello, " + name + "!<br>");
greetUser("John");
greetUser("Priya");
</script>
</body>
</html>
OUTPUT:
Hello, John!
Hello, Priya!
3. Function with Return Value:
<!DOCTYPE html>
<html>
<head>
<title>Function with Return Example</title>
</head>
<body>
<h2>Function with Return Value</h2>
<script>
function add(a, b) {
return a + b;
let result = add(10, 5);
[Link]("Sum of two numbers is: " + result);
</script>
</body>
</html>
OUTPUT:
Sum of two numbers is: 15
4. Function Expression:
Functions can also be stored in variables.
<html>
<body>
<script>
let multiply = function(x, y) {
return x * y;
};
[Link]("Product: " + multiply(4, 3));
</script>
</body>
</html>
OUTPUT:
Product: 12
[Link] Function (Modern Syntax)
Shorter way to write functions — introduced in ES6.
<html>
<head>
<title>Arrow Function Example</title>
</head>
<body>
<script>
let add = (a, b) => a + b;
[Link]("Sum: " + add(7, 3));
</script>
</body>
</html>
OUTPUT:
Sum: 10
Type Syntax Example
Simple Function function greet(){} greet();
With Parameters function greet(name){} greet("John");
With Return Value function add(a,b){ return a+b; } add(5,10);
Function Expression let f = function(){} f();
Type Syntax Example
Arrow Function let f = () => {} f();
Events - Form Validation:
Events:
An event is an action or occurrence in the browser that JavaScript can respond to.
Event Type Description
onclick When a button or element is clicked
onmouseover When the mouse moves over an element
onchange When an input field value changes
onkeyup When a key is released
onsubmit When a form is submitted
Example: (Onclick event)
<html>
<head>
<title>Button Event Example</title>
</head>
<body>
<button onclick="showMessage()">Click Me</button>
<script>
function showMessage() {
alert("Button Clicked!");
}
</script>
</body>
</html>
Form Validation:
Form validation means checking user input before submitting a form.
It ensures that users enter valid and complete information.
For example:
Name field should not be empty
Email should contain @
Password should have minimum length
Example:
<html>
<head>
<title>Form Validation Example</title>
</head>
<body>
<h2>Registration Form</h2>
<form onsubmit="return validateForm()">
Name: <input type="text" id="name"><br><br>
Email: <input type="text" id="email"><br><br>
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
let name = [Link]("name").value;
let email = [Link]("email").value;
if (name === "") {
alert("Please enter your name.");
return false; // stops form from submitting
if (email === "" || ) {
alert("Please enter a valid email.");
return false;
alert("Form submitted successfully!");
return true; // allows submission
</script>
</body>
</html>
Page Redirect:
A page redirect means sending the user from one web page to another
automatically or after a certain event (like a button click or form
submission).
JavaScript provides several ways to do this.
1. Using [Link]:
2. Using [Link]()
3. Redirect After a Delay (using setTimeout)
1. Using [Link]:
This changes the current page URL to another page.
<html>
<body>
<h2>Click the button to go to Google</h2>
<button onclick="redirectPage()">Go to Google</button>
<script>
function redirectPage() {
[Link] = "[Link]
}
</script>
</body> </html>
2. Using [Link]():
This also redirects, but it replaces the current page in history. So,
the user cannot go back using the Back button. This is used when
the user don’t want to return to the previous page.
Example:
<script>
[Link]("[Link]
</script>
3. Redirect After a Delay (using setTimeout):
Delay the redirect for specified time - useful for showing a message
before moving to another page.
Example:
<html>
<head>
<title>Auto Redirect Example</title>
</head>
<body>
<h2>You will be redirected in 3 seconds...</h2>
<script>
setTimeout(function() {
[Link] = "[Link]
}, 3000); // 3000 milliseconds = 3 seconds
</script>
</body>
</html>
Method Description Can Go Back?
[Link] = "URL" Normal redirect ✅Yes
[Link]("URL") Replaces current page ❌ No
setTimeout() + redirect Delayed redirect ✅ Yes
Java Script Exception Handling:
An exception is an error that occurs during program execution.
Examples:
Using a variable that doesn’t exist
Dividing by zero (in logic)
When such an error occurs, JavaScript stops execution unless it is
properly handled.
Exception handling is used to:
Prevent program crashes.
Show user-friendly messages instead of raw errors.
Continue program execution smoothly.
JavaScript uses try...catch blocks to handle exceptions.
Synatx:
try {
// Code that may cause an error
}
catch (error) {
// Code to handle the error
}
Example:
try {
let x = 10;
let y = x / z; // 'z' is not defined → error
[Link](y);
} catch (err) {
[Link]("An error occurred: " + [Link]);
}
OUTPUT:
An error occurred: z is not defined.
try...catch...finally:
Using finally block, which always executes — whether there’s an error or
not.
Example:
try {
[Link]("Inside try block");
let result = 10 / 2;
[Link]("Result:", result);
} catch (error) {
[Link]("Error:", error);
} finally {
[Link]("Finally block executed");
}
throw Statement:
manually throw (generate) errors using the throw keyword.