Introduction to JavaScript
JavaScript is a programming language used to make web pages interactive. It can change HTML content, modify styles, handle user input, and perform calculations.
What Can JavaScript Do?
- Change HTML content
- Change CSS styles
- Respond to user actions (click, input, etc.)
- Validate forms
- Create dynamic web applications
Example: Changing Text Using JavaScript
document.getElementById("demo").innerHTML = "Hello JavaScript!";
Complete Code for Practice
<!DOCTYPE html>
<html>
<head>
<title>Introduction to JavaScript</title>
</head>
<body>
<h1 id="demo">Welcome</h1>
<button onclick="changeText()">Click Me</button>
<script>
function changeText() {
document.getElementById("demo").innerHTML = "Hello JavaScript!";
}
</script>
</body>
</html>
π― Practice Task
- Change the button text.
- Change the color of the heading.
- Display todayβs date using JavaScript.
Basic Syntax
JavaScript syntax is the set of rules that define how JavaScript programs are written.
Statements
JavaScript programs are made up of statements. Each statement performs an action.
let message = "Hello";
console.log(message);
Case Sensitivity
JavaScript is case-sensitive.
let name = "Raman";
let Name = "Different"; // This is a different variable
Comments
Comments are used to explain code.
// This is a single-line comment
/*
This is a
multi-line comment
*/
Code Blocks
Code blocks are written inside curly braces { }.
if (true) {
console.log("This is a block of code");
}
Complete Code for Practice
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Basic Syntax</title>
</head>
<body>
<script>
// Variable declaration
let studentName = "Raman";
// Output to console
console.log("Student Name: " + studentName);
// Conditional statement
if (studentName === "Raman") {
console.log("Welcome Raman!");
}
</script>
</body>
</html>
π― Practice Task
- Create a variable called
ageand assign your age. - Print it using console.log().
- Create an if statement to check if age is greater than 18.
Introduction to Script Tag
The <script> tag is used to write or link JavaScript inside an HTML document.
Without the script tag, JavaScript will not run in the browser.
Basic Syntax
<script>
// JavaScript code here
</script>
Three Ways to Include JavaScript
1οΈβ£ Internal JavaScript (Inside HTML)
<script>
function greet() {
alert("Hello Student!");
}
</script>
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<button onclick="greet()">Click Me</button>
<script>
function greet() {
alert("Hello Student!");
}
</script>
</body>
</html>
2οΈβ£ External JavaScript (Recommended Method)
Create a separate file named script.js
// script.js
function greet() {
alert("Hello from External File!");
}
Now link it inside HTML:
<script src="script.js"></script>
3οΈβ£ Script at Bottom of Body (Best Practice)
Placing the script before </body> ensures HTML loads first.
<body>
<h1>Welcome</h1>
<script>
console.log("Page Loaded");
</script>
</body>
π― Practice Task
- Create a button that shows your name in an alert.
- Create an external file and link it.
- Move your script to the bottom of the body.
JavaScript Rules
1οΈβ£ Case Sensitivity
JavaScript is case-sensitive.
let myVar = 10;
let myvar = 20; // Different variable
2οΈβ£ Semicolons
Semicolons are optional but recommended.
let x = 5;
let y = 10;
3οΈβ£ Variable Naming Rules
- Must start with a letter, _ or $
- Cannot start with a number
- No spaces allowed
- Cannot use reserved words (if, for, while, etc.)
let studentName = "Raman"; // Correct
let 1name = "Wrong"; // β Error
4οΈβ£ Comments
// Single line comment
/*
Multi-line
comment
*/
5οΈβ£ Code Blocks
if (true) {
console.log("This is a block");
}
Common Errors
Reference Error
console.log(age); // age not defined
Syntax Error
let x = ; // Missing value
Type Error
let num = 10;
num(); // number is not a function
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
// Correct variable
let name = "Raman";
// Case-sensitive check
if (name === "Raman") {
console.log("Correct Name");
}
</script>
</body>
</html>
π― Practice Task
- Create 3 valid and 3 invalid variable names.
- Write one example of each error type.
- Write a small program with comments.
JavaScript Input & Output
JavaScript allows interaction with users using different input and output methods.
1οΈβ£ console.log() β Output to Console
console.log("Hello World");
2οΈβ£ alert() β Popup Message
alert("Welcome to JavaScript");
3οΈβ£ prompt() β Take User Input
let name = prompt("Enter your name:");
alert("Hello " + name);
4οΈβ£ document.write() β Write to Page
document.write("This text is written using JavaScript");
5οΈβ£ DOM Manipulation
document.getElementById("demo").innerHTML = "Changed Text";
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<h2 id="demo">Original Text</h2>
<script>
let userName = prompt("Enter your name:");
alert("Welcome " + userName);
document.getElementById("demo").innerHTML = "Hello " + userName;
console.log("User Name:", userName);
</script>
</body>
</html>
π― Practice Task
- Take two numbers using prompt() and display their sum.
- Change heading color using DOM.
- Show current date using JavaScript.
JavaScript Data Types
JavaScript has two main types of data:
πΉ Primitive Data Types
- Number β 10, 3.14
- String β "Hello"
- Boolean β true / false
- Undefined
- Null
- BigInt
- Symbol
let age = 25; // Number
let name = "Raman"; // String
let isStudent = true; // Boolean
let x; // Undefined
let y = null; // Null
πΉ Non-Primitive Data Type
- Object
- Array
let student = {
name: "Raman",
age: 20
};
let marks = [90, 85, 88];
Checking Data Type
console.log(typeof age);
π― Practice Task
- Create one variable of each primitive type.
- Create an object representing a student.
- Use typeof to check all variable types.
Variables in JavaScript
Variables are used to store data values.
Declaration Keywords
- var β Old method (function scoped)
- let β Block scoped
- const β Block scoped (cannot be reassigned)
var city = "Delhi";
let age = 25;
const country = "India";
Difference Between let and const
let score = 10;
score = 20; // Allowed
const pi = 3.14;
pi = 3.141; // β Error
Variable Scope Example
function test() {
let localVar = "Inside Function";
console.log(localVar);
}
π― Practice Task
- Create 5 variables using let.
- Create 2 constants.
- Try reassigning a const variable and observe error.
JavaScript Operators
1οΈβ£ Arithmetic Operators
let a = 10;
let b = 5;
console.log(a + b); // Addition
console.log(a - b); // Subtraction
console.log(a * b); // Multiplication
console.log(a / b); // Division
console.log(a % b); // Modulus
console.log(a ** b); // Power
2οΈβ£ Comparison Operators
let x = 10;
let y = "10";
console.log(x == y); // true
console.log(x === y); // false
console.log(x > 5); // true
3οΈβ£ Logical Operators
let isLoggedIn = true;
let isAdmin = false;
console.log(isLoggedIn && isAdmin);
console.log(isLoggedIn || isAdmin);
console.log(!isLoggedIn);
4οΈβ£ Assignment Operators
let num = 10;
num += 5;
num -= 2;
num *= 3;
num /= 2;
π― Practice Task
- Take two numbers and perform all arithmetic operations.
- Compare two values using == and ===.
- Create logical condition using && and ||.
If / Else Statement
Conditional statements allow JavaScript to make decisions. Code runs only if a specific condition is true.
1οΈβ£ Simple If Statement
let age = 18;
if (age >= 18) {
console.log("You are eligible to vote.");
}
2οΈβ£ If β Else Statement
let age = 15;
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}
3οΈβ£ If β Else If β Else
let marks = 85;
if (marks >= 90) {
console.log("Grade A");
} else if (marks >= 70) {
console.log("Grade B");
} else {
console.log("Grade C");
}
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
let number = prompt("Enter a number:");
if (number > 0) {
alert("Positive Number");
} else if (number < 0) {
alert("Negative Number");
} else {
alert("Zero");
}
</script>
</body>
</html>
π― Practice Task
- Check whether a number is even or odd.
- Find largest of two numbers.
- Create grading system (A, B, C, Fail).
Switch Case
The switch statement is used when you need to check multiple possible values of one variable.
Basic Syntax
switch(expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code
}
Example
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of week");
break;
case "Friday":
console.log("Weekend coming!");
break;
default:
console.log("Normal Day");
}
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
let color = prompt("Enter traffic light color:");
switch (color) {
case "red":
alert("Stop");
break;
case "yellow":
alert("Get Ready");
break;
case "green":
alert("Go");
break;
default:
alert("Invalid Color");
}
</script>
</body>
</html>
π― Practice Task
- Create simple calculator using switch.
- Create weekday message program.
For Loop
A for loop is used when you know how many times you want to repeat code.
Basic Syntax
for (initialization; condition; increment) {
// code block
}
Example
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
for (let i = 1; i <= 10; i++) {
console.log("Table of 5: " + (5 * i));
}
</script>
</body>
</html>
π― Practice Task
- Print numbers from 1 to 100.
- Print even numbers between 1β50.
- Print multiplication table of any number.
While Loop
A while loop runs as long as a condition is true. It is used when the number of iterations is unknown.
Basic Syntax
while (condition) {
// code
}
Example
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
let number = 10;
while (number > 0) {
console.log(number);
number--;
}
</script>
</body>
</html>
π― Practice Task
- Create countdown timer from 20 to 1.
- Keep asking user for password until correct.
- Print numbers divisible by 3 between 1β30.
Functions
A function is a reusable block of code designed to perform a specific task. It helps in organizing code and avoiding repetition.
Basic Syntax
function functionName() {
// code
}
Example
function greet() {
console.log("Hello World");
}
greet();
Function with Parameters
function add(a, b) {
return a + b;
}
console.log(add(5, 3));
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
function countdown(start) {
while (start > 0) {
console.log(start);
start--;
}
}
countdown(5);
</script>
</body>
</html>
π― Practice Task
- Create a function to print numbers from 1 to 10.
- Create a function to check if a number is even or odd.
- Create a function that takes name as input and prints greeting.
Parameters & Return
Parameters are values passed into a function, and a return statement sends a result back. This makes functions more dynamic and reusable.
Basic Syntax
function functionName(parameter1, parameter2) {
return value;
}
Example
function multiply(a, b) {
return a * b;
}
let result = multiply(4, 5);
console.log(result);
Without Return (Only Parameters)
function greet(name) {
console.log("Hello " + name);
}
greet("Raman");
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
function checkEvenOdd(num) {
if (num % 2 === 0) {
return "Even";
} else {
return "Odd";
}
}
let number = 7;
console.log(checkEvenOdd(number));
</script>
</body>
</html>
π― Practice Task
- Create a function that adds two numbers and returns result.
- Create a function to find square of a number.
- Create a function that returns the largest of two numbers.
Scope
Scope determines where variables can be accessed in your code. JavaScript mainly has three types of scope: Global, Function, and Block scope.
Global Scope
let name = "Raman";
function showName() {
console.log(name);
}
showName(); // Accessible everywhere
Function Scope
function test() {
let message = "Hello";
console.log(message);
}
test();
// console.log(message); // Error (not accessible outside)
Block Scope (let & const)
if (true) {
let x = 10;
const y = 20;
console.log(x, y);
}
// console.log(x, y); // Error (block scope)
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
let globalVar = "I am global";
function demoScope() {
let functionVar = "I am inside function";
if (true) {
let blockVar = "I am inside block";
console.log(globalVar);
console.log(functionVar);
console.log(blockVar);
}
// console.log(blockVar); // Error
}
demoScope();
</script>
</body>
</html>
π― Practice Task
- Create a global variable and use it inside a function.
- Create a function variable and try accessing it outside.
- Create a block variable using let and test its scope.
this Keyword
The this keyword refers to the object that is currently executing the function. Its value depends on how and where the function is called.
Global Context
console.log(this); // Refers to global object (window in browser)
Inside an Object Method
let person = {
name: "Raman",
greet: function() {
console.log(this.name);
}
};
person.greet(); // "Raman"
Inside a Function
function show() {
console.log(this);
}
show(); // Global object (or undefined in strict mode)
Arrow Function Behavior
let user = {
name: "Raman",
greet: () => {
console.log(this.name);
}
};
user.greet(); // undefined (arrow functions donβt have their own this)
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
let student = {
name: "Raman",
age: 20,
showDetails: function() {
console.log(this.name, this.age);
}
};
student.showDetails();
</script>
</body>
</html>
π― Practice Task
- Create an object and print its properties using this.
- Test this inside a normal function.
- Test this inside an arrow function and observe difference.
Arrays
An array is a collection of multiple values stored in a single variable. It allows you to store and manage lists of data easily.
Basic Syntax
let arrayName = [value1, value2, value3];
Example
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[0]); // Apple
console.log(fruits[1]); // Banana
Common Array Methods
let numbers = [1, 2, 3];
numbers.push(4); // Add at end
numbers.pop(); // Remove from end
numbers.unshift(0); // Add at beginning
numbers.shift(); // Remove from beginning
console.log(numbers);
Looping Through Array
let items = ["A", "B", "C"];
for (let i = 0; i < items.length; i++) {
console.log(items[i]);
}
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
let students = ["Raman", "Simran", "Aman"];
// Add new student
students.push("Karan");
// Print all students
for (let i = 0; i < students.length; i++) {
console.log(students[i]);
}
</script>
</body>
</html>
π― Practice Task
- Create an array of 5 numbers and print them.
- Add and remove elements using push() and pop().
- Find the length of an array.
Array Methods
Array methods are built-in functions that help you perform operations on arrays like adding, removing, searching, and transforming data.
Adding & Removing Elements
let arr = [1, 2, 3];
arr.push(4); // Add at end β [1,2,3,4]
arr.pop(); // Remove last β [1,2,3]
arr.unshift(0); // Add at start β [0,1,2,3]
arr.shift(); // Remove first β [1,2,3]
Searching Methods
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits.includes("Banana")); // true
console.log(fruits.indexOf("Mango")); // 2
Transforming Arrays
let numbers = [1, 2, 3, 4];
let doubled = numbers.map(num => num * 2);
console.log(doubled); // [2,4,6,8]
Filtering Data
let nums = [10, 15, 20, 25];
let filtered = nums.filter(n => n > 15);
console.log(filtered); // [20,25]
Loop Alternative (forEach)
let items = ["A", "B", "C"];
items.forEach(item => {
console.log(item);
});
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
let marks = [40, 55, 70, 85];
// Add new marks
marks.push(90);
// Filter passed students
let passed = marks.filter(m => m >= 50);
// Double marks
let updated = marks.map(m => m * 2);
console.log("Original:", marks);
console.log("Passed:", passed);
console.log("Updated:", updated);
</script>
</body>
</html>
π― Practice Task
- Create an array and use push() & pop().
- Use map() to square numbers.
- Use filter() to get numbers greater than 10.
Objects
An object is a collection of key-value pairs used to store related data. It allows you to represent real-world entities in your code.
Basic Syntax
let objectName = {
key1: value1,
key2: value2
};
Example
let student = {
name: "Raman",
age: 20,
course: "Computer Science"
};
console.log(student.name);
console.log(student.age);
Adding & Updating Properties
let user = {
name: "Aman"
};
user.age = 25; // Add property
user.name = "Raman"; // Update property
console.log(user);
Object Methods
let person = {
name: "Raman",
greet: function() {
console.log("Hello " + this.name);
}
};
person.greet();
Looping Through Object
let car = {
brand: "BMW",
model: "X5",
year: 2023
};
for (let key in car) {
console.log(key + ": " + car[key]);
}
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
let product = {
name: "Laptop",
price: 50000,
brand: "HP"
};
// Add new property
product.stock = 10;
// Update price
product.price = 45000;
// Display details
for (let key in product) {
console.log(key + ": " + product[key]);
}
</script>
</body>
</html>
π― Practice Task
- Create an object for a student with name, class, and marks.
- Add a new property to the object.
- Create a method inside object and call it.
Object Methods
Object methods are functions stored as properties inside an object. They allow objects to perform actions using their own data.
Basic Syntax
let obj = {
methodName: function() {
// code
}
};
Example
let person = {
name: "Raman",
greet: function() {
console.log("Hello " + this.name);
}
};
person.greet();
Using this Keyword
let car = {
brand: "BMW",
showBrand: function() {
console.log(this.brand);
}
};
car.showBrand();
Shorthand Method Syntax (ES6)
let user = {
name: "Aman",
greet() {
console.log("Hi " + this.name);
}
};
user.greet();
Object with Multiple Methods
let calculator = {
add(a, b) {
return a + b;
},
subtract(a, b) {
return a - b;
}
};
console.log(calculator.add(5, 3));
console.log(calculator.subtract(5, 3));
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
let student = {
name: "Raman",
marks: 80,
showDetails() {
console.log(this.name + " scored " + this.marks);
},
updateMarks(newMarks) {
this.marks = newMarks;
}
};
student.showDetails();
student.updateMarks(90);
student.showDetails();
</script>
</body>
</html>
π― Practice Task
- Create an object with a method to print your name.
- Create a calculator object with add and multiply methods.
- Create an object that updates and displays data using methods.
String Methods
String methods are built-in functions used to manipulate and work with text. They help in searching, modifying, and formatting strings.
Basic Example
let text = "Hello World";
console.log(text.length); // 11
console.log(text.toUpperCase()); // HELLO WORLD
Common String Methods
let str = "JavaScript";
// Convert case
str.toLowerCase();
str.toUpperCase();
// Find text
str.includes("Script");
str.indexOf("Script");
// Extract part
str.slice(0, 4); // Java
// Replace text
str.replace("Java", "Type");
Trimming Spaces
let name = " Raman ";
console.log(name.trim()); // "Raman"
Splitting String
let data = "apple,banana,mango";
let fruits = data.split(",");
console.log(fruits);
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
let message = " welcome to javascript ";
// Clean text
message = message.trim();
// Convert to uppercase
let upper = message.toUpperCase();
// Replace word
let newMessage = message.replace("javascript", "coding");
// Split into words
let words = message.split(" ");
console.log("Original:", message);
console.log("Uppercase:", upper);
console.log("Replaced:", newMessage);
console.log("Words:", words);
</script>
</body>
</html>
π― Practice Task
- Create a string and convert it to uppercase.
- Check if a word exists using includes().
- Split a sentence into words.
Math Object
The Math object in JavaScript provides built-in methods and properties for performing mathematical operations like rounding, finding powers, square roots, and generating random numbers.
Basic Examples
console.log(Math.PI); // 3.141592653589793
console.log(Math.sqrt(16)); // 4
Common Math Methods
// Rounding numbers
Math.round(4.6); // 5
Math.floor(4.9); // 4
Math.ceil(4.1); // 5
// Power & square root
Math.pow(2, 3); // 8
Math.sqrt(25); // 5
// Absolute value
Math.abs(-10); // 10
// Min & Max
Math.min(1, 5, 3); // 1
Math.max(1, 5, 3); // 5
Random Numbers
// Random number between 0 and 1
Math.random();
// Random number between 1 and 10
let randomNum = Math.floor(Math.random() * 10) + 1;
console.log(randomNum);
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
// Generate random number 1β100
let num = Math.floor(Math.random() * 100) + 1;
// Square and square root
let square = Math.pow(num, 2);
let root = Math.sqrt(num);
console.log("Number:", num);
console.log("Square:", square);
console.log("Square Root:", root);
</script>
</body>
</html>
π― Practice Task
- Generate a random number between 1β50.
- Find square root of a number.
- Find maximum number from a list.
Date Object
The Date object in JavaScript is used to work with dates and times. It allows you to get current date, time, and perform date calculations.
Creating Date
// Current date and time
let now = new Date();
// Specific date
let customDate = new Date("2025-01-01");
console.log(now);
console.log(customDate);
Getting Date Values
let today = new Date();
console.log(today.getFullYear()); // Year
console.log(today.getMonth()); // Month (0-11)
console.log(today.getDate()); // Day
console.log(today.getHours());
console.log(today.getMinutes());
console.log(today.getSeconds());
Setting Date Values
let d = new Date();
d.setFullYear(2030);
d.setMonth(11); // December
d.setDate(25);
console.log(d);
Formatting Date
let date = new Date();
console.log(date.toDateString());
console.log(date.toLocaleDateString());
console.log(date.toLocaleTimeString());
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
let now = new Date();
// Display current date
console.log("Today:", now.toDateString());
// Display time
console.log("Time:", now.toLocaleTimeString());
// Add 5 days
now.setDate(now.getDate() + 5);
console.log("After 5 days:", now.toDateString());
</script>
</body>
</html>
π― Practice Task
- Display current date and time.
- Show only year, month, and day separately.
- Add 10 days to current date.
Error Handling (try...catch)
Error handling allows you to manage runtime errors in your code. The try...catch statement lets you handle errors gracefully without stopping the entire program.
Basic Syntax
try {
// code that may cause error
} catch (error) {
// handle error
}
Example
try {
let x = y; // y is not defined
} catch (error) {
console.log("Error occurred:", error.message);
}
Using finally
try {
console.log("Try block");
} catch (error) {
console.log("Catch block");
} finally {
console.log("Always runs");
}
Throwing Custom Errors
function checkAge(age) {
if (age < 18) {
throw "You must be 18+";
}
return "Access granted";
}
try {
console.log(checkAge(16));
} catch (err) {
console.log(err);
}
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
function divide(a, b) {
try {
if (b === 0) {
throw "Cannot divide by zero";
}
return a / b;
} catch (err) {
console.log("Error:", err);
} finally {
console.log("Execution completed");
}
}
console.log(divide(10, 2));
console.log(divide(10, 0));
</script>
</body>
</html>
π― Practice Task
- Handle an undefined variable error using try...catch.
- Create a function that throws error if input is negative.
- Use finally block to display a message.
DOM Introduction
DOM (Document Object Model) represents the structure of an HTML document. It allows JavaScript to access, modify, and control HTML elements dynamically.
What is DOM?
// HTML is converted into a tree structure
document β html β body β elements
// JavaScript can access elements using DOM
document.getElementById("idName");
Selecting Elements
// By ID
document.getElementById("demo");
// By Class
document.getElementsByClassName("box");
// By Tag
document.getElementsByTagName("p");
// Modern Method
document.querySelector(".box");
document.querySelectorAll("p");
Changing Content
let el = document.getElementById("demo");
el.innerHTML = "Hello World";
Changing Style
let el = document.getElementById("demo");
el.style.color = "red";
el.style.fontSize = "20px";
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<h2 id="title">Original Text</h2>
<button onclick="changeText()">Click Me</button>
<script>
function changeText() {
let element = document.getElementById("title");
element.innerHTML = "Text Changed!";
element.style.color = "blue";
}
</script>
</body>
</html>
π― Practice Task
- Select an element using getElementById and change text.
- Change color of a paragraph using JavaScript.
- Use querySelector to select a class and modify it.
DOM Selectors
DOM selectors are used to select and access HTML elements using JavaScript. They allow you to target specific elements to modify content, style, or behavior.
Basic Selectors
// Select by ID
document.getElementById("idName");
// Select by Class
document.getElementsByClassName("className");
// Select by Tag
document.getElementsByTagName("p");
Modern Selectors
// Select first matching element
document.querySelector(".box");
// Select all matching elements
document.querySelectorAll(".box");
Example
let title = document.getElementById("heading");
let items = document.querySelectorAll(".item");
title.innerHTML = "Updated Heading";
items.forEach(el => {
el.style.color = "green";
});
Difference (Single vs Multiple)
// Single element
document.querySelector("#id");
// Multiple elements (NodeList)
document.querySelectorAll(".class");
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<h2 id="heading">Hello</h2>
<p class="text">Paragraph 1</p>
<p class="text">Paragraph 2</p>
<button onclick="changeStyle()">Change Style</button>
<script>
function changeStyle() {
let heading = document.getElementById("heading");
let paras = document.querySelectorAll(".text");
heading.style.color = "blue";
paras.forEach(p => {
p.style.fontSize = "18px";
});
}
</script>
</body>
</html>
π― Practice Task
- Select an element by ID and change its text.
- Select multiple elements using querySelectorAll.
- Change style of all selected elements.
DOM Manipulation
DOM Manipulation allows you to dynamically change HTML elements using JavaScript. You can update content, styles, attributes, and even create or remove elements.
Changing Content
let el = document.getElementById("demo");
el.innerHTML = "New Content";
el.textContent = "Only Text";
Changing Styles
let el = document.getElementById("demo");
el.style.color = "red";
el.style.backgroundColor = "yellow";
Changing Attributes
let img = document.getElementById("myImage");
img.src = "new-image.jpg";
img.alt = "Updated Image";
Creating & Adding Elements
let newEl = document.createElement("p");
newEl.textContent = "I am new element";
document.body.appendChild(newEl);
Removing Elements
let el = document.getElementById("demo");
el.remove();
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<h2 id="title">Hello World</h2>
<button onclick="updateContent()">Update</button>
<button onclick="addElement()">Add</button>
<script>
function updateContent() {
let el = document.getElementById("title");
el.innerHTML = "Content Updated!";
el.style.color = "green";
}
function addElement() {
let newPara = document.createElement("p");
newPara.textContent = "New Paragraph Added!";
document.body.appendChild(newPara);
}
</script>
</body>
</html>
π― Practice Task
- Change text and color of an element.
- Create a new element and add it to the page.
- Remove an existing element using JavaScript.
Events
Events are actions that occur in the browser, such as clicks, typing, or page loading. JavaScript can respond to these events to make web pages interactive.
Common Events
// Mouse Events
onclick
onmouseover
onmouseout
// Keyboard Events
onkeydown
onkeyup
// Form Events
onsubmit
onchange
Inline Event Example
<button onclick="showMessage()">Click Me</button>
<script>
function showMessage() {
alert("Button Clicked!");
}
</script>
addEventListener Method
let btn = document.getElementById("btn");
btn.addEventListener("click", function() {
console.log("Button clicked");
});
Event Object
document.addEventListener("click", function(event) {
console.log(event.target);
});
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<button id="btn">Click Me</button>
<p id="text">Hello</p>
<script>
let button = document.getElementById("btn");
let text = document.getElementById("text");
button.addEventListener("click", function() {
text.innerHTML = "Button Clicked!";
text.style.color = "blue";
});
</script>
</body>
</html>
π― Practice Task
- Create a button and handle click event.
- Change text on mouseover event.
- Capture keyboard input using keydown event.
Event Listeners
Event listeners allow you to attach JavaScript functions to HTML elements. They listen for specific events (like clicks or key presses) and execute code when those events occur.
Basic Syntax
element.addEventListener("event", function() {
// code to run
});
Example
let btn = document.getElementById("btn");
btn.addEventListener("click", function() {
console.log("Button clicked");
});
Multiple Events on Same Element
let box = document.getElementById("box");
box.addEventListener("mouseover", function() {
console.log("Mouse over");
});
box.addEventListener("mouseout", function() {
console.log("Mouse out");
});
Using Named Function
function handleClick() {
console.log("Clicked!");
}
btn.addEventListener("click", handleClick);
Removing Event Listener
function showMessage() {
console.log("Hello");
}
btn.addEventListener("click", showMessage);
// Remove event
btn.removeEventListener("click", showMessage);
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<button id="btn">Click Me</button>
<div id="box" style="width:100px;height:100px;background:gray;"></div>
<script>
let btn = document.getElementById("btn");
let box = document.getElementById("box");
function changeColor() {
box.style.background = "green";
}
btn.addEventListener("click", changeColor);
box.addEventListener("mouseover", function() {
box.style.background = "blue";
});
box.addEventListener("mouseout", function() {
box.style.background = "gray";
});
</script>
</body>
</html>
π― Practice Task
- Add a click event listener to a button.
- Change element color on mouseover and mouseout.
- Remove an event listener after one click.
Event Bubbling & Capturing
Event propagation in JavaScript defines how events travel through the DOM. There are two main phases: Bubbling (child β parent) and Capturing (parent β child).
Event Bubbling (Default)
// Event moves from child to parent
document.getElementById("child").addEventListener("click", function() {
console.log("Child clicked");
});
document.getElementById("parent").addEventListener("click", function() {
console.log("Parent clicked");
});
Event Capturing
// Use true as third parameter
document.getElementById("parent").addEventListener("click", function() {
console.log("Parent (capturing)");
}, true);
document.getElementById("child").addEventListener("click", function() {
console.log("Child (capturing)");
}, true);
Stopping Propagation
document.getElementById("child").addEventListener("click", function(event) {
event.stopPropagation();
console.log("Only child event runs");
});
Example
let parent = document.getElementById("parent");
let child = document.getElementById("child");
parent.addEventListener("click", () => {
console.log("Parent clicked");
});
child.addEventListener("click", () => {
console.log("Child clicked");
});
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<div id="parent" style="padding:30px;background:lightblue;">
Parent
<div id="child" style="padding:30px;background:lightgreen;">
Child
</div>
</div>
<script>
let parent = document.getElementById("parent");
let child = document.getElementById("child");
// Bubbling
parent.addEventListener("click", () => {
console.log("Parent clicked (Bubbling)");
});
child.addEventListener("click", (e) => {
console.log("Child clicked (Bubbling)");
// e.stopPropagation(); // Uncomment to stop
});
// Capturing
parent.addEventListener("click", () => {
console.log("Parent clicked (Capturing)");
}, true);
child.addEventListener("click", () => {
console.log("Child clicked (Capturing)");
}, true);
</script>
</body>
</html>
π― Practice Task
- Create parent-child elements and observe bubbling.
- Enable capturing and compare output order.
- Use stopPropagation() to stop event flow.
Form Validation
Form validation ensures that user input is correct and complete before submitting a form. It helps improve data accuracy and user experience.
Basic Validation Example
function validateForm() {
let name = document.getElementById("name").value;
if (name === "") {
alert("Name is required");
return false;
}
}
HTML Required Attribute
<input type="text" required>
Validating Email
function validateEmail(email) {
let pattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
return pattern.test(email);
}
Displaying Error Messages
let error = document.getElementById("error");
if (name === "") {
error.textContent = "Name cannot be empty";
}
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<form onsubmit="return validateForm()">
Name: <input type="text" id="name"><br><br>
Email: <input type="text" id="email"><br><br>
<p id="error" style="color:red;"></p>
<button type="submit">Submit</button>
</form>
<script>
function validateForm() {
let name = document.getElementById("name").value;
let email = document.getElementById("email").value;
let error = document.getElementById("error");
error.textContent = "";
if (name === "") {
error.textContent = "Name is required";
return false;
}
let pattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
if (!pattern.test(email)) {
error.textContent = "Invalid email format";
return false;
}
return true;
}
</script>
</body>
</html>
π― Practice Task
- Validate a required input field.
- Check valid email format.
- Display custom error messages on screen.
Let and Const
let and const are modern ways to declare variables in JavaScript. They provide better scope control and help avoid common errors compared to var.
let Keyword
let name = "Raman";
name = "Aman"; // Allowed (can be updated)
console.log(name);
const Keyword
const pi = 3.14;
// pi = 3.141; β Error (cannot reassign)
console.log(pi);
Block Scope
if (true) {
let a = 10;
const b = 20;
console.log(a, b);
}
// console.log(a, b); β Error (block scope)
Difference Between let and const
// let β can be updated
let x = 5;
x = 10;
// const β cannot be reassigned
const y = 5;
// y = 10; β Error
Using const with Objects & Arrays
const user = {
name: "Raman"
};
// Allowed: modifying properties
user.name = "Aman";
// Not allowed: reassigning object
// user = {}; β Error
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
let count = 1;
count = 2;
const city = "Delhi";
if (true) {
let inside = "Block Variable";
console.log(inside);
}
// const object example
const product = {
name: "Mobile",
price: 10000
};
product.price = 12000;
console.log(count);
console.log(city);
console.log(product);
</script>
</body>
</html>
π― Practice Task
- Create a variable using let and update its value.
- Create a constant and try reassigning it.
- Use const with an object and modify its properties.
Arrow Functions
Arrow functions are a shorter and modern way to write functions in JavaScript. They use the => syntax and provide a cleaner and more concise code style.
Basic Syntax
// Traditional function
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => {
return a + b;
};
Short Syntax (Implicit Return)
const multiply = (a, b) => a * b;
console.log(multiply(3, 4));
Single Parameter
const greet = name => {
console.log("Hello " + name);
};
No Parameters
const sayHello = () => {
console.log("Hello World");
};
Arrow Function & this
let user = {
name: "Raman",
greet: function() {
console.log(this.name); // Works
const inner = () => {
console.log(this.name); // Inherits from parent
};
inner();
}
};
user.greet();
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
// Simple arrow function
const square = num => num * num;
// Array with arrow function
let numbers = [1, 2, 3, 4];
let squares = numbers.map(n => n * n);
console.log("Square of 5:", square(5));
console.log("Squares Array:", squares);
</script>
</body>
</html>
π― Practice Task
- Convert a normal function into an arrow function.
- Create an arrow function to find cube of a number.
- Use arrow function inside map() to double array values.
Template Literals
Template literals are a modern way to work with strings in JavaScript. They use backticks (`) instead of quotes and allow embedding variables and expressions using ${ }.
Basic Syntax
let name = "Raman";
let message = `Hello ${name}`;
console.log(message);
Multi-line Strings
let text = `This is line 1
This is line 2
This is line 3`;
console.log(text);
Expressions Inside Template
let a = 5;
let b = 10;
console.log(`Sum is ${a + b}`);
Using with Functions
function greet(name) {
return `Welcome ${name}`;
}
console.log(greet("Raman"));
Comparison with Normal Strings
// Old way
let oldMsg = "Hello " + name + "!";
// Modern way
let newMsg = `Hello ${name}!`;
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
let user = "Raman";
let age = 20;
// Create message
let message = `My name is ${user} and I am ${age} years old.`;
// Multi-line example
let info = `User Details:
Name: ${user}
Age: ${age}`;
console.log(message);
console.log(info);
</script>
</body>
</html>
π― Practice Task
- Create a template string using variables.
- Write a multi-line string using backticks.
- Embed an expression inside a template literal.
Destructuring
Destructuring is a modern JavaScript feature that allows you to extract values from arrays and objects into separate variables in a clean and concise way.
Array Destructuring
let numbers = [10, 20, 30];
let [a, b, c] = numbers;
console.log(a); // 10
console.log(b); // 20
Skipping Values
let arr = [1, 2, 3];
let [x, , z] = arr;
console.log(x); // 1
console.log(z); // 3
Object Destructuring
let user = {
name: "Raman",
age: 20
};
let { name, age } = user;
console.log(name);
console.log(age);
Renaming Variables
let student = {
name: "Aman"
};
let { name: studentName } = student;
console.log(studentName);
Default Values
let person = {
name: "Raman"
};
let { name, city = "Delhi" } = person;
console.log(city); // Delhi
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
// Array destructuring
let fruits = ["Apple", "Banana", "Mango"];
let [f1, f2, f3] = fruits;
// Object destructuring
let product = {
name: "Laptop",
price: 50000
};
let { name, price } = product;
console.log(f1, f2, f3);
console.log(name, price);
</script>
</body>
</html>
π― Practice Task
- Extract values from an array using destructuring.
- Destructure an object and print its properties.
- Use default values in object destructuring.
Spread Operator (...)
The spread operator (...) is used to expand elements of an array, object, or iterable into individual elements. It helps in copying, merging, and passing values easily.
Array Spread
let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5];
console.log(arr2); // [1,2,3,4,5]
Copying Arrays
let original = [10, 20, 30];
let copy = [...original];
console.log(copy);
Merging Arrays
let a = [1, 2];
let b = [3, 4];
let merged = [...a, ...b];
console.log(merged); // [1,2,3,4]
Object Spread
let user = {
name: "Raman",
age: 20
};
let updatedUser = {
...user,
city: "Delhi"
};
console.log(updatedUser);
Passing Arguments
function sum(a, b, c) {
return a + b + c;
}
let nums = [1, 2, 3];
console.log(sum(...nums));
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
// Combine arrays
let fruits = ["Apple", "Banana"];
let moreFruits = ["Mango", "Orange"];
let allFruits = [...fruits, ...moreFruits];
// Copy object
let product = {
name: "Mobile",
price: 10000
};
let newProduct = {
...product,
price: 12000
};
console.log(allFruits);
console.log(newProduct);
</script>
</body>
</html>
π― Practice Task
- Copy an array using spread operator.
- Merge two arrays into one.
- Update object properties using spread.
Modules
JavaScript modules allow you to split your code into separate files. This helps in organizing code, improving readability, and reusing functionality.
Exporting from a File
// file: math.js
export function add(a, b) {
return a + b;
}
export const pi = 3.14;
Importing in Another File
// file: main.js
import { add, pi } from "./math.js";
console.log(add(2, 3));
console.log(pi);
Default Export
// file: greet.js
export default function greet(name) {
return "Hello " + name;
}
Import Default
import greet from "./greet.js";
console.log(greet("Raman"));
Using Modules in HTML
<script type="module" src="main.js"></script>
Complete Practice Code
// math.js
export function multiply(a, b) {
return a * b;
}
// main.js
import { multiply } from "./math.js";
console.log(multiply(4, 5));
π― Practice Task
- Create a module file and export a function.
- Import and use that function in another file.
- Try default export and import.
Classes (OOP)
Classes in JavaScript are used to create objects using a blueprint. They help organize code using Object-Oriented Programming (OOP) concepts like properties, methods, and inheritance.
Basic Syntax
class ClassName {
constructor(parameter) {
this.property = parameter;
}
methodName() {
// code
}
}
Example
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log("Hello " + this.name);
}
}
let p1 = new Person("Raman", 20);
p1.greet();
Inheritance
class Student extends Person {
constructor(name, age, course) {
super(name, age);
this.course = course;
}
showCourse() {
console.log(this.course);
}
}
let s1 = new Student("Aman", 22, "IT");
s1.greet();
s1.showCourse();
Getters & Setters
class User {
constructor(name) {
this._name = name;
}
get name() {
return this._name;
}
set name(value) {
this._name = value;
}
}
let u = new User("Raman");
console.log(u.name);
u.name = "Aman";
console.log(u.name);
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
showDetails() {
console.log(this.name + " costs " + this.price);
}
}
class DiscountProduct extends Product {
constructor(name, price, discount) {
super(name, price);
this.discount = discount;
}
finalPrice() {
return this.price - this.discount;
}
}
let item = new DiscountProduct("Laptop", 50000, 5000);
item.showDetails();
console.log("Final Price:", item.finalPrice());
</script>
</body>
</html>
π― Practice Task
- Create a class with constructor and method.
- Create a child class using inheritance.
- Add a getter and setter in a class.
Callbacks
A callback is a function passed as an argument to another function. It is executed after the completion of a task, helping handle asynchronous operations.
Basic Syntax
function mainFunction(callback) {
// do something
callback();
}
Example
function greet(name, callback) {
console.log("Hello " + name);
callback();
}
function sayBye() {
console.log("Goodbye!");
}
greet("Raman", sayBye);
Callback with Anonymous Function
function processUser(callback) {
console.log("Processing user...");
callback();
}
processUser(function() {
console.log("User processed!");
});
Callback with setTimeout
setTimeout(function() {
console.log("Executed after 2 seconds");
}, 2000);
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
function fetchData(callback) {
console.log("Fetching data...");
setTimeout(function() {
console.log("Data received");
callback();
}, 2000);
}
fetchData(function() {
console.log("Processing complete");
});
</script>
</body>
</html>
π― Practice Task
- Create a function that accepts a callback.
- Pass an anonymous function as callback.
- Use setTimeout with a callback.
Promises
A Promise is used to handle asynchronous operations in JavaScript. It represents a value that may be available now, later, or never.
Promise States
// Pending β Initial state
// Fulfilled β Operation successful
// Rejected β Operation failed
Basic Syntax
let promise = new Promise(function(resolve, reject) {
// async task
if (success) {
resolve("Success");
} else {
reject("Error");
}
});
Using .then() and .catch()
let myPromise = new Promise((resolve, reject) => {
resolve("Data received");
});
myPromise
.then(result => console.log(result))
.catch(error => console.log(error));
Example with setTimeout
let fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data loaded");
}, 2000);
});
fetchData.then(data => console.log(data));
Handling Errors
let check = new Promise((resolve, reject) => {
let success = false;
if (success) {
resolve("All good");
} else {
reject("Something went wrong");
}
});
check
.then(res => console.log(res))
.catch(err => console.log(err));
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
function getData() {
return new Promise((resolve, reject) => {
console.log("Fetching data...");
setTimeout(() => {
let success = true;
if (success) {
resolve("Data fetched successfully");
} else {
reject("Error fetching data");
}
}, 2000);
});
}
getData()
.then(data => {
console.log(data);
})
.catch(err => {
console.log(err);
});
</script>
</body>
</html>
π― Practice Task
- Create a simple Promise that resolves after 2 seconds.
- Handle success using .then().
- Handle error using .catch().
Async / Await
Async/Await is a modern way to handle asynchronous operations in JavaScript. It makes asynchronous code look and behave like synchronous code, improving readability.
Basic Syntax
// async function always returns a Promise
async function functionName() {
let result = await promise;
}
Example
function getData() {
return new Promise(resolve => {
setTimeout(() => {
resolve("Data received");
}, 2000);
});
}
async function fetchData() {
let data = await getData();
console.log(data);
}
fetchData();
Handling Errors (try...catch)
async function loadData() {
try {
let result = await Promise.reject("Error occurred");
console.log(result);
} catch (err) {
console.log(err);
}
}
loadData();
Multiple Await
async function showData() {
let a = await Promise.resolve(10);
let b = await Promise.resolve(20);
console.log(a + b);
}
showData();
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
function fetchUser() {
return new Promise(resolve => {
setTimeout(() => {
resolve("User data loaded");
}, 2000);
});
}
async function loadUser() {
console.log("Loading...");
try {
let user = await fetchUser();
console.log(user);
} catch (err) {
console.log("Error:", err);
}
}
loadUser();
</script>
</body>
</html>
π― Practice Task
- Create an async function that waits for a Promise.
- Handle errors using try...catch.
- Use multiple await statements.
Fetch API
The Fetch API is used to make network requests to servers. It allows you to fetch data from APIs and work with it in your application.
Basic Syntax
fetch("url")
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => console.log(error));
Example
fetch("https://jsonplaceholder.typicode.com/users")
.then(res => res.json())
.then(users => {
console.log(users);
});
Using Async/Await
async function getUsers() {
try {
let response = await fetch("https://jsonplaceholder.typicode.com/users");
let data = await response.json();
console.log(data);
} catch (error) {
console.log(error);
}
}
getUsers();
POST Request
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
title: "Hello",
body: "World"
})
})
.then(res => res.json())
.then(data => console.log(data));
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<button onclick="loadData()">Load Users</button>
<ul id="list"></ul>
<script>
async function loadData() {
let list = document.getElementById("list");
list.innerHTML = "Loading...";
try {
let res = await fetch("https://jsonplaceholder.typicode.com/users");
let data = await res.json();
list.innerHTML = "";
data.forEach(user => {
let li = document.createElement("li");
li.textContent = user.name;
list.appendChild(li);
});
} catch (err) {
list.innerHTML = "Error loading data";
}
}
</script>
</body>
</html>
π― Practice Task
- Fetch data from a public API.
- Display fetched data in HTML.
- Handle errors using try...catch.
JSON (JavaScript Object Notation)
JSON is a lightweight data format used to store and exchange data between a server and a client. It looks similar to JavaScript objects but is written as a string.
JSON Syntax
{
"name": "Raman",
"age": 20,
"city": "Delhi"
}
Convert Object to JSON (stringify)
let obj = {
name: "Raman",
age: 20
};
let jsonData = JSON.stringify(obj);
console.log(jsonData);
Convert JSON to Object (parse)
let jsonString = '{"name":"Raman","age":20}';
let obj = JSON.parse(jsonString);
console.log(obj.name);
Example
let user = {
name: "Aman",
city: "Mumbai"
};
// Convert to JSON
let data = JSON.stringify(user);
// Convert back to object
let newUser = JSON.parse(data);
console.log(newUser);
Using JSON with Fetch
fetch("https://jsonplaceholder.typicode.com/users")
.then(res => res.json()) // Converts JSON to JS object
.then(data => console.log(data));
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<script>
// JavaScript object
let student = {
name: "Raman",
marks: 85
};
// Convert to JSON
let jsonData = JSON.stringify(student);
console.log("JSON:", jsonData);
// Convert back to object
let parsedData = JSON.parse(jsonData);
console.log("Object:", parsedData);
</script>
</body>
</html>
π― Practice Task
- Convert an object into JSON string.
- Parse JSON string into object.
- Fetch data from API and log JSON.
Local Storage
Local Storage is a web storage feature that allows you to store data in the browser permanently (until manually cleared). It stores data as key-value pairs.
Basic Syntax
// Store data
localStorage.setItem("key", "value");
// Get data
localStorage.getItem("key");
// Remove item
localStorage.removeItem("key");
// Clear all data
localStorage.clear();
Example
// Save data
localStorage.setItem("username", "Raman");
// Get data
let user = localStorage.getItem("username");
console.log(user);
Storing Objects (JSON)
let user = {
name: "Raman",
age: 20
};
// Convert to JSON before storing
localStorage.setItem("user", JSON.stringify(user));
// Convert back to object
let data = JSON.parse(localStorage.getItem("user"));
console.log(data.name);
Removing Data
localStorage.removeItem("username");
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<input type="text" id="name" placeholder="Enter name">
<button onclick="saveData()">Save</button>
<button onclick="loadData()">Load</button>
<p id="output"></p>
<script>
function saveData() {
let name = document.getElementById("name").value;
localStorage.setItem("name", name);
}
function loadData() {
let name = localStorage.getItem("name");
document.getElementById("output").innerText = name;
}
</script>
</body>
</html>
π― Practice Task
- Store and retrieve a value using localStorage.
- Store an object using JSON.
- Remove a specific item from storage.
Session Storage
Session Storage is used to store data temporarily in the browser. The data is available only for the duration of the page session and gets cleared when the browser tab is closed.
Basic Syntax
// Store data
sessionStorage.setItem("key", "value");
// Get data
sessionStorage.getItem("key");
// Remove item
sessionStorage.removeItem("key");
// Clear all data
sessionStorage.clear();
Example
// Save data
sessionStorage.setItem("username", "Raman");
// Get data
let user = sessionStorage.getItem("username");
console.log(user);
Storing Objects (JSON)
let user = {
name: "Raman",
age: 20
};
// Convert to JSON
sessionStorage.setItem("user", JSON.stringify(user));
// Convert back to object
let data = JSON.parse(sessionStorage.getItem("user"));
console.log(data.name);
Difference: Local vs Session Storage
// localStorage β permanent (until cleared)
// sessionStorage β temporary (cleared when tab closes)
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<input type="text" id="name" placeholder="Enter name">
<button onclick="saveData()">Save</button>
<button onclick="loadData()">Load</button>
<p id="output"></p>
<script>
function saveData() {
let name = document.getElementById("name").value;
sessionStorage.setItem("name", name);
}
function loadData() {
let name = sessionStorage.getItem("name");
document.getElementById("output").innerText = name;
}
</script>
</body>
</html>
π― Practice Task
- Store and retrieve data using sessionStorage.
- Store an object using JSON.
- Compare localStorage and sessionStorage behavior.
Cookies
Cookies are small pieces of data stored in the browser. They are used to store user information like login sessions, preferences, and tracking data.
Basic Syntax
// Set cookie
document.cookie = "username=Raman";
// Read cookies
console.log(document.cookie);
Setting Expiry Date
let date = new Date();
date.setTime(date.getTime() + (24 * 60 * 60 * 1000)); // 1 day
document.cookie = "user=Raman; expires=" + date.toUTCString();
Adding Path
document.cookie = "theme=dark; path=/";
Deleting Cookie
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
Example Functions
function setCookie(name, value) {
document.cookie = name + "=" + value + "; path=/";
}
function getCookie() {
return document.cookie;
}
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<input type="text" id="name" placeholder="Enter name">
<button onclick="saveCookie()">Save</button>
<button onclick="showCookie()">Show</button>
<p id="output"></p>
<script>
function saveCookie() {
let name = document.getElementById("name").value;
document.cookie = "username=" + name + "; path=/";
}
function showCookie() {
document.getElementById("output").innerText = document.cookie;
}
</script>
</body>
</html>
π― Practice Task
- Set a cookie with name and value.
- Display cookies in console or page.
- Delete a cookie using expiry date.
Mini Projects
Mini projects help you apply your JavaScript knowledge in real-world scenarios. They improve problem-solving skills and build confidence in coding.
Beginner Projects
// 1. Counter App
// Increase / Decrease number using buttons
// 2. Color Changer
// Change background color on button click
// 3. Number Guessing Game
// Generate random number and guess it
Intermediate Projects
// 1. To-Do List App
// Add, delete, mark tasks complete
// 2. Calculator
// Perform basic arithmetic operations
// 3. Form Validation
// Validate inputs with error messages
Advanced Projects
// 1. Weather App
// Fetch API + display weather data
// 2. User Directory
// Fetch users and display in cards
// 3. Notes App
// Store notes using localStorage
Example (Simple Counter)
let count = 0;
function increase() {
count++;
console.log(count);
}
function decrease() {
count--;
console.log(count);
}
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<h2 id="count">0</h2>
<button onclick="increase()">+</button>
<button onclick="decrease()">-</button>
<script>
let count = 0;
function increase() {
count++;
document.getElementById("count").innerText = count;
}
function decrease() {
count--;
document.getElementById("count").innerText = count;
}
</script>
</body>
</html>
π― Practice Task
- Create a working counter app.
- Build a simple calculator.
- Develop a to-do list using DOM.
Final Project
The final project is your opportunity to apply everything youβve learned. It combines concepts like DOM manipulation, events, APIs, storage, and modern JavaScript.
Project Idea: Smart Student Manager
// Features:
// Add student details
// Display student list
// Edit & delete student
// Store data using localStorage
// Search students
Key Concepts Used
// DOM Manipulation
// Event Handling
// Arrays & Objects
// Local Storage
// Functions & Loops
Basic Structure
<input type="text" id="name" placeholder="Enter Name">
<button onclick="addStudent()">Add</button>
<ul id="list"></ul>
Example Logic
let students = [];
function addStudent() {
let name = document.getElementById("name").value;
students.push(name);
displayStudents();
}
function displayStudents() {
let list = document.getElementById("list");
list.innerHTML = "";
students.forEach((student, index) => {
let li = document.createElement("li");
li.textContent = student;
list.appendChild(li);
});
}
Complete Practice Code
<!DOCTYPE html>
<html>
<body>
<h2>Student Manager</h2>
<input type="text" id="name" placeholder="Enter Name">
<button onclick="addStudent()">Add Student</button>
<ul id="list"></ul>
<script>
let students = JSON.parse(localStorage.getItem("students")) || [];
function addStudent() {
let name = document.getElementById("name").value;
if (name === "") return;
students.push(name);
localStorage.setItem("students", JSON.stringify(students));
displayStudents();
}
function displayStudents() {
let list = document.getElementById("list");
list.innerHTML = "";
students.forEach((student, index) => {
let li = document.createElement("li");
li.textContent = student;
list.appendChild(li);
});
}
// Load data on start
displayStudents();
</script>
</body>
</html>
π― Final Challenge
- Add delete button for each student.
- Add edit/update feature.
- Add search functionality.
- Improve UI with CSS styling.
π Course Completed!
Congratulations! Youβve successfully finished this course.