JS
JS
SEMESTER: 4
Unit 3
Working With JavaScript
Execution Location Runs in the user's web browser Runs on the web server
Speed Faster since it runs locally on the Slower due to communication with
user's device the server
Security Less secure, as the code is visible More secure, as code runs on the
to the user server and is hidden from the user
Dependency on Can work offline for static Requires an internet connection for
Internet content processing
Variables in JavaScript are used to store data values. They can hold different types of data such as
numbers, strings, objects, etc.
Declaring Variables
Examples
Key Differences
Hoisting Yes (initialized as undefineYes (but not initialized) Yes (but not initialized)
Data Type in JavaScript
JavaScript has two main categories of data types: Primitive and Non-Primitive (Reference).
Symbol Used to create unique and immutable values let sym = Symbol('id');
Example Code
let name = "Alice"; // String
let age = 25; // Number
let isStudent = true; // Boolean
let score; // Undefined
let emptyValue = null; // Null
let largeNumber = 12345678901234567890n; // BigInt
let uniqueId = Symbol('id'); // Symbol
let person = { name: "Alice", age: 25 }; // Object
let numbers = [1, 2, 3, 4]; // Array
function sayHello() { console.log("Hello"); } // Function
Operators in JavaScript
1. Arithmetic Operators
Used for mathematical calculations.
+ Addition 5 + 3 8
- Subtraction 5 - 3 2
* Multiplication 5 * 3 15
/ Division 10 / 2 5
% Modulus (Remainder) 10 % 3 1
** Exponentiation (Power) 2 ** 3 8
2. Assignment Operators
Used to assign values to variables.
= Assign value x = 10 x = 10
3. Comparison Operators
Used to compare values and return true or false.
!== Strict not equal (value & type) 5 !== "5" true
4. Logical Operators
Used for boolean logic.
Operator Description Example Result
` ` OR
5. Bitwise Operators
Used to perform operations on binary numbers.
` ` OR `5 3`
^ XOR 5 ^ 3 0110 6
~ NOT ~5 1010 -6
6. Ternary Operator (? :)
A shorthand for if...else.
Example:
let age = 18;
let canVote = (age >= 18) ? "Yes" : "No";
console.log(canVote); // Output: Yes
Function
A function in JavaScript is a reusable block of code that performs a specific task. Functions help in
modularizing code, making it more readable and maintainable.
1. Declaring a Function
Function Declaration
A function is declared using the function keyword and can be called before its definition due to
hoisting.
Example:
function greet() {
console.log("Hello, World!");
}
greet(); // Output: Hello, World!
Example:
Example:
const greet = () => console.log("Hello, World!");
greet(); // Output: Hello, World!
2. Function Parameters and Return Values
Functions can take parameters and return values.
Example:
function add(a, b) {
return a + b;
}
let sum = add(5, 10);
console.log(sum); // Output: 15
Example:
const add = (a, b) => a + b;
console.log(add(5, 10)); // Output: 15
3. Default Parameters
If a parameter is not provided, a default value can be used.
Example:
function greet(name = "Guest") {
console.log("Hello, " + name);
}
greet(); // Output: Hello, Guest
greet("Alice"); // Output: Hello, Alice
1. Conditional Statements
if-else Statement
A better alternative to multiple if-else statements when checking the same variable against different values.
Example:
l8.
2. Looping Statements
for Loop
while Loop
do-while Loop
3. Branching Statements
break Statement
continue Statement
return Statement
Array
An array in JavaScript is a special variable that can store multiple values in a single variable.
Creating an Array
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits); // ["Apple", "Banana", "Cherry"]
OR using the new Array() constructor:
let numbers = new Array(1, 2, 3, 4, 5);
console.log(numbers); // [1, 2, 3, 4, 5]
Accessing Elements
Example:
console.log(fruits[0]); // "Apple"
console.log(fruits[1]); // "Banana"
Modifying Elements
Example:
fruits[1] = "Mango";
console.log(fruits); // ["Apple", "Mango", "Cherry"]
Method Description
Examples:
let arr = [1, 2, 3];
arr.push(4);
console.log(arr); // [1, 2, 3, 4]
arr.pop();
console.log(arr); // [1, 2, 3]
arr.unshift(0);
console.log(arr); // [0, 1, 2, 3]
arr.shift();
console.log(arr); // [1, 2, 3]
Method Description
Examples:
let nums = [1, 2, 3, 4, 5];
// forEach()
nums.forEach(num => console.log(num * 2)); // 2, 4, 6, 8, 10
// map()
let squares = nums.map(num => num * num);
console.log(squares); // [1, 4, 9, 16, 25]
// filter()
let evenNums = nums.filter(num => num % 2 === 0);
console.log(evenNums); // [2, 4]
// reduce()
let sum = nums.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15
Method Description
Examples:
let arr2 = [10, 20, 30, 40, 50];
console.log(arr2.indexOf(30)); // 2
console.log(arr2.includes(20)); // true
console.log(arr2.find(num => num > 25)); // 30
console.log(arr2.findIndex(num => num > 25)); // 2
4. Modifying & Combining Arrays
Method Description
Examples:
let animals = ["Dog", "Cat", "Elephant", "Lion"];
// slice()
let someAnimals = animals.slice(1, 3);
console.log(someAnimals); // ["Cat", "Elephant"]
// splice()
animals.splice(2, 1, "Tiger"); // Removes 1 element at index 2, adds
"Tiger"
console.log(animals); // ["Dog", "Cat", "Tiger", "Lion"]
// concat()
let moreAnimals = animals.concat(["Monkey", "Giraffe"]);
console.log(moreAnimals); // ["Dog", "Cat", "Tiger", "Lion", "Monkey",
"Giraffe"]
// join()
console.log(animals.join(" - ")); // "Dog - Cat - Tiger - Lion"
5. Sorting & Reversing Arrays
Method Description
Examples:
let numbersArr = [5, 2, 8, 1, 4];
numbersArr.sort();
console.log(numbersArr); // [1, 2, 4, 5, 8]
numbersArr.reverse();
console.log(numbersArr); // [8, 5, 4, 2, 1]
Common Methods
console.log(Math.PI); // 3.141592653589793
console.log(Math.sqrt(25)); // 5
console.log(Math.pow(2, 3)); // 8 (2^3)
console.log(Math.round(4.6)); // 5
console.log(Math.floor(4.9)); // 4
console.log(Math.ceil(4.1)); // 5
console.log(Math.random()); // Random number between 0 and 1
console.log(Math.max(10, 5, 20)); // 20
console.log(Math.min(10, 5, 20)); // 5
2. Date Object
Creating a Date
let now = new Date();
console.log(now); // Current date & time
Modifying Date
now.setFullYear(2025);
console.log(now.getFullYear()); // 2025
User Define Objects
In JavaScript, you can create user-defined objects to model real-world entities by defining
custom properties and methods.
let person = {
name: "Alice",
age: 25,
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
console.log(person.name); // Alice
person.greet(); // Hello, my name is Alice
Document
├── <html>
│ ├── <head>
│ │ ├── <title>
│ │ ├── <meta>
│ ├── <body>
│ ├── <h1>
│ ├── <p>
│ ├── <div>
│ ├── <button>
Remove an Element
let element = document.getElementById("main-heading");
element.remove();
Events in JavaScript
● In JavaScript, events are actions that occur when users interact with a webpage.
● These interactions can be clicking a button, typing in an input field, moving the mouse, or loading the page.
JavaScript allows us to handle these events using event listeners.
You can assign an event handler to an element using its event property (e.g., onclick).
btn.addEventListener("click", showMessage);
btn.addEventListener("click", function(event) {
console.log("Event Type:", event.type); // "click"
console.log("Clicked Element:", event.target); // <button>
});
document.getElementById("myLink").addEventListener("click",
function(event) {
event.preventDefault(); // Prevents link navigation
alert("Link clicked, but navigation is stopped!");
});
Validation in JavaScript
Validation in JavaScript ensures that user input meets specific criteria before submitting a form. It
helps prevent incorrect or malicious data entry.
1. Types of Validation
✅ Client-Side Validation (JavaScript)
● Fast (happens in the browser)
● Provides instant feedback
● Prevents unnecessary server requests
function validateEmail() {
let email = document.getElementById("email").value;
let regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
if (!regex.test(email)) {
alert("Invalid email format!");
return false;
}
return true;
}
✅ Uses Regular Expressions (RegEx) to check email format.
(c) Validating Password Strength
function validatePassword() {
let password = document.getElementById("password").value;
let regex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
if (!regex.test(password)) {
alert("Password must be at least 8 characters long and include
letters & numbers.");
return false;
}
return true;
}
✅ Ensures password contains at least one letter, one number, and 8+ characters.
(d) Validating Phone Numbers
function validatePhone() {
let phone = document.getElementById("phone").value;
let regex = /^\d{10}$/; // 10-digit number
if (!regex.test(phone)) {
alert("Invalid phone number! Must be 10 digits.");
return false;
}
return true;
}
✅ Allows only 10-digit numbers.
3. Complete Form Validation Example
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<script>
function validateForm() {
return validateName() && validateEmail() && validatePassword()
&& validatePhone();
}
function validateName() {
let name = document.getElementById("name").value;
if (name.trim() === "") {
alert("Name is required.");
return false;
}
return true;
}
function validateEmail() {
let email = document.getElementById("email").value;
let regex =
/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
if (!regex.test(email)) {
alert("Invalid email address.");
return false;
}
return true;
}
function validatePassword() {
let password = document.getElementById("password").value;
let regex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
if (!regex.test(password)) {
alert("Password must be at least 8 characters long with
letters & numbers.");
return false;
}
return true;
}
function validatePhone() {
let phone = document.getElementById("phone").value;
let regex = /^\d{10}$/;
if (!regex.test(phone)) {
alert("Invalid phone number! Must be 10 digits.");
return false;
}
return true;
}
</script>
</head>
<body>
<form onsubmit="return validateForm()">
<label>Name:</label>
<input type="text" id="name"><br><br>
<label>Email:</label>
<input type="text" id="email"><br><br>
<label>Password:</label>
<input type="password" id="password"><br><br>
<label>Phone:</label>
<input type="text" id="phone"><br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
✅ Prevents form submission if validation fails.
<form>
<input type="text" id="name" required> <!-- Ensures field is not empty
-->
<input type="email" id="email" required> <!-- Ensures correct email
format -->
<input type="password" id="password" minlength="8" required> <!--
Minimum 8 chars -->
<input type="tel" id="phone" pattern="\d{10}" required> <!-- 10-digit
phone -->
<button type="submit">Submit</button>
</form>
✅ Simple & effective, but lacks customization.
JS Cookies
JavaScript cookies are small pieces of data stored in the browser, typically used for session
management, user preferences, or tracking. You can create, read, update, and delete cookies using
JavaScript.
Creating a Cookie
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2025 23:59:59
GMT; path=/";
"username=JohnDoe; theme=dark"
function getCookie(name) {
let cookies = document.cookie.split("; ");
for (let cookie of cookies) {
let [key, value] = cookie.split("=");
if (key === name) return value;
}
return null;
}
console.log(getCookie("username")); // "JohnDoe"
Updating a Cookie
Deleting a Cookie
Important Properties:
Example:
<input type="text" id="nameInput" placeholder="Enter your name">
<button onclick="getInputValue()">Get Value</button>
<script>
function getInputValue() {
let input = document.getElementById("nameInput");
alert("Value: " + input.value);
}
</script>
Important Properties:
Example:
<input type="checkbox" id="agreeCheckbox"> Agree to terms
<button onclick="checkAgreement()">Check Status</button>
<script>
function checkAgreement() {
let checkbox = document.getElementById("agreeCheckbox");
alert(checkbox.checked ? "Checked" : "Not Checked");
}
</script>
Important Properties:
Example:
<input type="radio" name="gender" value="Male" id="male"> Male
<input type="radio" name="gender" value="Female" id="female"> Female
<button onclick="getSelectedGender()">Get Selected</button>
<script>
function getSelectedGender() {
let gender = document.querySelector('input[name="gender"]:checked');
alert(gender ? gender.value : "No selection");
}
</script>
4. Dropdown (<select>)
Important Properties:
<script>
function getSelectedFruit() {
let select = document.getElementById("fruitSelect");
alert("Selected: " + select.value);
}
</script>
5. Textarea (<textarea>)
Important Properties:
Example:
<textarea id="comments">This is a comment</textarea>
<button onclick="showComment()">Show Comment</button>
<script>
function showComment() {
let textarea = document.getElementById("comments");
alert(textarea.value);
}
</script>
6. Button (<button>)
Important Properties:
Example:
<button id="submitBtn" onclick="disableButton()">Click Me</button>
<script>
function disableButton() {
document.getElementById("submitBtn").disabled = true;
}
</script>
Important Properties:
Example:
<input type="file" id="fileInput">
<button onclick="showFileName()">Get File</button>
<script>
function showFileName() {
let fileInput = document.getElementById("fileInput");
alert(fileInput.files.length > 0 ? fileInput.files[0].name : "No file
selected");
}
</script>