0% found this document useful (0 votes)
5 views38 pages

Unit 3 JavaScript

JavaScript is a versatile programming language primarily used for creating dynamic and interactive web content, functioning alongside HTML and CSS. It features lightweight syntax, client-side scripting, dynamic typing, and supports various programming paradigms including functional and object-oriented programming. JavaScript variables can be declared using var, let, or const, each with distinct characteristics regarding scope, hoisting, and reassignment.

Uploaded by

nargis.banu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views38 pages

Unit 3 JavaScript

JavaScript is a versatile programming language primarily used for creating dynamic and interactive web content, functioning alongside HTML and CSS. It features lightweight syntax, client-side scripting, dynamic typing, and supports various programming paradigms including functional and object-oriented programming. JavaScript variables can be declared using var, let, or const, each with distinct characteristics regarding scope, hoisting, and reassignment.

Uploaded by

nargis.banu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JavaScript

JavaScript is a programming language used to create dynamic and interactive content on websites. It is
one of the core technologies of the web, along with HTML and CSS.
Key Features of JavaScript
1. Lightweight and Interpreted
o JavaScript is easy to learn and does not require compilation.
o It runs directly in the browser (interpreted by the browser engine).
2. Client-Side Scripting
o JavaScript is mainly used to add interactivity to web pages.
o It runs on the user’s browser, reducing the load on the server.
3. Dynamic Typing
o You don't need to define variable types (like int, string).
o Example:
var x = 10; // number
x = "hello"; // string (valid!)
4. Event-Based Programming
o JavaScript responds to user actions like clicks, hovers, key presses, etc.
o Example: onclick, onchange, onmouseover
5. Functional Programming Style
o Functions in JavaScript can be treated like variables.
o You can pass them as arguments or return them from other functions.
6. Asynchronous Processing
o JavaScript uses callbacks, promises, and async/await to handle tasks like API calls without
blocking the main thread.
7. Object-Oriented Programming (OOP)
o JavaScript supports objects, classes (ES6), inheritance, and methods.
8. Platform Independent
o JavaScript code runs on any platform (Windows, Linux, Mac) and any browser.
9. Rich Built-in Libraries
o JavaScript has many built-in objects like Array, Date, Math, and powerful web APIs.
10. DOM Manipulation
JavaScript can access and change HTML and CSS content dynamically via the DOM (Document
Object Model).
11. Community and Ecosystem
A huge developer community and thousands of open-source libraries (like React, Angular, Vue).

Advantages of JavaScript
1. Runs in the Browser (Client-Side)
o No need to install or set up — it runs directly in web browsers.
o Reduces server load and makes pages faster.
2. Fast Execution
o JavaScript is executed immediately in the browser using powerful engines like Chrome’s V8.
3. Easy to Learn and Use
o Simple syntax similar to C, Java, or Python.
o Great for beginners as well as professionals.
4. Interactivity
o Makes web pages dynamic and interactive (e.g., buttons, forms, sliders).
5. Supports Asynchronous Programming
o Using callbacks, promises, and async/await, it handles tasks like loading data from a server
without blocking the page.
6. Cross-Platform Support
o Runs on any device with a web browser — Windows, macOS, Android, iOS.
7. Huge Ecosystem
o Tons of libraries and frameworks available (e.g., React, Angular, [Link]).
o NPM (Node Package Manager) offers thousands of reusable packages.
8. Full-Stack Development
o JavaScript is not just for frontend; with [Link], it can also be used on the backend.
9. Large Community Support
o Massive community means more tutorials, tools, job opportunities, and help.
10. DOM Manipulation
o Can dynamically update content, styles, and structure of a web page without reloading.

Variable:
A variable is like a container or storage space used to store data (numbers, strings, objects, etc.).
Example:
var x = 10;
let y = 20;
const z = 30;

Rules for Naming Variables in JavaScript


Variables are names used to store data. But while naming them, JavaScript follows some important rules.
1. Variable name must start with a:
 Letter (a–z or A–Z)
 Underscore _
 Dollar sign $
✅ Valid:
let name = "John";
let _value = 50;
let $amount = 100;
✅ Invalid:
let 1name = "wrong"; // ✅ cannot start with a number

2. Can include letters, digits, _, and $ (after the first character)


✅ Valid:
let student1 = "Alice";
let $price = 99;
let user_name = "admin";
✅ Invalid:
let first-name = "Bob"; // ✅ hyphens are not allowed
3. No spaces allowed
✅ Valid and Use camelCase:
let firstName = "John";
✅ Invalid:
let first name = "John"; // ✅ space not allowed
4. JavaScript is case-sensitive
let Age = 25;
let age = 30;
➡✅ Age and age are two different variables.
5. Cannot use reserved keywords
✅ You cannot name variables using JavaScript keywords like:
let var = 10; // ✅
let for = "loop"; // ✅
let if = true; // ✅
These are reserved for JavaScript syntax.
Good Variable Names
 Use meaningful names: userName, totalMarks
 Follow camelCase convention (common practice in JS)
 Avoid short or unclear names like x, temp1 unless temporary

Types of Variables
There are three types of variables in JavaScript, based on how they are declared:

[Link]
 var is used to declare variables in JavaScript.
 It was the original way to declare variables before let and const were introduced in ES6.
 It is function-scoped, meaning it is only visible inside the function where it is declared.
 It is hoisted to the top of its scope and initialized with undefined.

Key Features of var:
Feature Description
Re-assignable ✅ Yes – value can be changed after declaration
Re-declarable ✅ Yes – can be re-declared in the same scope
Scope Function-scoped – accessible throughout the function where declared
Hoisting ✅ Yes – hoisted and initialized as undefined (can be used before declaration)

Syntax:
var variableName = value;
 var: var is a keyword in JavaScript used to declare a variable.
 variableName: the name of the variable
 value: (optional) the value to assign

Example:

var a = 5; // 2. Declaration + initialization


[Link]("After init, a is:", a);

Output: a is: 5
2. Let
The let keyword is used in JavaScript to declare variables that can be changed (re-assigned) but cannot be
re-declared in the same scope.
It was introduced in ES6 (ECMAScript 2015) as a modern replacement for var.
Key Features of let:

Feature Description
Re-assignable ✅ Yes – value can be changed after declaration
Re-declarable ✅ No – in the same scope, re-declaring causes error
Scope Block-scoped – only accessible inside {}
Hoisting ✅ Yes – but in Temporal Dead Zone (TDZ), so can't be used before declared
Syntax:
let variableName = value;
 variableName: the name you give to the variable
 value: the data you store (optional at declaration)

Example:
let name = "Alice";
[Link](name);

Output: Alice

[Link]
constis a keyword used to declare variables whose values cannot be re-assigned after they are
initialized.
It was introduced in ES6 (2015) as a safer way to declare constant values.

Key Features of const:


Feature Description
Re-assignable ✅ No – once assigned, the value cannot be changed
Re-declarable ✅ No – cannot be re-declared in the same scope
Scope Block-scoped – only accessible inside {}
Hoisting ✅ Yes – hoisted but in Temporal Dead Zone (TDZ), so can't be used before declared

Syntax:
const variableName = value;

Examples:
� 1. Constant with primitive value:
const pi = 3.14;
[Link](pi);

