Unit 3 JavaScript
Unit 3 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;
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:
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.
Syntax:
const variableName = value;
Examples:
� 1. Constant with primitive value:
const pi = 3.14;
[Link](pi);
Output: 3.14
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. 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
</script>
</body>
</html>
Output:
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;
</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
</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;
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 OR (||)
[Link]("a || b:", a || b); // true (at least one is true)
// Use in condition
let age = 25;
let hasID = 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);
</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
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.
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.
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
};
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).
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
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
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])
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
// 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.
[Link]();
[Link](numbers); // [50, 30, 20, 10]
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.
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.”
[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");
[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.
[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
Expressions Description
\d Find a digit
\uxxxx Find the Unicode character specified by the hexadecimal number xxxxx
Quantifier Description
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 is not followed by a specific string m.
Property Description
constructor Return the function that created the RegExp object’s prototype
Method Description
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
<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.
<script>
function toggleStyle() {
[Link]("para").[Link]("highlight");
}
</script>
</body>
</html>
Each time you click, the paragraph style switches.
<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).
<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.