JavaScript
JavaScript
🧠 1. Basics (Foundation)
📘 1.1 JavaScript Introduction (What, Why Use, Where Use)
Definition:
👉 JavaScript is a programming language used to make websites interactive and dynamic.
It works mainly in browsers (frontend) but can also run on servers (backend) using
[Link].
🧩 In simple words:
JavaScript is a programming language that helps make websites lively and interactive — for
example, when you click, animations appear or data updates dynamically.
Reason Explanation
🎨 Interactive Websites Buttons, sliders, pop-ups, forms — all can work dynamically
You can control how your webpage behaves (e.g., if the user
⚙️Logic Handling
clicks, show a message)
Area Example
<script>
function greet() {
alert("Hello, welcome to JavaScript!");
}
</script>
</body>
</html>
🗣 Output:
When you click the button → a popup appears saying “Hello, welcome to JavaScript!”
Definition:
Variables are containers used to store data values in JavaScript.
Syntax:
var name = "Suba";
let age = 21;
const country = "India";
📘 Types of Variables
Reassign
Keyword Scope Hoisting Description
Allowed?
var Function scoped ✅ Yes ✅ Yes Old method, avoid using now
💡 Example:
[Link](name); // Suba
[Link](age); // 21
[Link](city); // Madurai
🗣 Explanation:
let y; [Link](y) →
Undefined Variable declared but not assigned a value
undefined
- Subtraction 5-2=3
* Multiplication 3*2=6
/ Division 10 / 2 = 5
% Modulus (remainder) 10 % 3 = 1
** Exponentiation 2 ** 3 = 8
B. Comparison Operators
Return a Boolean (true/false).
Operator Description Example
C. Logical Operators
Used for true/false logic.
` `
D. Assignment Operators
Assign or update values.
= Assign x=5
B. Explicit Conversion
You manually convert types using functions.
// String → Number
let num = Number("123"); // 123
let num2 = parseInt("123.45"); // 123
let num3 = parseFloat("123.45"); // 123.45
// Number → String
let str = String(123); // "123"
let str2 = (123).toString(); // "123"
// Boolean Conversion
Boolean(0); // false
Boolean(1); // true
Boolean(""); // false
Boolean("Hi");// true
Tip: Always check for NaN when converting strings to numbers.
Number 10 10
Addition 5+2 7
Conditional Statements
Conditional statements allow JavaScript to make decisions based on conditions.
A. if Statement
Executes a block of code if the condition is true.
let age = 18;
B. if...else Statement
Executes one block if the condition is true, another block if false.
let age = 15;
C. if...else if...else
For multiple conditions.
let marks = 75;
D. switch Statement
Useful when comparing one value with many options.
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"
break stops execution after a match.
default runs if no case matches.
A. for Loop
Runs a fixed number of times.
for (let i = 1; i <= 5; i++) {
[Link]("Hello", i);
}
Output:
Hello 1
Hello 2
Hello 3
Hello 4
Hello 5
i++ means i = i + 1.
B. while Loop
Runs as long as the condition is true.
let i = 1;
while (i <= 5) {
[Link]("Hi", i);
i++;
}
Output is same as for loop.
Be careful: If condition never becomes false → infinite loop.
C. do...while Loop
Runs at least once, then checks the condition.
let i = 1;
do {
[Link]("Hey", i);
i++;
} while (i <= 5);
Output:
Hey 1
Hey 2
Hey 3
Hey 4
Hey 5
B. for...of
Loops through values of an array or iterable.
let arr = [10, 20, 30];
for (let value of arr) {
[Link](value);
}
Output:
10
20
30
Can also use with strings:
let name = "Suba";
for (let char of name) {
[Link](char);
}
Output:
S
u
b
a
Key difference:
for...in → keys/indexes
for...of → values
✅ Summary Table
Runs if
if if(x>5){} condition
true
Compare one
switch(x){case1:
switch value against
...}
many
Repeat fixed
for for(i=0;i<5;i++)
times
Repeat while
while while(x<5)
true
Control Flow Example Description
Runs at least
do...while do{} while(x<5)
once
Loop
for...in for(key in obj)
keys/index
What is a Function?
A function is a block of reusable code that performs a
specific task.
Instead of writing the same code again and again, you can
call a function whenever needed.
function greet() {
[Link]("Hello Suba!");
}
A. Parameters
Functions can take inputs called parameters (or arguments).
function greet(name) {
[Link]("Hello " + name + "!");
}
B. Return Statement
Functions can return a value using return.
function add(a, b) {
return a + b;
}
[Link](add(5, 3)); // 8
If the function has only one statement, you can
skip {} and return:
const multiply = (a, b) => a * b;
[Link](multiply(4, 2)); // 8
No this binding in arrow functions → behaves
differently in objects (advanced topic).
processUser("Suba", greet);
Output:
Processing user...
Hello Suba
Control Flow Example Description
Can be called
Normal Function function greet(){}
before definition
Passed as
Callback processUser(name,
argument, called
Function callback)
later
💡 Quick Tip:
let person = {
name: "Suba",
age: 21,
greet: function() {
[Link]("Hello, " + [Link]);
}
};
Properties: name, age
Method: greet()
[Link]([Link]); // Suba
[Link](); // Hello, Suba
this refers to the current object.
B. Modifying Objects
[Link] = 22; // Update property
[Link] = "Madurai"; // Add new property
delete [Link]; // Delete property
C. Nested Objects
Objects can have objects inside them.
let student = {
name: "Vidya",
marks: { math: 90, science: 85 }
};
[Link]([Link]); // 90
B. Nested Arrays
Arrays can contain arrays or objects.
let nestedArr = [[1,2],[3,4]];
[Link](nestedArr[0][1]); // 2
let users = [
{name: "Suba", age: 21},
{name: "Vidya", age: 22}
];
[Link](users[1].name); // Vidya
B. Rest Operator
Control Flow Example Description
Key-value
Object {name:"Suba", age:21}
collection
Object Function
greet:function(){}
Method inside object
Object inside
Nested Object {marks:{math:90}}
object
Transform
map() [Link](x=>x*2) array, returns
new
Filter
filter() [Link](x=>x>2) elements,
returns new
Reduce to
reduce() [Link]((a,c)=>a+c,0)
single value
return
Nested Multi-level
arr=[{name:"Suba"}]
Array/Object data
Expand
Spread ... [...arr1, ...arr2]
array/object
Collect
Rest ... function sum(...nums) remaining
values
💡 Quick Tip:
Converts string to
toUpperCase() "hello".toUpperCase() "HELLO"
uppercase
Converts string to
toLowerCase() "HELLO".toLowerCase() "hello"
lowercase
Returns character at
charAt(index) "Suba".charAt(1) "u"
specified index
Checks if string
includes(value) "Hello".includes("lo") true
contains value
Removes whitespace
trim() " Hello ".trim() "Hello"
from both ends
B. Example Usage
let text = " Hello Suba ";
[Link]([Link]); // 13
[Link]([Link]()); // " HELLO SUBA "
[Link]([Link]()); // "Hello Suba"
[Link]([Link]("Suba"));// true
[Link]([Link]("Suba","Vidya")); // " Hello Vidya "
[Link]([Link](" ")); // ["", "", "Hello", "Suba", "", ""]
The Math object provides mathematical constants and functions. You do not create a
Math object, just call its methods.
Rounds x to nearest
[Link](x) [Link](4.6) 5
integer
Rounds x up to
[Link](x) [Link](4.1) 5
nearest integer
Rounds x down to
[Link](x) [Link](4.9) 4
nearest integer
Removes decimal
[Link](x) [Link](4.9) 4
part
Returns x to the
[Link](x,y) [Link](2,3) 8
power of y
Returns absolute
[Link](x) [Link](-5) 5
value
Returns smallest
[Link](a,b,...) [Link](1,5,3) 1
number
Returns largest
[Link](a,b,...) [Link](1,5,3) 5
number
Returns random
[Link]() number between 0 [Link]() 0.123…
and 1
Random integer
[Link]([Link]()*10) [Link]([Link]()*10) e.g., 7
between 0-9
B. Example Usage
let num = 4.7;
[Link]([Link](num)); // 5
[Link]([Link](num)); // 5
[Link]([Link](num)); // 4
[Link]([Link](num)); // 4
[Link]([Link](16)); // 4
[Link]([Link](2,3)); // 8
[Link]([Link](-10)); // 10
✅ Summary
💡 Quick Tip:
A. getElementById
Selects one element by its id.
Returns a single element object.
let heading = [Link]("title");
[Link]([Link]); // Access text
Example in HTML:
<h1 id="title">Hello</h1>
B. getElementsByClassName
Selects all elements with the given class.
Returns an HTMLCollection (like an array but not exactly).
let items = [Link]("item");
[Link](items[0].innerText); // Access first element
Example in HTML:
<p class="item">Item 1</p>
<p class="item">Item 2</p>
JavaScript can respond to user actions like clicks, typing, hover, etc.
A. Using HTML attribute (onclick)
<button onclick="sayHello()">Click Me</button>
<script>
function sayHello() {
alert("Hello Suba!");
}
</script>
B. Using addEventListener (Recommended)
let btn = [Link]("button");
[Link]("click", function() {
alert("Button clicked!");
});
Advantages:
o Can attach multiple events
A. Creating an element
let newPara = [Link]("p"); // Create <p> element
[Link] = "I am new!";
[Link](newPara); // Add to page
B. Removing an element
let oldPara = [Link]("old");
[Link](); // Removes element from DOM
C. Modifying element dynamically
let list = [Link]("ul");
let newItem = [Link]("li");
[Link] = "New Item";
[Link](newItem); // Add new <li> to <ul>
6️⃣ Summary Table
Conce
Method/Property Example Notes
pt
Returns
Select getElementsByClassName("cl [Link](
HTMLCollecti
by class ass") "item")
on
CSS
Selecto querySelector(".class") [Link](".item") First match
r
CSS
NodeList of all
Selecto querySelectorAll(".class") [Link](".item")
matches
r All
Change
innerText [Link] = "Hi" Only text
text
Change
[Link] [Link] = "red" Inline CSS
style
Add
appendChild [Link](child) Add to DOM
element
Remov
Delete from
e remove() [Link]()
DOM
element
💡 Quick Tips:
function test() {
[Link](globalVar); // Accessible
}
test();
[Link](globalVar); // Accessible
B. Function Scope
Variables declared inside a function are local to that function.
Cannot be accessed outside the function.
function myFunc() {
let localVar = "I am local";
[Link](localVar); // Accessible
}
myFunc();
[Link](localVar); // Error: localVar is not defined
C. Block Scope
Variables declared with let or const inside { } are block-scoped.
var is not block scoped (function-scoped).
if(true){
let blockVar = "I am block scoped";
var funcVar = "I am function scoped";
}
[Link](blockVar); // Error
[Link](funcVar); // Accessible
2️⃣ Hoisting
Hoisting moves variable and function declarations to the top of their scope before
execution.
A. Functions are hoisted
greet(); // Works
function greet(){
[Link]("Hello");
}
B. Variables
var is hoisted but undefined initially
let and const are hoisted but cannot be accessed before declaration (TDZ -
Temporal Dead Zone)
[Link](x); // undefined
var x = 5;
[Link](y); // Error
let y = 10;
3️⃣ Closures
A closure is a function that remembers variables from its outer scope, even after the outer
function has finished.
function outer() {
let count = 0;
return function inner() {
count++;
[Link](count);
}
}
Examples
// Object method
let obj = {
name: "Suba",
greet: function() {
[Link]([Link]);
}
};
[Link](); // Suba
// Arrow function
let arrow = () => [Link](this);
arrow(); // Window (or outer scope)
A. Prototype
Every JavaScript object has a prototype.
You can add methods/properties to it for reuse.
function Person(name){
[Link] = name;
}
[Link] = function(){
[Link]("Hello " + [Link]);
}
B. Inheritance (Prototype-based)
Objects can inherit properties/methods from other objects.
function Animal(name){
[Link] = name;
}
[Link] = function(){
[Link]([Link] + " makes a sound");
}
function Dog(name){
[Link](this, name); // Inherit properties
}
Closure Function remembers outer variables function outer(){ return function inner(){}}
💡 Quick Tips:
1. Use closures for private variables.
2. Always understand what this refers to, especially with arrow functions.
3. Use prototype to save memory when creating multiple objects.
4. Inheritance in JS is prototype-based, not class-based (though ES6 classes make it
look like classes).
What is Asynchronous JavaScript?
Normally, JavaScript executes line by line (synchronously).
Asynchronous JS allows code to run without blocking the rest of the program.
Useful for timers, API calls, or heavy tasks.
processUser("Suba", greet);
Output:
Processing user...
Hello Suba
Real-time analogy: You order food, and the chef calls you (callback) when it’s ready.
5️⃣ Promises
o Fulfilled → Success
o Rejected → Error
Example:
let promise = new Promise((resolve, reject) => {
let success = true;
setTimeout(() => {
if(success) resolve("Task completed");
else reject("Task failed");
}, 2000);
});
promise
.then(result => [Link](result)) // Success
.catch(error => [Link](error)); // Error
Output (after 2 sec):
Task completed
Real-time analogy: Promise is like ordering a package online. It will either arrive
(resolve) or fail (reject).
greet();
Output:
Start
Hello after 2 seconds
Use: Simplifies chaining multiple async tasks without callback hell.
getPost();
Real-time analogy: You ask a server for info → server responds → you handle data
when it arrives.
Callback Hell Nested callbacks making code unreadable Multiple nested API calls
try {
[Link](divide(10,0));
} catch(error) {
[Link]("Error:", [Link]);
}
Output:
Error: Cannot divide by zero!
Real-time analogy:
o Imagine a vending machine → you try to buy candy with no money →
machine throws an error instead of giving wrong candy.
Reason Explanation
💡 Quick Tips:
// Old way
[Link]("Hello " + name + ", your age is " + age);
// Template literal
[Link](`Hello ${name}, your age is ${age}`);
Output: Hello Suba, your age is 21
Also supports multi-line strings:
let text = `Hello
Suba
Welcome!`;
[Link](text);
Why use it: Cleaner syntax, easier to read, supports expressions.
2️⃣ Destructuring
Modules allow splitting code into multiple files for better maintainability.
export → expose variables/functions
import → use them in another file
Example:
[Link]
export function add(a,b){ return a+b; }
export const PI = 3.14;
[Link]
import { add, PI } from "./[Link]";
[Link](add(2,3)); // 5
[Link](PI); // 3.14
Why use it: Better organization, reusable code, avoids global scope pollution.
4️⃣ Classes
Allows safe access to nested object properties without throwing errors if a property
is undefined or null.
let person = {name:"Suba", address:{city:"Madurai"}};
[Link]([Link]); // Madurai
[Link]([Link]?.phone); // undefined (does not throw error)
Works with arrays and functions too:
let arr = [1,2,3];
[Link](arr?.[5]); // undefined
Why use it: Prevents runtime errors when accessing deep or optional properties.
Object-oriented
Classes Blueprint for objects class Person {...}
programming, clean syntax
💡 Quick Tips:
// Get data
let name = [Link]("name");
[Link](name); // Suba
// Remove data
[Link]("name");
// Clear all
[Link]();
Why use it:
Persist data across sessions (like user preferences, theme).
Faster than server-side storage for small data.
B. SessionStorage
Stores data only for the current session.
Data is deleted when the browser/tab is closed.
[Link]("sessionName", "Suba");
[Link]([Link]("sessionName")); // Suba
Why use it:
Useful for temporary data, e.g., form input while user navigates pages.
JSON is a data format used to send and receive data between server and client.
It is lightweight and easy to read.
A. Converting JS objects to JSON
let person = {name:"Suba", age:21};
let jsonData = [Link](person);
[Link](jsonData); // '{"name":"Suba","age":21}'
B. Converting JSON to JS object
let obj = [Link]('{"name":"Suba","age":21}');
[Link]([Link]); // Suba
Why use it:
Communicate with APIs (fetch/send data).
Store complex data in LocalStorage/SessionStorage.
JavaScript is single-threaded, meaning it can execute one task at a time, but it can handle
asynchronous tasks via Event Loop.
A. Call Stack
A stack data structure that keeps track of function calls.
LIFO (Last In First Out) → last function called is executed first.
function first() {
second();
[Link]("First");
}
function second() {
[Link]("Second");
}
first();
Execution flow:
1. first() pushed to stack
2. second() pushed → executed → popped
3. [Link]("First") executes → popped
Output:
Second
First
B. Event Loop
Handles asynchronous code like setTimeout, Promises, fetch.
How it works:
1. JS executes synchronous code in the call stack.
2. Async tasks go to Web APIs / browser APIs (like timers, fetch).
3. When ready, async callbacks go to task queue.
4. Event loop checks if call stack is empty → pushes task from queue.
Example:
[Link]("Start");
setTimeout(() => {
[Link]("Timeout");
}, 0);
[Link]("End");
Output:
Start
End
Timeout
Explanation:
setTimeout callback goes to task queue, executed after call stack is empty.
Why use it:
Makes JS non-blocking.
Handles async tasks like API calls, timers, DOM events efficiently.
for current
forms
session
Tracks
Understand
function
Call Stack first(); second(); sync code
execution
execution
(LIFO)
Make JS non-
Handles blocking,
Event Loop setTimeout(()=>{},0)
async tasks handle async
code
💡 Quick Tips:
B. Object
Instance of a class.
Contains specific values for properties.
let vidya = new Person("Vidya", 22); // Object
[Link]([Link]); // Vidya
C. Encapsulation
Hiding internal details of an object.
Use private properties with _ or # (ES2020).
class BankAccount {
#balance = 0; // private property
deposit(amount) {
this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
D. Inheritance
One class inherits properties and methods from another class.
Use extends and super().
class Animal {
constructor(name) {
[Link] = name;
}
speak() {
[Link](`${[Link]} makes a sound`);
}
}
E. Polymorphism
Same method behaves differently for different objects.
Achieved by method overriding.
let cat = new Animal("Kitty");
[Link](); // Kitty makes a sound
[Link](); // Tommy barks
Both speak() exist, but behave differently.
F. Abstraction
Hide unnecessary details, show only essential features.
Achieved using classes and methods.
class Car {
startEngine() {
this.#checkFuel();
[Link]("Engine started");
}
#checkFuel() {
[Link]("Fuel level OK"); // private method
}
}
[Link] = function() {
[Link](`Hello, ${[Link]}`);
};
💡 Quick Tips:
Task
Calculator
Purpose: Create a simple arithmetic calculator that performs basic operations like addition,
subtraction, multiplication, and division.
Key Concepts:
Handling user input via buttons.
Performing arithmetic operations.
Displaying results dynamically.
Managing state (current input, previous input).
Learning Outcome: You'll grasp event handling, DOM manipulation, and basic logic
implementation.
2. To-Do List
Purpose: Develop an application that allows users to add, edit, and delete tasks.
Key Concepts:
Creating and managing lists.
Handling user interactions (add, edit, delete).
Storing data temporarily (e.g., using arrays).
Learning Outcome: You'll learn about CRUD operations (Create, Read, Update, Delete) and
dynamic content rendering.
3. Digital Clock
Purpose: Build a real-time digital clock that displays the current time and updates every
second.
Key Concepts:
Using JavaScript's setInterval function.
Manipulating Date and Time objects.
Updating the DOM at regular intervals.
Learning Outcome: You'll understand asynchronous operations and time-based functions.
5. Rock-Paper-Scissors Game
Purpose: Develop a simple game where the user plays against the computer.
Key Concepts:
Generating random choices for the computer.
Comparing user and computer choices.
Displaying results and keeping score.
Learning Outcome: You'll practice conditional statements and random number generation.
6. Form Validation
Purpose: Implement a form that validates user input before submission (e.g., checking for
empty fields, valid email format).
Key Concepts:
Accessing and validating form elements.
Providing real-time feedback to users.
Preventing form submission on invalid input.
Learning Outcome: You'll enhance your understanding of user input handling and validation
techniques.
8. Countdown Timer
Purpose: Build a timer that counts down from a specified time and alerts the user when time
is up.
Key Concepts:
Using setInterval and clearInterval.
Calculating time differences.
Updating the DOM dynamically.
Learning Outcome: You'll understand time-based events and user notifications.
9. Quotes Generator
Purpose: Develop an application that displays a random quote each time the user interacts
with it.
Key Concepts:
Storing and retrieving data (quotes).
Manipulating the DOM to display content.
Handling user interactions (e.g., button clicks).
Learning Outcome: You'll practice working with arrays and event listeners.
10. BMI Calculator
Purpose: Create a tool that calculates the Body Mass Index (BMI) based on user input
(weight and height).
Key Concepts:
Performing mathematical calculations.
Converting units (e.g., cm to meters).
Displaying results and categorizing BMI.
Learning Outcome: You'll enhance your skills in mathematical operations and data
presentation.