Output: 3.14

// pi = 3.14159; ✅ Error: Assignment to constant variable


Difference Between var, let, and const
Feature var let const
✅ Yes ✅ Yes ✅ No (fixed after assignment)
Re-
var a = 10; a = 20; let b = 30; b = 40; const c = 50; c = 60; //
assignable
[Link](a); [Link](b); ✅ Error
✅ Yes (in same scope) ✅ No ✅ No
Re-declarable var x = 5; var x = 15; let y = 10; let y = 20; const z = 25; const z = 35;
[Link](x); ✅ Error ✅ Error
Function-scoped Block-scoped ({ }) Block-scoped ({ })
Scope { var m = 100; } { let n = 200; } { const p = 300; }
[Link](m); [Link](n); [Link](p);
✅ Yes (initialized as ✅ Yes (TDZ – cannot use before ✅ Yes (TDZ – cannot use before
undefined) declaration) declaration)
Hoisting
[Link](x); [Link](y); [Link](z);
var x = 10; let y = 20; const z = 30;
✅ No ✅ No ✅ Yes (must assign at declaration)
Must var a; let b; const c;
initialize? a = 5; b = 10; c = 15;
[Link](a); [Link](b); ✅ Error
ES5 (old JavaScript) ES6 (modern JavaScript) ES6 (modern JavaScript)
Introduced in
✅ JavaScript ES5 (Old) ✅ JavaScript ES6 (Modern) ✅ JavaScript ES6 (Modern)

Explanation :
Re-assignable
 var and let both allow you to change the value of a variable after it has been declared.
 const does not allow reassignment — once a value is assigned, it cannot be changed.

� Re-declarable
 var can be declared multiple times in the same scope without error.
 let and const cannot be re-declared in the same scope. Doing so causes a syntax error.

� Scope
 var is function-scoped, meaning it is visible anywhere inside the function where it's declared.
 let and const are block-scoped, meaning they are only accessible within the {} block where they are
declared.

� Hoisting
 All three (var, let, const) are hoisted to the top of their scope.
 However:
o var is initialized as undefined, so you can access it before its declaration (though it's not
recommended).
o let and const are hoisted but are in a Temporal Dead Zone (TDZ) — meaning they cannot be
accessed before the line where they are declared.

� Must Initialize?
 var and let can be declared without an initial value.
 const must be initialized at the time of declaration — it requires a value immediately.

� Introduced In
 var was part of the older JavaScript standard — ES5.
 let and const were introduced in ES6 (ES2015) and are part of modern JavaScript practices.

Data types
1. Primitive Data Types (Immutable)
String String
 Description: A sequence of characters enclosed in quotes. Used for text data.
 Syntax: Use single (') or double (") quotes.
Example:
 <!DOCTYPE html>
<html xmlns="[Link]
<head>
<meta charset="UTF-8">
<title> String </title>
</head>
<body>
<script>
let greeting = "Hello";
let name = 'Alice';
[Link](greeting + " " + name);
</script>
</body>
</html>

Output:

2. Number
 Description: Represents both integers and floating-point (decimal) numbers.
Example:
 <!DOCTYPE html>
<html xmlns="[Link]
<head>
<meta charset="UTF-8">
<title> Number </title>
</head>
<body>
<script>
let age = 25;
let price = 99.99;
[Link](age + price);
</script>
</body>
</html>

Output:

3. Boolean
 Description: Represents only two values – true or false. Commonly used in conditions and logic.
Example:
<!DOCTYPE html>
<html xmlns="[Link]
<head>
<meta charset="UTF-8">
<title> Boolean </title>
</head>
<body>
<script>
let isLoggedIn = true;
let hasPermission = false;
[Link](isLoggedIn && hasPermission);
</script>
</body>
</html>

Output:

4. Undefined
 Description: A variable that has been declared but not assigned a value yet.
Example:
<!DOCTYPE html>
<html xmlns="[Link]
<head>
<meta charset="UTF-8">
<title> Undefined </title>
</head>
<body>
<script>
let a;
[Link](a);
</script>
</body>
</html>
Output:

5. Null

Description: Explicitly represents "no value". You assign null to indicate emptiness.
Example:
<!DOCTYPE html>
<html xmlns="[Link]
<head>
<meta charset="UTF-8">
<title> Null </title>
</head>
<body>
<script>
let student = null;
[Link](student);
</script>
</body>
</html>
Output:

6. BigInt

Description: Used to represent integers larger than the Number type can handle (beyond 2^53).

Syntax: Add n at the end of the number.
Example:
<!DOCTYPE html>
<html xmlns="[Link]
<head>
<meta charset="UTF-8">
<title> BigInt e</title>
</head>
<body>
<script>
let bigNumber = 123456789012345678901234567890n;
[Link](bigNumber);
</script>
</body>
</html>
Output:

7. Symbol
 Description: Represents a unique identifier. Commonly used as keys for object properties to avoid
name conflicts.
Example:
<!DOCTYPE html>
<html xmlns="[Link]
<head>
<meta charset="UTF-8">
<title> Symbol </title>
</head>
<body>
<script>
let id1 = Symbol("id");
let id2 = Symbol("id");
[Link](id1 === id2);
</script>
</body>
</html>
Output:

1. Primitive Data Types (Immutable)


These are the basic building blocks of data in JavaScript.
Data Type Description Example
String Sequence of characters (text) "Hello" or 'Hi'
Number Numeric values (integers & decimals) 42, 3.14
Boolean Logical values: true or false true, false
Undefined A variable that has been declared but not assigned let a; → a is undefined
Null Represents “no value” or “empty” let x = null;
BigInt For large integers beyond Number limit 12345678901234567890n
Symbol Unique and immutable value (for object keys) Symbol("id")

2. Non-Primitive (Reference) Data Types


Used to store collections or complex data.

1. Object
1)Description: A collection of key-value pairs. Each key (also called a property) has a value. Used to
group related data.
2) Syntax: Curly braces {} with properties inside.
Example:
3) <!DOCTYPE html>
<html xmlns="[Link]
<head>
<meta charset="UTF-8">
<title> object </title>
</head>
<body>
<script>
let person = {
name: "John",
age: 30,
isEmployed: true
};
[Link]([Link]); // Output: John
[Link](person["age"]); // Output: 30
</script>
</body>
</html>

Example:

2. Array
 Description: An ordered list of values, stored in a single variable. Values can be of any type.
 Syntax: Square brackets [], values separated by commas.

Example:

3. Function
 Description: A block of reusable code that performs a specific task. Functions can accept input
(parameters) and return output.
 Syntax: Use the function keyword or arrow => syntax.
Example:
<!DOCTYPE html>
<html xmlns="[Link]
<head>
<meta charset="UTF-8">
<title> function </title>
</head>
<body>
<script>
function greet(name) {
return "Hello, " + name;
}
[Link](greet("Alice")); // Output: Hello, Alice

</script>
</body>
</html>
Output:

4. Date
 Description: Represents date and time. JavaScript provides the built-in Date object for working with
dates.
 Syntax: new Date() creates a new date instance.
Example:

<!DOCTYPE html>
<html xmlns="[Link]
<head>
<meta charset="UTF-8">
<title> function </title>
</head>
<body>
<script>
let now = new Date();
[Link](now); // Output: Current date and time

let specificDate = new Date("2024-12-25");


[Link](specificDate); // Output: Wed Dec 25 2024 ...

</script>
</body>
</html>

Output:

2. Non-Primitive (Reference) Data Types


Used to store collections or complex data.

Data Type Description Example


Object Key-value pairs { name: "John", age: 30 }
Array Ordered list of values [10, 20, 30]
Function Block of reusable code function greet() {}
Date Date and time objects new Date()

Dynamic Typing
JavaScript is a dynamically typed language, which means:
 You don’t need to declare a variable’s type.
 A variable can change its type at runtime.
let data = 10; // Number
data = "hello"; // Now it's a String
Expression and operators
What is an Expression ?
An expression is a piece of code that produces a value.
If something evaluates to a value, it’s an expression.
Examples:
5+3 // 8 → Arithmetic expression
"Hi" + " there" // "Hi there" → String expression
x = 10 // → Assignment expression
Types of Expressions:
Type Example Description
Arithmetic 3 + 4 Resol ves to 7
String 'Hello ' + 'World' Resolves to 'Hello World'
Logical true && false Resolves to false
Variable x = 10 Assignment expression
Function Call myFunc(5) Calls function with argument

Operators
In JavaScript, an operator is a symbol that performs an operation on one or more values (called
operands) to produce a result.
In simple words:
An operator manipulates values and helps you do things like math, comparisons, assignments, logical
decisions, etc.
1. Arithmetic Operators
2. Assignme1nt Operators 1. Arithmetic
3. Comparison Operators
Operators
4. Logical Operators [Link] 7. Type
5. String Operator Operators Operators
6. Ternary (Conditional) Operator
6. Ternary
7. Type Operators [Link]
(Conditional)
Operators
Operator
Operators
4. Logical 5. String
1. Arithmetic Operators Operators Operator
Used to perform basic mathematical operations.
Operator Meaning Example Result
+ Addition 4+2 6
- Subtraction 4-2 2
* Multiplication 4*2 8
/ Division 4/2 2
% Modulus (remainder) 5 % 2 1
** Exponentiation 2 ** 3 8

Example:
<!DOCTYPE html>
<html xmlns="[Link]
<head>
<meta charset="UTF-8">
<title> Arithmetic Operators </title>
</head>
<body>
<script>
// Declare two numbers
let a = 4;
let b = 2;
let c = 5;

// Perform arithmetic operations


[Link]("Addition (4 + 2):", a + b); // 6
[Link]("Subtraction (4 - 2):", a - b); // 2
[Link]("Multiplication (4 * 2):", a * b); // 8
[Link]("Division (4 / 2):", a / b); // 2
[Link]("Modulus (5 % 2):", c % b); // 1
[Link]("Exponentiation (2 ** 3):", b ** 3); // 8

</script>
</body>
</html>
Output:

Addition (4 + 2): 6
Subtraction (4 - 2): 2
Multiplication (4 * 2): 8
Division (4 / 2): 2
Modulus (5 % 2): 1
Exponentiation (2 ** 3): 8
2. Assignment Operators
Used to assign values to variables.
Operator Description Example Result
= Assign value x = 10 x is 10
+= Add and assign x += 2 x=x+2
-= Subtract and assign x -= 2 x=x-2
*= Multiply and assign x *= 2 x=x*2
/= Divide and assign x /= 2 x=x/2

Example:
<!DOCTYPE html>
<html xmlns="[Link]
<head>
<meta charset="UTF-8">
<title> Assignment Operators </title>
</head>
<body>
<script>
// Initial assignment using '='
let x = 10;
[Link]("Initial value of x:", x); // x = 10

// Use of += (Add and assign)


x += 2; // x = x + 2
[Link]("After x += 2:", x); // 12

// Use of -= (Subtract and assign)


x -= 2; // x = x - 2
[Link]("After x -= 2:", x); // 10

// Use of *= (Multiply and assign)


x *= 2; // x = x * 2
[Link]("After x *= 2:", x); // 20

// Use of /= (Divide and assign)


x /= 2; // x = x / 2
[Link]("After x /= 2:", x); // 10

</script>
</body>
</html>

Output:

Output:
Initial value of x: 10
After x += 2: 12
After x -= 2: 10
After x *= 2: 20
After x /= 2: 10
3. Comparison Operators
Used to compare two values (returns true or false).
Operator Meaning Example Result
== Equal to (value only) 5 == '5' true
=== Strictly equal (value + type) 5 === '5' false
!= Not equal (value only) 5 != 3 true
!== Strictly not equal 5 !== '5' true
> Greater than 6>3 true
< Less than 2<5 true
>= Greater than or equal 5 >= 5 true
<= Less than or equal 3 <= 2 false
Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> Comparison Operators </title>
</head>
<body>
<script>
let a = 10;
let b = "10";
let c = 5;

// == : Equal (value only)


[Link]("a == b:", a == b); // true

// === : Strict Equal (value + type)


[Link]("a === b:", a === b); // false

// != : Not equal (value only)


[Link]("a != c:", a != c); // true
// !== : Strict Not equal (value + type)
[Link]("a !== b:", a !== b); // true

// > : Greater than


[Link]("a > c:", a > c); // true

// < : Less than


[Link]("c < a:", c < a); // true

// >= : Greater than or equal


[Link]("a >= b:", a >= b); // true

// <= : Less than or equal


[Link]("c <= a:", c <= a); // true
</script>
</body>
</html>

Output:

a == b: true
a === b: false
a != c: true
a !== b: true
a > c: true
c < a: true
a >= b: true
c <= a: true

4. Logical Operators
Used to combine or modify Boolean values.
Operator Meaning Example Result
&& Logical AND true && false false
` ` Logical OR
! Logical NOT !true false

<!DOCTYPE html>
<html xmlns="[Link]
<head>
<meta charset="UTF-8">
<title> Logical Operators </title>
</head>
<body>
<script>
// Define boolean values
let a = true;
let b = false;

// Logical AND (&&)


[Link]("a && b:", a && b); // false (both must be true)

// Logical OR (||)
[Link]("a || b:", a || b); // true (at least one is true)

// Logical NOT (!)


[Link]("!a:", !a); // false (a is true, !a is false)
[Link]("!b:", !b); // true (b is false, !b is true)

// Use in condition
let age = 25;
let hasID = true;

if (age >= 18 && hasID) {


[Link]("Entry allowed");
} else {
[Link]("Entry denied");
}

let isStudent = false;


let hasCoupon = true;

if (isStudent || hasCoupon) {
[Link]("Discount applied");
} else {
[Link]("No discount");
}

</script>
</body>
</html>

Output:

Output:
a && b: false
a || b: true
!a: false
!b: true
Entry allowed
Discount applied

5. String Operator
Only + is used to combine (concatenate) strings.
"Hello" + " World" // Output: "Hello World"
6. Ternary Operator
The Ternary Operator is a short-hand form of if...else statement in JavaScript.
It is called "ternary" because it takes three operands:
1. A condition
2. A value if true
3. A value if false

Syntax:
Condition? expression_if_true : expression_if_false;

Example:
<!DOCTYPE html>
<html xmlns="[Link]
<head>
<meta charset="UTF-8">
<title> Ternary Operator</title>
</head>
<body>
<script>
// Example 1: Age check
let age = 17;
let message = (age >= 18) ? "You are an adult" : "You are a minor";
[Link]("Age Check:", message);

// Example 2: Even or Odd


let number = 9;
let result = (number % 2 === 0) ? "Even" : "Odd";
[Link]("Even/Odd Check:", result);

// Example 3: Positive, Negative, or Zero


let value = -10;
let status = (value > 0) ? "Positive" : (value < 0) ? "Negative" : "Zero";
[Link]("Number Type:", status);

// Example 4: Login check


let isLoggedIn = true;
let greeting = isLoggedIn ? "Welcome back!" : "Please log in.";
[Link]("Login Greeting:", greeting);

</script>
</body>
</html>
Output:

Output in Console:
Age Check: You are a minor
Even/Odd Check: Odd
Number Type: Negative
Login Greeting: Welcome back!
Type Operators
Type Operators in JavaScript are special keywords used to check or identify the type of a value or
object.
They help developers:
 Understand what kind of data is stored in a variable
 Verify the structure/type of objects at runtime
1. typeof Operator
✅ Used to find the primitive type of a value.
Example:
[Link](typeof "Hello"); // Output: "string"
[Link](typeof 123); // Output: "number"
[Link](typeof true); // Output: "boolean"
2. instanceof Operator
Used to check whether an object is created from a particular class or constructor.
Example:
let arr = [1, 2, 3];
[Link](arr instanceof Array); // Output: true
[Link](arr instanceof Object); // Output: true
Flow Control (Control Flow)
Flow control (or control flow) in JavaScript refers to the order in which statements are executed in a
program.
Types of Flow Control:
1. Sequential Flow
2. Conditional Flow (Decision Making)
3. Looping / Iterative Flow

1. Sequential Flow
 Code runs line by line from top to bottom.
let a = 10;
let b = 20;
let sum = a + b;
[Link](sum); //

output: 30

2. Conditional Flow (Decision Making)


 Executes different code based on conditions.
1..if Statement:
The if statement is used to execute a block of code only when the condition is true.
If the condition is false, the code inside the if block is skipped.
Syntax:
if (condition) {
// code runs if condition is true
}

let age = 18;


if (age >= 18) {
[Link]("You are an adult.");
}
Output:
You are an adult.
Because age is 18 and the condition age >= 18 is true.
Applications of If Conditional Statement:
 Validating user inputs.
 Basic decision-making in algorithms.
Advantages of If Conditional Statement:
 Simple and straightforward.
 Useful for handling basic decision logic.
Disadvantages of If Conditional Statement:
 Limited to checking only one condition at a time.
 Not suitable for complex decision-making.
2….if...else Statement:
The if-else statement extends the if statement by adding an else clause.
If the condition is false, the program executes the code in the else block.
Syntax:
if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}

Example:
let marks = 40;
if (marks >= 50) {
[Link]("Pass");
} else {
[Link]("Fail");
}
Output:
Fail
Because marks = 40, and the condition marks >= 50 is false.
Applications of If-Else Conditional Statement:
 Error handling: For example, displaying an error message if user input is invalid.
 Program flow control: Directing program execution based on conditions.
Advantages of If-Else Conditional Statement:
 Handles binary decisions efficiently.
 Clear and concise syntax.
Disadvantages of If-Else Conditional Statement:
 Limited to binary decisions.
 May become verbose in complex scenarios.

3…. else if Ladder:


The if-else if statement allows for multiple conditions to be checked in sequence. If the if
condition is false, the program checks the next else if condition, and so on.
Syntax:

if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
// code to execute if condition2 is true
} else {
// code to execute if all conditions are false
}

In else if statements, the conditions are checked from the top-down, if the first block returns
true, the second and the third blocks will not be checked, but if the first if block returns false,
the second block will be checked. This checking continues until a block returns a true
outcome.
Example:
let score = 75;
if (score >= 90) {
[Link]("Grade A+");
} else if (score >= 80) {
[Link]("Grade A");
} else if (score >= 70) {
[Link]("Grade B");
} else if (score >= 60) {
[Link]("Grade C");
} else if (score >= 50) {
[Link]("Grade D");
} else {
[Link]("Fail");
}
Output:
Grade B
Because score = 75, so the condition score >= 75 is true. First if is false, but else if is true.

Applications of If-Elif-Else Conditional Statement:


 Implementing menu selection logic.
 Categorizing data based on multiple criteria.
Advantages of If-Elif-Else Conditional Statement:
 Allows handling multiple conditions in a structured manner.
 Reduces the need for nested if-else statements.
Disadvantages of If-Elif-Else Conditional Statement:
 Can become lengthy and harder to maintain with many conditions.
 The order of conditions matters; incorrect ordering can lead to unexpected behaviour.

4…switch Statement:

The switch statement is used when you need to check a variable against a series of values. It’s
often used as a more readable alternative to a long if-else if chain.
In switch expressions, each block is terminated by a break keyword. The statements in switch
are expressed with cases.
Switch Conditional Statement Syntax:
switch (variable) {
case value1:
// code to execute if variable equals value1
break;
case value2:
// code to execute if variable equals value2
break;
default:
// code to execute if variable doesn't match any value
}

let day = 3;
switch(day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
default: [Link]("Invalid Day");
}

Output:
Wednesday
Because day = 3, so it matches case 3 and prints "Wednesday".
Applications of Switch Statement:
 Processing user choices in a menu.
 Implementing state machines.
Advantages of Switch Statement:
 Provides a clean and efficient way to handle multiple cases.
 Improves code readability when dealing with many conditions.
Disadvantages of Switch Statement:
 Limited to equality comparisons, cannot use range checks or complex conditions.
 Lack of fall-through control can lead to unintentional bugs if not used carefully.

Object
In JavaScript, an object is a collection of properties.
 A property is a key-value pair.
 Keys are always strings (or symbols).
 Values can be any data type (string, number, boolean, array, function, even another object).

Syntax of an Object
let objectName = {
key1: value1,
key2: value2,
key3: value3
};

Example 1: Simple Object


let car = {
brand: "Toyota",
model: "Corolla",
year: 2022,
color: "White"
};
[Link]([Link]); // Toyota
[Link](car["year"]); // 2022
Here:
 brand, model, year, color → properties (keys)
 "Toyota", "Corolla", 2022, "White" → values
Example 3: Nested Object
let student = {
name: "Nargis",
rollNo: 101,
marks: {
maths: 90,
english: 85,
science: 92
}
};
[Link]([Link]); // 90

Example 4: Object with Array

let library = {
books: ["JavaScript", "Python", "C++"]
};

[Link]([Link][1]); // Python
Features of Objects in JavaScript
1. Key-Value Pair Structure
o Objects store data as properties (key-value pairs).
let car = { brand: "BMW", year: 2024 };
2. Dynamic Nature
o Properties can be added, modified, or removed anytime.
[Link] = "Black"; // add new property
delete [Link]; // remove property
3. Methods (Functions Inside Objects)
o Objects can hold both data and behaviour.
let person = {
name: "Amit",
greet: function() { return "Hi, " + [Link]; }
};
4. Nested Objects
o An object can contain another object.
let student = {
name: "Nargis",
marks: { math: 90, science: 85 }
};
5. Objects are Mutable
o Even if declared with const, object contents can be changed.
const obj = { x: 1 };
obj.x = 2; // valid
6. Reference Type
o Objects are stored and copied by reference, not by value.
let a = { value: 10 };
let b = a;
[Link] = 20;
[Link]([Link]); // 20
7. Prototype-based
o JavaScript objects are built on prototypes, supporting inheritance.
Advantages of Using Objects
1. Organized Data Representation
o Objects help represent real-world entities in code (like car, student, employee).
2. Reusability
o Functions inside objects (methods) can be reused without rewriting code.
3. Encapsulation
o Objects group related data and functions together.
4. Flexibility
o Easy to update, add, or remove properties dynamically.
5. Readable & Manageable
o Code becomes more structured and easier to understand.
6. Supports Complex Data
o Can store arrays, other objects, and even functions.
7. Foundation of OOP in JS
o Objects form the basis for advanced concepts like Classes, Inheritance, Polymorphism.
Array
An array in JavaScript is a special type of object used to store multiple values in a single variable.
 Each value is called an element.
 Each element has an index (position number).
 Index starts from 0 (first element).
Example: A basket that contains many fruits (apple, mango, banana) is like an array.
Syntax of an Array
let arrayName = [value1, value2, value3, ...];
Array Initialization
Initialization of an array means creating an array and assigning values to it when it is declared (or
later).

Ways to Initialize an Array in JavaScript


1. Using Square Brackets [] (Most Common)
let fruits = ["Apple", "Banana", "Mango"]; // initialized with values
let emptyArr = []; // initialized empty

[Link](fruits); // ["Apple", "Banana", "Mango"]


[Link](emptyArr); // []

2. Using new Array() Constructor


let numbers = new Array(10, 20, 30); // initialized with values
[Link](numbers); // [10, 20, 30]

let emptyArr = new Array(); // empty array


[Link](emptyArr); // []
⚠✅ Note:
If you pass a single number to new Array(), it creates an empty array of that length, not with that number.
let arr = new Array(5);
[Link](arr); // [ <5 empty items> ] → array with length 5 but no values

3. Initialize with Mixed Data Types


let student = ["Nargis", 25, true, { grade: "A" }];
[Link](student);
// ["Nargis", 25, true, { grade: "A" }]

4. Initialize Using Loops


let squares = [];
for(let i = 1; i <= 5; i++) {
[Link](i * i);
}
[Link](squares); // [1, 4, 9, 16, 25]

5. Initialize Using [Link]() or [Link]()


let arr1 = [Link](1, 2, 3, 4);
[Link](arr1); // [1, 2, 3, 4]

let arr2 = new Array(5).fill(0);


[Link](arr2); // [0, 0, 0, 0, 0]

Different types Array:


JavaScript has only one array type (all arrays are objects),
but based on usage and data organization, we categorize arrays into different types.

1. Single-Dimensional Array
 Stores data in a single row (like a simple list).
let fruits = ["Apple", "Banana", "Mango"];

[Link](fruits[0]); // Apple
[Link](fruits[2]); // Mango

2. Multi-Dimensional Array (Array of Arrays)


 An array that contains another array.
 Commonly used as matrix or table.
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];

[Link](matrix[0][1]); // 2 (row 0, column 1)


[Link](matrix[2][2]); // 9 (row 2, column 2)

3. Array of Objects
 Each element in the array is an object.
 Very useful in real-world applications (e.g., storing records).
let students = [
{ name: "Amit", age: 21 },
{ name: "Nargis", age: 22 },
{ name: "Rahul", age: 23 }
];

[Link](students[0].name); // Amit
[Link](students[2].age); // 23

4. Sparse Array
 An array with missing elements (some indexes empty).
let arr = [10, , 30];
[Link](arr[1]); // undefined
[Link]([Link]); // 3

5. Dynamic Array
 JavaScript arrays are dynamic by nature, meaning size can grow/shrink automatically.
let numbers = [1, 2];
[Link](3); // add at end
numbers[10] = 99; // add at specific index

[Link](numbers);
// [1, 2, 3, empty × 7, 99]
[Link]([Link]); // 11

6. Typed Arrays (Special)


 Introduced in ES6.
 Used for handling binary data (e.g., images, audio, raw memory).
 Examples: Int8Array, Uint8Array, Float32Array.
let typedArr = new Int16Array([10, 20, 30]);
[Link](typedArr[1]); // 20

Summary Table
Type of Array Description Example
Single-Dimensional Simple list of elements [1, 2, 3]
Multi-Dimensional Array of arrays (matrix) [[1,2],[3,4]]
Array of Objects Elements are objects [{name:"Amit"}, {name:"Nargis"}]
Sparse Array Some indexes are missing [1, , 3]
Dynamic Array Grows or shrinks automatically push(), pop()
Typed Array (Special) For binary/low-level data handling new Int8Array([1,2,3])

Common Operations on Arrays


1. Create / Initialize an Array
Creating a new array with elements using [] or new Array().
let fruits = ["Apple", "Banana", "Mango"];
[Link](fruits); // ["Apple", "Banana", "Mango"]
2. Access Elements
Retrieving an element by its index (e.g., arr[0]).
[Link](fruits[0]); // Apple
[Link](fruits[2]); // Mango

3. Update Elements
Changing the value of an element at a specific index.
fruits[1] = "Orange";
[Link](fruits); // ["Apple", "Orange", "Mango"]

4. Add Elements
Adds an element
 At the end → push()
Adds an element at the end of the array.
[Link]("Grapes");
[Link](fruits); // ["Apple", "Orange", "Mango", "Grapes"]
 At the beginning → unshift()
Adds an element at the beginning of the array.
[Link]("Pineapple");
[Link](fruits); // ["Pineapple", "Apple", "Orange", "Mango", "Grapes"]
 At specific index → splice()
Adds or removes elements at a specific index.
[Link](2, 0, "Kiwi");
[Link](fruits); // ["Pineapple", "Apple", "Kiwi", "Orange", "Mango", "Grapes"]

5. Remove Elements
 From end → pop()
Removes the last element of the array.
[Link]();
[Link](fruits); // last element removed
 From beginning → shift()
Removes the first element of the array.
[Link]();
[Link](fruits); // first element removed
 From specific index → splice()
Adds or removes elements at a specific index.
[Link](1, 2); // remove 2 elements starting at index 1
[Link](fruits);

6. Search in Array
 Find index → indexOf()
Returns the index of the first occurrence of an element.
[Link]([Link]("Mango")); // 2
 Check existence → includes()
Checks if an element exists (returns true/false).
[Link]([Link]("Apple")); // true

8. Traverse / Loop through Array


Iterates over each element of the array.
for (let i = 0; i < [Link]; i++) {
[Link](fruits[i]);
}

// OR using forEach
[Link](fruit => [Link](fruit));
9. Sort and Reverse
sort() → Sorts array elements in ascending or alphabetical order.
reverse() → Reverses the order of elements in the array.
slice() → Extracts a portion of the array (without modifying the original).
concat() → Joins two or more arrays into one.

let numbers = [30, 10, 50, 20];


[Link]();
[Link](numbers); // [10, 20, 30, 50] (lexical sort)

[Link]();
[Link](numbers); // [50, 30, 20, 10]

10. Join and Split


join() → Converts an array into a string with separators.
split() → Splits a string into an array based on a delimiter.

let str = [Link](", ");


[Link](str); // "Apple, Orange, Mango"

let arr = [Link](", ");


[Link](arr); // ["Apple", "Orange", "Mango"]

11. Map, Filter, Reduce (Advanced)


map() → Creates a new array by applying a function to each element.
filter() → Returns a new array with elements that satisfy a condition.
reduce() → Reduces the array to a single value (e.g., sum).
 Map → create new array by applying function
let nums = [1, 2, 3];
let squares = [Link](x => x * x);
[Link](squares); // [1, 4, 9]
 Filter → select elements
let even = [Link](x => x % 2 === 0);
[Link](even); // [2]
 Reduce → reduce to single value
let sum = [Link]((acc, val) => acc + val, 0);
[Link](sum); // 6

Functions
Functions in JavaScript are reusable blocks of code designed to perform specific tasks. They
allow you to organize, reuse, and modularize code. It can take inputs, perform actions, and
return outputs

Example :

function sum(x, y) {
return x + y;
}
[Link](sum(6, 9));

// output: 15
Create a Function in JavaScript
A function in JavaScript can be created in multiple ways, but the most basic way is by using the function
keyword.
The general syntax is:
function functionName(parameters) {
// code block to be executed
return value; // optional
}
� Step-by-step Explanation
1. Use the function keyword – Every function begins with the function keyword in JavaScript (unless
you are using arrow functions).
This tells JavaScript that you are creating a function.
2. Give the function a name – After the function keyword, you write a name (like add, greet, etc.).
This name is how you will later call or “invoke” the function.
3. Add parentheses () – Inside the parentheses, you can define parameters (like a, b) which act as
placeholders for input values.
If you don’t need input, just leave the parentheses empty.
4. Write the code inside {} curly braces – Everything between {} is the function body.
This is where you put the instructions that should run when the function is called.
5. Use return (optional) – If you want the function to give back a value, you use the return keyword.
If you don’t return anything, the function will run but return undefined.
6. Call the function – To use the function, write its name followed by parentheses ().
If the function has parameters, pass arguments inside those parentheses.
Example 1: Simple Function (No Parameters)
function greet() {
[Link]("Hello, Welcome to JavaScript!");
}
greet(); // Calling the function
 Here, the function name is greet.
 It has no parameters.
 It prints a message when called.

Example 2: Function with Parameters


function add(a, b) {
return a + b;
}
[Link](add(5, 10)); // Output: 15
 The function add takes two inputs (a and b).
 Inside the function body, it adds them.
 The return keyword gives the result back.

Example 3: Function without Return


function sayHello(name) {
[Link]("Hello, " + name);
}
sayHello("Anisha");

// Output: Hello, Anisha


 This function accepts an argument (name).
 Instead of returning, it directly prints the message.
 Such functions are often used for actions instead of calculations.
Types of Functions in JavaScript (with Examples)
Type Explanation (2–3 lines) Example
Traditional way using function keyword with
1. Function
a name. Hoisted, so can be called before js function greet() { [Link]("Hello!"); } greet();
Declaration
defined.
2. Function Function stored in a variable. Not hoisted. js const add = function(a, b) { return a + b; };
Expression Useful in callbacks and modular code. [Link](add(2,3));
3. Arrow Short syntax, doesn’t have its own this. Good
js const square = n => n * n; [Link](square(4));
Function (ES6) for concise code and array methods.
4. Anonymous Function without a name, often used as js setTimeout(function() { [Link]("Hi"); }, 1000);
Type Explanation (2–3 lines) Example
Function callback or inside timers/events.
Immediately runs after creation, creates
5. IIFE js (function(){ [Link]("IIFE runs!"); })();
private scope. Used for initialization.
6. Recursive Function that calls itself until a base js function fact(n){ return n<=1?1:n*fact(n-1);}
Function condition is met. Useful in algorithms. [Link](fact(5));
7. Constructor Special function used with new to create js function Person(n){ [Link]=n; } let p=new
Function objects (before ES6 classes). Person("Ali"); [Link]([Link]);
8. Higher-Order Takes/returns another function. Common in js function twice(fn){ return x=>fn(fn(x)); } const
Function map, filter, reduce. double=x=>x*2; [Link](twice(double)(3));
9. Callback Passed as argument to another function, js function process(n,cb){ return cb(n);}
Function executed later (async tasks). [Link](process(5,x=>x*2));
10. Generator Declared with function*, yields values one by js function* gen(){ yield 1; yield 2;} let g=gen();
Function one on demand. [Link]([Link]().value);
11. Async Declared with async, always returns a js async function getData(){ return "Done"; }
Function Promise. Uses await for async ops. getData().then([Link]);

Advantages and Disadvantages of Functions

Advantages of Functions
1. Code Reusability
o You write a function once and can use it multiple times in different places.
o Example: A sum(a, b) function can be reused for different numbers.
2. Modularity (Divide and Conquer)
o Functions break a large program into smaller, manageable parts.
o This makes complex programs easier to understand and maintain.
3. Readability & Maintainability
o Functions give meaningful names (calculateTax, greetUser), making code self-explanatory.
o Easier to debug since each function handles only one task.
4. Avoids Repetition
o Instead of writing the same code again and again, functions reduce redundancy.
o Saves time and reduces chances of errors.
5. Testing and Debugging Becomes Easier
o You can test each function separately (unit testing).
o Easier to find where a bug is located.
6. Abstraction
o Users of a function don’t need to know its internal logic.
o Example: You can just call [Link](25) without worrying how it works inside.
7. Supports Asynchronous & Modular Programming
o In JavaScript, functions (callbacks, async/await) make it possible to handle async tasks.
o Functions allow modular programming by splitting logic into small reusable blocks.

Disadvantages of Functions
1. Overhead in Small Programs
o For very small tasks, creating functions might add unnecessary complexity.
o Example: Writing a function for just [Link]("Hello") is not efficient.
2. Memory Usage (Extra Function Calls)
o Each function call adds to the call stack, which consumes memory.
o Too many nested or recursive calls can cause a stack overflow error.
3. Debugging Across Functions Can Be Hard
o If a program uses too many functions, tracking the flow of execution may become confusing.
o
Especially true in callback-heavy code (callback hell).
4. Function Overhead in Performance
o In performance-critical code, repeatedly calling functions may be slightly slower compared to
inline code.
o (Though modern JavaScript engines optimize this well).
5. Dependency Management
o If one function depends on another, changing one may affect many parts of the program.
o Improper design can lead to “spaghetti code.”

What are Methods?


1. In JavaScript, a method is simply a function that belongs to an object.
2. Functions become methods when they are stored as a property of an object.
3. They are used to perform actions related to that object.
4. Methods can use the special keyword this to refer to the object they belong to.
5. Example:
let person = {
name: "Alex",
greet: function() {
[Link]("Hello, my name is " + [Link]);
}
};

[Link](); // Output: Hello, my name is lex


Here, greet is a method of the person object.

How to Create a Method?


 A method is created inside an object as a property with a function value.
Example:
let car = {
brand: "Toyota",
start() {
[Link]([Link] + " engine started!");
}
};

[Link](); // Output: Toyota engine started!

Types of Methods in JavaScript


1. Built-in Methods (provided by JavaScript itself):
String → Work with text (toUpperCase, includes).
Array → Work with lists (push, pop, reverse).
Math → Do calculations (sqrt, random).
Date → Handle dates/time (getFullYear, toDateString).
Number → Handle numbers (toFixed, parseInt).
Example:
let str = "Hello";
[Link]([Link]()); // "HELLO"
[Link]([Link]("He")); // true
2. User-defined Methods (created by the programmer inside objects):
Example:
let calculator = {
add: function(a, b) { return a + b; },
subtract: function(a, b) { return a - b; }
};

[Link]([Link](5, 3)); // 8
[Link]([Link](9, 4)); // 5
The object calculator works like a small calculator machine.
It has two buttons (methods): add and subtract.
When you press [Link](5,3), it gives you 8.
When you press [Link](9,4), it gives you 5.
Why Use Methods?
 To organize code related to an object.
 To avoid writing repeated code.
 To use this for accessing object properties easily.
 To make objects more real-world like (e.g., [Link](), [Link]()).
Regular Expression (Regex)
 A regular expression is a pattern used to find, search, or match text inside strings.
 For example: checking if a string contains numbers, validating an email, or finding a word.
2. How to Create Regex in JavaScript?
Two ways:
1. Regex literal:
let pattern = /abc/;
2. RegExp object:
let pattern = new RegExp("abc");

3. How to Match a Pattern?


 We use the .test() method → returns true or false.
Example:
let pattern = /hello/;
[Link]([Link]("hello world")); // true
[Link]([Link]("hi there")); // false

Creating a RegExp in JavaScript


There are two primary ways to create a RegExp in JavaScript
1. Using the RegExp Constructor
The RegExp constructor is useful when you need to create a regular expression dynamically,
such as when the pattern or flags might change based on user input or other conditions.

let pattern = "hello"; // Pattern to match


let flags = "i"; // Case-insensitive flag
let regex = new RegExp(pattern, flags);

let s = "Hello world";

[Link]([Link](s));

Output
true
 Here, we dynamically create a RegExp object using the RegExp() constructor.
 The pattern "hello" will match the string "Hello" because of the 'i' flag, which makes the
search case-insensitive.
 [Link](s) returns true because "Hello" matches the pattern "hello" in a case-insensitive
manner.

2. Using Regular Expression Literal


This is the most common and simple way to create a regular expression in JavaScript. It’s
especially useful when the pattern is static (doesn’t change dynamically).
let regex = /hello/i;

let s = "Hello world";

[Link]([Link](s));

Output
true
 In this example, we define the regular expression directly using literal notation.
 /hello/i means we're looking for the word "hello", and the 'i' flag ensures the search is
case-insensitive.
 [Link](s) returns true because "Hello" matches the pattern "hello" case-insensitively.
Regular Expression Modifiers can be used to perform multiline searches which can also be
set to case-insensitive matching:

Expressions Descriptions

g Find the character globally

i Find a character with case-insensitive matching

m Find multiline matching

Regular Expression Brackets can Find characters in a specified range

Expressions Description

[abc] Find any of the characters inside the brackets

[^abc] Find any character, not inside the brackets

[0-9] Find any of the digits between the brackets 0 to 9

[^0-9] Find any digit not in between the brackets

(x | y) Find any of the alternatives between x or y separated with |

Regular Expression Metacharacters are characters with a special meaning:


Metacharacter Description

\. Search single characters, except line terminator or newline.

\w Find the word character i.e. characters from a to z, A to Z, 0 to 9

\d Find a digit

\D Search non-digit characters i.e all the characters except digits

\s Find a whitespace character

\S Find the non-whitespace characters.

\b Find a match at the beginning or at the end of a word

\B Find a match that is not present at the beginning or end of a word.

\0 Find the NULL character.

\n Find the newline character.

\f Find the form feed character

\r Find the carriage return character

\t Find the tab character

\v Find the vertical tab character

\uxxxx Find the Unicode character specified by the hexadecimal number xxxxx

Regular Expression Quantifiers are used to define quantities occurrence

Quantifier Description

n+ Match any string that contains at least one n


Quantifier Description

n* Match any string that contains zero or more occurrences of n

n? Match any string that contains zero or one occurrence of n

m{X} Find the match of any string that contains a sequence of m, X times

m{X, Y} Find the match of any string that contains a sequence of m, X to Y times

m{X,} Find the match of any string that contains a sequence of m, at least X times

m$ Find the match of any string which contains m at the end of it

^m Find the match of any string which contains m at the beginning of it

?!m Find the match of any string which is not followed by a specific string m.

Regular Expression Object Properties:

Property Description

constructor Return the function that created the RegExp object’s prototype

global Specify whether the “g” modifier is set or not

ignorecase Specify whether the “i” modifier is set or not

lastindex Specify the index at which to start the next match

multiline Specify whether the “m” modifier is set or not

source Return the text of RegExp pattern

Regular Expression Object Methods:

Method Description

compile() Used to compile the regular expression while executing of script


Method Description

exec() Used to test for the match in a string.

test() Used to test for a match in a string

toString() Return the string value of the regular expression

Use Cases of Regular Expressions(examples):


1. Validating Email Addresses
Regular expressions are frequently used for validating emails. Here’s an example that matches
most email formats
let regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
[Link]([Link]("user@[Link]"));

Output
true
2. Extracting Specific Data from a String
You can use regular expressions to extract specific data from a string, like extracting all
numbers from a text.
let regex = /\d+/g;
let res = "There are 123 apples and 456 oranges".match(regex);
[Link](res);

Output
[ '123', '456' ]
3. Replacing Substrings
Regular expressions are often used in replacing certain substrings in text.
let regex = /foo/g;
let res = "foo bar foo".replace(regex, "baz");
[Link](res);

Output
baz bar baz

web page styles using JavaScript


JavaScript can manipulate HTML and CSS dynamically through the DOM (Document Object Model).
There are mainly 3 ways:

1. Change Inline Style with .style


We can directly access an element and change its style.
<!DOCTYPE html>
<html>
<body>
<h1 id="title">Welcome!</h1>
<button onclick="changeStyle()">Change Style</button>

<script>
function changeStyle() {
let heading = [Link]("title");
[Link] = "blue"; // text color
[Link] = "40px"; // font size
[Link] = "yellow"; // background
[Link] = "center"; // alignment
}
</script>
</body>
</html>
When the button is clicked, JavaScript applies new styles.

2. Use CSS Classes with .classList


Instead of writing styles inline, we can define CSS in <style> or a .css file and use JavaScript to
add/remove/toggle classes.
<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
color: white;
background: green;
padding: 10px;
border-radius: 8px;
}
</style>
</head>
<body>
<p id="para">This is a paragraph</p>
<button onclick="toggleStyle()">Toggle Style</button>

<script>
function toggleStyle() {
[Link]("para").[Link]("highlight");
}
</script>
</body>
</html>
Each time you click, the paragraph style switches.

3. Change Entire Stylesheet


We can even swap themes (like light/dark mode) by changing the CSS file using JavaScript.
<!DOCTYPE html>
<html>
<head>
<link id="theme" rel="stylesheet" href="[Link]">
</head>
<body>
<button onclick="switchTheme()">Switch to Dark Theme</button>

<script>
function switchTheme() {
[Link]("theme").href = "[Link]";
}
</script>
</body>
</html>
Clicking the button replaces the whole stylesheet.

In short:
 [Link] = "value" → directly change CSS property.
 [Link]/remove/toggle("classname") → use CSS classes with JS.
 [Link]("id").href = "[Link]" → change linked stylesheet.
What is AJAX
AJAX = Asynchronous JavaScript and XML
 It is not a programming language, but a web development technique.
 It allows a webpage to communicate with the server in the background and update parts of the
page without refreshing the whole page.
 It combines several existing technologies:
o HTML / CSS → to display content
o JavaScript → to control behavior
o DOM (Document Object Model) → to update page dynamically
o XML / JSON → formats to receive/send data
o HTTP (XMLHttpRequest) → to communicate with the server
Why “Asynchronous”?
 Normally, when you submit a form or click a link, the whole page reloads to get new data.
 With AJAX, requests are sent asynchronously (in the background).
 That means the user can continue using the page while new data loads.
 Example:
o While typing in Google Search, suggestions appear instantly without reloading the page.
Key Features of AJAX
1. Asynchronous
 The biggest strength of AJAX.
 Normally, when you send a request to a server, the whole web page reloads.
 With AJAX, the request is handled in the background (asynchronously).
 Only the required part of the page updates while the user continues working.
 Example: In Gmail, when you click on a new mail, only the message area updates — not the whole
page.

2. Cross-Platform
 AJAX uses standard technologies like JavaScript, HTML, and HTTP.
 Works on all major browsers (Chrome, Firefox, Edge, Safari, etc.).
 No extra plugins or software are required.
 Ensures a wide compatibility across devices (desktop, mobile, tablets).

3. Uses Existing Standards


 AJAX is not a new language — it’s a combination of existing web technologies:
o HTML & CSS → structure and presentation of the page.
o JavaScript → to create AJAX requests and handle responses.
o DOM (Document Object Model) → to update parts of the page dynamically.
o XML/JSON → formats for sending/receiving data.
o HTTP → the protocol for communication between browser and server.
 This makes AJAX easy to learn (if you know JavaScript and HTML).

4. Better User Experience


 Pages feel more like desktop applications (smooth and fast).
 User doesn’t see page flicker or reload → only small parts refresh.
 Reduces waiting time since only needed data is transferred.
 Results in interactive, responsive, and modern web apps.
 Examples: Auto-suggestions in search, live chat, instant notifications.
Technologies Used in AJAX
AJAX is not a single technology — it is a combination of several web standards working together.
1. HTML / CSS → For Presentation
 HTML (HyperText Markup Language):
Defines the structure of the webpage (headings, paragraphs, forms, buttons).
 CSS (Cascading Style Sheets):
Defines the style and look of the webpage (colors, fonts, layout).
 In AJAX, HTML/CSS are used to display content and results after the page is dynamically
updated.
Example:
A search box is created in HTML, styled with CSS, and AJAX updates the search results dynamically.
2. JavaScript → For Event Handling and Request
 JavaScript is the core language used in AJAX.
 It handles user events like clicks, typing, or submitting a form.
 Creates the XMLHttpRequest object (or modern fetch() API) to communicate with the server.
 Processes the server response and updates the web page.
Example:
When a user types in Google Search, JavaScript detects the keystroke and sends an AJAX request.
3. DOM (Document Object Model) → Update Page Dynamically
 DOM is a programming interface that represents the HTML structure as objects.
 AJAX uses DOM to change or update only specific parts of the page without reloading the whole
document.
 Example operations: changing text, inserting new elements, updating tables, etc.
Example:
[Link]("result").innerHTML = "New Data";
✅ Updates only the result area with fresh server data.
4. XML / JSON → Data Format for Exchange
 AJAX needs a format to send and receive data between browser and server.
 XML (eXtensible Markup Language):
o Older format, structured like HTML with tags.
o Example: <user><name>John</name></user>
 JSON (JavaScript Object Notation):
o Lightweight, faster, and widely used today.
o Example: { "name": "John" }
 JSON is preferred in modern web apps because it’s easier to read and use in JavaScript.

5. HTTP → Communication Protocol


 AJAX communicates with the server using HTTP (HyperText Transfer Protocol).
 Common request methods:
o GET → To request data (like reading a file or fetching database results).
o POST → To send data (like submitting a form or saving user info).
 HTTP enables the browser ↔ server interaction.
Example:
AJAX sends a GET request to /[Link], and the server responds with JSON data.
Simple example:
<!DOCTYPE html>
<html>
<body>
<h2>AJAX Example</h2>
<button onclick="loadData()">Get Data</button>
<p id="result"></p>

<script>
function loadData() {
let xhttp = new XMLHttpRequest();
[Link] = function() {
if ([Link] == 4 && [Link] == 200) {
[Link]("result").innerHTML = [Link];
}
};
[Link]("GET", "[Link]", true);
[Link]();
}
</script>
</body>
</html>

Advantages of AJAX
1. Faster Loading Time (No Full Page Reload)
 Traditional websites reload the entire page even for small updates.
 AJAX only updates the required portion, making pages load faster.
 Example: In Gmail, opening a new mail loads instantly without refreshing the entire inbox
2. Smooth and Interactive User Experience
 Users don’t face the delay of page reloads.
 Web pages behave more like desktop applications.
 AJAX makes the interface responsive and user-friendly.
 Example: Google Maps lets you drag and zoom smoothly because AJAX fetches only the required
map tiles.
3. Reduces Network Traffic
 Instead of sending the whole HTML page, AJAX sends/receives only small data (like JSON).
 Saves bandwidth and reduces server load.
 Example: Online forms that validate usernames instantly (without reloading).
4. Fetch Data from Server On-Demand
 Data can be retrieved only when needed, not all at once.
 This allows real-time updates like live scores, stock prices, weather info, etc.
 Example: Cricket score websites update automatically without pressing refresh.
Disadvantages of AJAX
1. More Complex to Implement
 AJAX programming involves JavaScript, DOM, and server-side handling.
 More difficult compared to simple HTML form submissions.
 Debugging AJAX is also harder since it works in the background.
2. Search Engine Indexing Issues
 Search engines like Google usually index the initial page content.
 AJAX-loaded content may not be visible to crawlers if not properly handled.
 This can hurt a website’s SEO (Search Engine Optimization).
3. Requires JavaScript Enabled
 AJAX depends on JavaScript.
 If the browser has JavaScript disabled (for security reasons), the AJAX functionality won’t work.
 This makes the site less accessible to all users.
4. Too Many AJAX Requests Can Overload the Server
 Since AJAX makes it easy to send frequent requests, poorly designed apps may overload servers.
 Example: Auto-refreshing stock prices or chat apps making continuous calls.
 This increases server cost and reduces performance.

You might also like