Introduction to JavaScript
JavaScript is a high-level, interpreted programming language that runs inside browsers and servers. It is used to make web pages interactive, dynamic, and intelligent.
- Runs in browser & Node.js
- Used for frontend & backend
- Event-driven & asynchronous
Why JavaScript Matters
- It powers interactivity (forms, animations, dynamic content).
- It works across platforms (web, mobile, desktop, server).
- It has a huge ecosystem (libraries, frameworks, tools).
Core Characteristics
- Dynamically typed and flexible.
- Supports functional, object-oriented, and procedural styles.
- Single-threaded with asynchronous event loop.
How JavaScript Runs
In browsers, JavaScript runs in the JavaScript engine (like V8 in Chrome). In Node.js, it runs on the server to build APIs, scripts, and tools.
Basic Syntax
JavaScript syntax defines the rules for writing JavaScript programs. Understanding syntax is the first step toward writing clean and correct code.
JavaScript Structure with HTML
You can add JavaScript inside the <script> tag
in the HTML file, or link an external .js file.
For better performance, place scripts at the end of <body>
or use defer.
<!-- Inline script -->
<script>
console.log("Hello from inline JS");
</script>
<!-- External script -->
<script src="app.js" defer></script>
Comments
Comments are used to explain code and are ignored by the JavaScript engine. They help developers understand the logic later.
// Single-line comment /* Multi-line comment Used for longer explanations */
Variables in JavaScript
Variables are containers used to store data values. JavaScript provides three ways to declare variables.
let x = 10; // block-scoped variable const y = 20; // constant value (cannot change) var z = 5; // function-scoped (old style)
let Keyword
let is used to declare variables whose values can change.
It has block scope, meaning it exists only inside the block `{}`.
let count = 1;
count = 2; // allowed
if(true){
let a = 10;
console.log(a); // works
}
// console.log(a); β error (block scope)
const Keyword
const is used when the value should not change.
It also has block scope.
const PI = 3.14;
// PI = 3.15; β Error (cannot reassign)
const user = { name: "Aman" };
user.name = "Rahul"; // β
allowed (object reference remains same)
var Keyword (Old Style)
var was used before ES6. It has function scope
and causes many bugs due to hoisting.
It is not recommended.
var num = 10;
if(true){
var num = 20;
}
console.log(num); // 20 (unexpected behavior)
Hoisting (Important Concept)
Hoisting means JavaScript moves variable declarations to the top of the scope before execution.
console.log(a); // undefined var a = 5; // console.log(b); β error let b = 10;
β Use
let when value can changeβ Use
const by defaultβ Avoid
var
Naming Rules for Variables
- Must start with a letter,
_or$ - Cannot start with a number
- Case-sensitive (
ageβAge) - Use meaningful names
let userName = "Rahul"; // β good let _count = 10; // β valid let 1value = 5; // β invalid
Data Types
JavaScript is a dynamically typed language, meaning you do not need to specify the data type of a variable. The type is determined at runtime.
Primitive Data Types
- Number
- String
- Boolean
- Undefined
- Null
- Symbol
- BigInt
1οΈβ£ Number
The Number type represents both integers and floating-point numbers.
let age = 25; let price = 99.99; let negative = -10; console.log(typeof age); // number
Special numeric values:
let x = Infinity; let y = -Infinity; let z = NaN; // Not a Number console.log(10 / "abc"); // NaN
2οΈβ£ String
Strings represent text data and can be written using single quotes, double quotes, or backticks.
let name = "Alice";
let city = 'Delhi';
let message = `Hello ${name}, welcome!`;
console.log(message);
3οΈβ£ Boolean
Boolean represents logical values: true or false.
let isLoggedIn = true; let hasPermission = false; console.log(5 > 3); // true
4οΈβ£ Undefined
A variable is undefined when it is declared but not assigned a value.
let score; console.log(score); // undefined console.log(typeof score); // undefined
5οΈβ£ Null
null represents an intentional empty value.
let data = null; console.log(data); // null console.log(typeof data); // object (JavaScript bug)
null is an object due to a historical JavaScript bug.
6οΈβ£ Symbol
Symbols are unique and immutable values, mainly used as object keys.
let id1 = Symbol("id");
let id2 = Symbol("id");
console.log(id1 === id2); // false
7οΈβ£ BigInt
BigInt is used for very large integers.
let bigNumber = 12345678901234567890n; console.log(typeof bigNumber); // bigint
Non-Primitive (Reference) Data Types
- Object
- Array
- Function
8οΈβ£ Object
Objects store data in key-value pairs.
let person = {
name: "Bob",
age: 30,
isStudent: false
};
console.log(person.name); // Bob
9οΈβ£ Array
Arrays store ordered collections of values.
let fruits = ["apple", "banana", "orange"];
fruits.push("grape");
console.log(fruits[0]); // apple
π Function
Functions are also objects in JavaScript.
function greet(name){
return "Hello " + name;
}
console.log(greet("Aman"));
typeof Operator
The typeof operator is used to check data types.
console.log(typeof "Hello"); // string
console.log(typeof 100); // number
console.log(typeof true); // boolean
console.log(typeof []); // object
console.log(typeof {}); // object
console.log(typeof null); // object (bug)
β Use
typeof for type checkingβ Prefer
const for reference typesβ Understand primitive vs reference behavior
Operators
Operators are special symbols used to perform operations on values and variables. JavaScript operators help in calculations, comparisons, logical decisions, and writing smart conditions.
1οΈβ£ Arithmetic Operators
Used to perform mathematical calculations.
let a = 10; let b = 3; console.log(a + b); // Addition β 13 console.log(a - b); // Subtraction β 7 console.log(a * b); // Multiplication β 30 console.log(a / b); // Division β 3.33 console.log(a % b); // Modulus (remainder) β 1
Increment and Decrement operators:
let count = 5; count++; // 6 count--; // 5
2οΈβ£ Assignment Operators
Used to assign values to variables.
let x = 10; x += 5; // x = x + 5 β 15 x -= 3; // x = x - 3 β 12 x *= 2; // x = x * 2 β 24 x /= 4; // x = x / 4 β 6
3οΈβ£ Comparison Operators
Comparison operators compare two values and return
true or false.
let p = 10; let q = "10"; console.log(p == q); // true (value only) console.log(p === q); // false (value + type) console.log(p != q); // false console.log(p !== q); // true console.log(p > 5); // true console.log(p <= 10); // true
=== instead of == to avoid bugs.
4οΈβ£ Logical Operators
Used to combine multiple conditions.
let age = 20; let hasID = true; console.log(age >= 18 && hasID); // AND β true console.log(age < 18 || hasID); // OR β true console.log(!hasID); // NOT β false
πΉ Logical AND (&&) Return Value Concept
Logical operators do not always return true or false. They return actual values.
console.log(5 && 10); // 10 console.log(0 && 10); // 0 console.log(5 || 10); // 5 console.log(0 || 10); // 10
5οΈβ£ Ternary Operator (Conditional Operator)
The ternary operator is a short form of if-else.
let marks = 45; let result = marks >= 40 ? "Pass" : "Fail"; console.log(result); // Pass
Same logic using if-else:
if (marks >= 40) {
result = "Pass";
} else {
result = "Fail";
}
6οΈβ£ Real-World Example
let isLoggedIn = true; let username = isLoggedIn && "Nafees"; console.log(username); // Nafees
β Summary
- Arithmetic operators β calculations
- Assignment operators β update values
- Comparison operators β true / false
- Logical operators β combine conditions
- Ternary operator β short if-else
Control Flow Statements
Control Flow defines the order in which JavaScript statements are executed. It allows JavaScript to make decisions, repeat actions, skip code blocks, and respond intelligently to different conditions.
1οΈβ£ if Statement
The if statement executes a block of code
only when the condition is true.
let age = 20;
if (age >= 18) {
console.log("You are eligible to vote");
}
How it works:
- The condition inside
ifis evaluated - If true β code runs
- If false β code is skipped
2οΈβ£ if...else Statement
The if...else statement provides
two execution paths.
let temperature = 30;
if (temperature > 25) {
console.log("It is hot");
} else {
console.log("It is cold");
}
3οΈβ£ else if Statement
Use else if when you need to
check multiple conditions.
let marks = 72;
if (marks >= 90) {
console.log("Grade A");
} else if (marks >= 75) {
console.log("Grade B");
} else if (marks >= 50) {
console.log("Grade C");
} else {
console.log("Fail");
}
4οΈβ£ Nested if Statements
A nested if means an if
inside another if.
let username = "admin";
let password = "1234";
if (username === "admin") {
if (password === "1234") {
console.log("Login Successful");
} else {
console.log("Wrong Password");
}
} else {
console.log("Invalid User");
}
5οΈβ£ switch Statement
The switch statement is used when
one value is compared against
multiple possible cases.
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
case 4:
console.log("Thursday");
break;
default:
console.log("Invalid Day");
}
break is mandatory to stop execution.
Without it, all following cases will run (fall-through).
When to use switch?
- Menu selection
- Day / month logic
- Status codes
6οΈβ£ Ternary Operator (Conditional Expression)
The ternary operator is a shorter alternative
to if...else for simple conditions.
let age = 20; let result = age >= 18 ? "Adult" : "Minor"; console.log(result);
Syntax:
condition ? valueIfTrue : valueIfFalse
7οΈβ£ Logical Operators in Control Flow
AND (&&) β All conditions must be true
let isLoggedIn = true;
let isAdmin = true;
if (isLoggedIn && isAdmin) {
console.log("Access Granted");
}
OR (||) β At least one condition must be true
let hasEmail = false;
let hasPhone = true;
if (hasEmail || hasPhone) {
console.log("Contact possible");
}
NOT (!) β Reverses condition
let isBlocked = false;
if (!isBlocked) {
console.log("User can access");
}
8οΈβ£ Real-World Example: Login System
let isLoggedIn = true;
let role = "admin";
if (isLoggedIn && role === "admin") {
console.log("Welcome Admin");
} else if (isLoggedIn) {
console.log("Welcome User");
} else {
console.log("Please Login");
}
β Summary
ifβ execute code when condition is trueif...elseβ two execution pathselse ifβ multiple conditionsnested ifβ conditions inside conditionsswitchβ multiple fixed valuesternaryβ short conditional logic- Logical operators β advanced decision making
Loops
A loop is used to execute the same block of code repeatedly as long as a specified condition is true. Loops are widely used in JavaScript for working with arrays, objects, numbers, DOM elements, and API data.
1οΈβ£ for Loop
The for loop is used when we
already know how many times the loop should run.
Syntax:
for (initialization; condition; increment/decrement) {
// code to execute
}
for (let i = 1; i <= 5; i++) {
console.log(i);
}
How it works:
let i = 1β starting valuei <= 5β condition to continuei++β increase value after each iteration
Looping through an array:
let fruits = ["apple", "banana", "orange"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Reverse loop:
for (let i = 5; i >= 1; i--) {
console.log(i);
}
2οΈβ£ while Loop
The while loop is used when
the exact number of iterations is unknown
and execution depends only on a condition.
let count = 5;
while (count > 0) {
console.log(count);
count--;
}
Real-world example:
let password = "";
while (password !== "admin") {
password = prompt("Enter password");
}
3οΈβ£ do...while Loop
The do...while loop
always executes at least once,
even if the condition is false.
let num = 0;
do {
console.log("This runs at least once");
num++;
} while (num < 0);
Use case example:
let otp;
do {
otp = prompt("Enter OTP");
} while (otp !== "1234");
4οΈβ£ for...of Loop
The for...of loop is used for
arrays and strings.
It provides a clean and modern syntax.
let colors = ["red", "green", "blue"];
for (let color of colors) {
console.log(color);
}
String example:
let name = "JS";
for (let char of name) {
console.log(char);
}
5οΈβ£ for...in Loop
The for...in loop is used to
iterate over the keys of an object.
let user = {
name: "Nafees",
age: 22,
city: "Delhi"
};
for (let key in user) {
console.log(key + " : " + user[key]);
}
for...in is not recommended for arrays.
6οΈβ£ forEach Loop (Array Method)
forEach is an array method
that executes a function for each element.
let numbers = [1, 2, 3, 4];
numbers.forEach(function(num) {
console.log(num * 2);
});
Using arrow function:
numbers.forEach(num => console.log(num));
7οΈβ£ break and continue
break β immediately stops the loop
for (let i = 1; i <= 5; i++) {
if (i === 4) break;
console.log(i);
}
continue β skips the current iteration
for (let i = 1; i <= 5; i++) {
if (i === 3) continue;
console.log(i);
}
8οΈβ£ Nested Loop
A nested loop is a loop inside another loop. It is commonly used for tables, patterns, and matrices.
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 2; j++) {
console.log(i, j);
}
}
9οΈβ£ Loop Comparison (Quick Review)
- for β fixed number of iterations
- while β condition-based looping
- do...while β runs at least once
- for...of β arrays and strings
- for...in β objects
- forEach β arrays only
Functions
A function is a reusable block of code that performs a specific task. Functions help reduce repetition, improve readability, and make code easier to maintain.
Why Use Functions?
- Avoid repeating the same code
- Write clean and organized programs
- Improve debugging and maintenance
- Reuse logic anywhere in the application
1οΈβ£ Function Declaration
A function declaration defines a function using the
function keyword.
// Function declaration
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // 5
Explanation:
aandbare parametersreturnsends a value back- The function can be reused multiple times
2οΈβ£ Function Expression
A function expression stores a function inside a variable.
const subtract = function(a, b) {
return a - b;
};
console.log(subtract(10, 4)); // 6
3οΈβ£ Arrow Function (ES6)
Arrow functions provide a shorter syntax and are commonly used in modern JavaScript.
// Arrow function const multiply = (a, b) => a * b; console.log(multiply(2, 3)); // 6
Arrow function with block body:
const divide = (a, b) => {
return a / b;
};
console.log(divide(10, 2)); // 5
const cube = num => num * num * num; console.log(cube(3)); const isEven = num => num % 2 === 0; console.log(isEven(10)); console.log(isEven(7));
this.
4οΈβ£ Parameters and Arguments
Parameters are variables defined in a function. Arguments are actual values passed to the function.
function greet(name) {
console.log("Hello " + name);
}
greet("Nafees");
greet("JavaScript");
5οΈβ£ Default Parameters
Default parameters provide a value when no argument is passed.
function welcome(user = "Guest") {
console.log("Welcome " + user);
}
welcome();
welcome("Admin");
6οΈβ£ Return vs console.log
return sends data back from a function,
while console.log only displays output.
function square(num) {
return num * num;
}
let result = square(4);
console.log(result);
7οΈβ£ Calling a Function
A function runs only when it is called.
function welcomeUser() {
console.log("Welcome to Technacode");
}
welcomeUser();
welcomeUser();
8οΈβ£ Nested Functions
A function inside another function is called a nested function.
function mainFunction() {
console.log("Main function");
function childFunction() {
console.log("Child function");
}
childFunction();
}
mainFunction();
function outer() {
function inner() {
console.log("Inner function");
}
inner();
}
outer();
9οΈβ£ Callback Functions
A callback is a function passed as an argument to another function.
function processData(callback) {
callback();
}
processData(function() {
console.log("Callback executed");
});
Arrow callback example:
setTimeout(() => {
console.log("Executed after 2 seconds");
}, 2000);
Real-world callback example:
function calculate(a, b, operation) {
return operation(a, b);
}
const addNumbers = (x, y) => x + y;
const multiplyNumbers = (x, y) => x * y;
console.log(calculate(5, 3, addNumbers));
console.log(calculate(5, 3, multiplyNumbers));
π Real-World Example: Calculator
function calculate(a, b, operation) {
return operation(a, b);
}
const add = (x, y) => x + y;
const multiply = (x, y) => x * y;
console.log(calculate(5, 3, add));
console.log(calculate(5, 3, multiply));
Real-World Example: Login Check
function login(username, password) {
if (username === "admin" && password === "1234") {
return "Login Successful";
}
return "Login Failed";
}
console.log(login("admin", "1234"));
console.log(login("user", "0000"));
1οΈβ£1οΈβ£ Functions with Arrays
function printItems(arr) {
for (let item of arr) {
console.log(item);
}
}
printItems(["HTML", "CSS", "JavaScript"]);
1οΈβ£2οΈβ£ Functions with Objects
function showUser(user) {
console.log("Name:", user.name);
console.log("Age:", user.age);
}
showUser({ name: "Nafees", age: 22 });
β Summary
- Functions group reusable logic
- Function declaration is hoisted
- Arrow functions are modern and concise
- Parameters receive values
- Return sends data back
- Callbacks enable advanced logic
Objects
In JavaScript, an object is a collection of related data and functionality stored as keyβvalue pairs. Objects are used to represent real-world entities like users, products, cars, students, etc.
1οΈβ£ Creating a Basic Object
Objects are created using curly braces { }.
let person = {
name: "Alice",
age: 25,
city: "London"
};
console.log(person);
2οΈβ£ Accessing Object Properties
You can access properties in two ways:
Dot Notation
console.log(person.name); console.log(person.age);
Bracket Notation
console.log(person["city"]);
3οΈβ£ Adding & Updating Properties
person.age = 26; // update person.country = "UK"; // add new property console.log(person);
4οΈβ£ Deleting a Property
delete person.city; console.log(person);
5οΈβ£ Object Methods
When a function is stored inside an object, it is called a method.
let user = {
name: "Bob",
greet: function () {
console.log("Hello " + this.name);
}
};
user.greet();
6οΈβ£ Understanding the this Keyword
let car = {
brand: "BMW",
model: "X5",
info: function () {
return this.brand + " " + this.model;
}
};
console.log(car.info());
7οΈβ£ Nested Objects
let student = {
name: "Nafees",
marks: {
math: 85,
science: 90
}
};
console.log(student.marks.math);
8οΈβ£ Looping Through an Object
let product = {
name: "Laptop",
price: 50000,
brand: "HP"
};
for (let key in product) {
console.log(key + ": " + product[key]);
}
9οΈβ£ Objects with External Functions
function displayUser(user) {
console.log("Name:", user.name);
console.log("Age:", user.age);
}
displayUser({ name: "Aman", age: 23 });
π Array of Objects (Very Important)
let users = [
{ name: "Ali", age: 20 },
{ name: "Sara", age: 22 },
{ name: "John", age: 25 }
];
users.forEach(user => {
console.log(user.name, user.age);
});
1οΈβ£1οΈβ£ Object Destructuring (ES6)
let employee = {
id: 101,
role: "Developer",
salary: 60000
};
let { role, salary } = employee;
console.log(role);
console.log(salary);
1οΈβ£2οΈβ£ Useful Object Methods
let keys = Object.keys(employee); let values = Object.values(employee); let entries = Object.entries(employee); console.log(keys); console.log(values); console.log(entries);
1οΈβ£3οΈβ£ Real-World Example: User Profile
let profile = {
username: "technacode",
isLoggedIn: true,
login() {
console.log("User logged in");
},
logout() {
console.log("User logged out");
}
};
if (profile.isLoggedIn) {
profile.logout();
}
π Practice Tasks
- Create an object for a book
- Create an array of student objects
- Loop through object and print values
- Add a method to calculate total marks
- Use destructuring on an object
Arrays
An array is a data structure used to store multiple values in a single variable. Arrays are ordered, zero-indexed, and can hold any data type.
1οΈβ£ Creating an Array
let fruits = ["apple", "banana", "orange"]; console.log(fruits);
Array index starts from 0.
console.log(fruits[0]); // apple console.log(fruits[2]); // orange
2οΈβ£ Updating Array Elements
fruits[1] = "mango"; console.log(fruits);
3οΈβ£ Array Length
console.log(fruits.length);
4οΈβ£ push() and pop()
push() adds an element to the end
pop() removes the last element
fruits.push("grape");
console.log(fruits);
fruits.pop();
console.log(fruits);
5οΈβ£ shift() and unshift()
unshift() adds to start
shift() removes from start
fruits.unshift("kiwi");
console.log(fruits);
fruits.shift();
console.log(fruits);
6οΈβ£ Looping Through an Array
Using for Loop
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Using for...of Loop
for (let fruit of fruits) {
console.log(fruit);
}
7οΈβ£ forEach() Method
fruits.forEach(function(fruit) {
console.log(fruit);
});
fruits.forEach(fruit => console.log(fruit));
8οΈβ£ map() Method
map() creates a new array
by transforming each element.
let upperFruits = fruits.map(fruit => fruit.toUpperCase()); console.log(upperFruits);
9οΈβ£ filter() Method
let numbers = [10, 25, 40, 15, 5]; let filteredNumbers = numbers.filter(num => num > 20); console.log(filteredNumbers);
π reduce() Method
let prices = [100, 200, 300]; let total = prices.reduce((sum, price) => sum + price, 0); console.log(total);
1οΈβ£1οΈβ£ find() Method
let result = numbers.find(num => num > 20); console.log(result);
1οΈβ£2οΈβ£ includes()
console.log(fruits.includes("apple"));
console.log(fruits.includes("papaya"));
1οΈβ£3οΈβ£ sort()
let scores = [40, 10, 100, 25]; scores.sort((a, b) => a - b); console.log(scores);
1οΈβ£4οΈβ£ splice()
fruits.splice(1, 1, "pineapple"); console.log(fruits);
1οΈβ£5οΈβ£ slice()
let newFruits = fruits.slice(0, 2); console.log(newFruits);
1οΈβ£6οΈβ£ Array of Objects (Very Important)
let students = [
{ name: "Ali", marks: 80 },
{ name: "Sara", marks: 90 },
{ name: "John", marks: 70 }
];
students.forEach(student => {
console.log(student.name, student.marks);
});
1οΈβ£7οΈβ£ Real-World Example: Shopping Cart
let cart = [200, 450, 300];
let cartTotal = cart.reduce((sum, item) => sum + item, 0);
console.log("Total Price:", cartTotal);
π Practice Tasks
- Create an array of numbers and find the sum
- Filter even numbers from an array
- Convert all strings to uppercase using map()
- Find the highest number in an array
- Create an array of users and print their names
DOM Manipulation in JavaScript
The DOM (Document Object Model) represents the structure of an HTML document as a tree of objects. JavaScript can use the DOM to read, change, add, or remove HTML elements dynamically.
1οΈβ£ Selecting Elements from the DOM
JavaScript provides multiple ways to select HTML elements.
getElementById
const title = document.getElementById("title");
console.log(title);
querySelector
const heading = document.querySelector("h1");
const card = document.querySelector(".card");
querySelectorAll
const items = document.querySelectorAll("li");
console.log(items);
querySelector returns the first match
β querySelectorAll returns a NodeList
2οΈβ£ Changing Text Content
const h1 = document.querySelector("h1");
h1.textContent = "Hello JavaScript";
h1.innerHTML = "Welcome to JS";
innerHTML carefully to avoid security issues.
3οΈβ£ Changing Styles Using JavaScript
const box = document.querySelector(".card");
box.style.backgroundColor = "#fff7cc";
box.style.borderRadius = "12px";
box.style.padding = "20px";
4οΈβ£ Working with CSS Classes
const element = document.querySelector(".card");
element.classList.add("active");
element.classList.remove("active");
element.classList.toggle("active");
5οΈβ£ Working with Attributes
const img = document.querySelector("img");
img.setAttribute("alt", "JavaScript Logo");
console.log(img.getAttribute("src"));
img.removeAttribute("width");
6οΈβ£ Event Handling (Very Important)
Events allow JavaScript to respond to user actions like clicks, typing, hovering, etc.
const btn = document.getElementById("btn");
btn.addEventListener("click", () => {
alert("Button clicked!");
});
Mouse & Keyboard Events
btn.addEventListener("mouseover", () => {
console.log("Mouse over button");
});
document.addEventListener("keydown", (event) => {
console.log("Key pressed:", event.key);
});
7οΈβ£ Creating & Adding Elements
const list = document.querySelector("ul");
const newItem = document.createElement("li");
newItem.textContent = "New Item";
list.appendChild(newItem);
8οΈβ£ Removing Elements
const removeItem = document.querySelector(".remove");
removeItem.remove();
9οΈβ£ Looping Through DOM Elements
const buttons = document.querySelectorAll("button");
buttons.forEach(btn => {
btn.addEventListener("click", () => {
console.log("Button clicked");
});
});
π Form Handling with DOM
const form = document.querySelector("form");
form.addEventListener("submit", (e) => {
e.preventDefault();
const name = document.getElementById("name").value;
console.log("User Name:", name);
});
1οΈβ£1οΈβ£ Real-World Example: Theme Toggle
const toggleBtn = document.getElementById("toggle");
toggleBtn.addEventListener("click", () => {
document.body.classList.toggle("dark-mode");
});
1οΈβ£2οΈβ£ DOMContentLoaded Event
document.addEventListener("DOMContentLoaded", () => {
console.log("DOM fully loaded");
});
π Practice Tasks
- Change text on button click
- Create a list dynamically using JavaScript
- Toggle dark/light theme
- Validate form input using DOM
- Show/hide elements on click
Events in JavaScript
In JavaScript, an event is an action performed by the user or the browser, such as clicking a button, typing on the keyboard, submitting a form, or loading a page.
1οΈβ£ What is an Event?
Examples of common events:
- Mouse click
- Mouse hover
- Key press
- Form submit
- Page load
2οΈβ£ addEventListener()
The addEventListener() method attaches an event
handler to an element.
const btn = document.getElementById("btn");
btn.addEventListener("click", () => {
console.log("Button clicked");
});
3οΈβ£ Mouse Events
const box = document.querySelector(".box");
box.addEventListener("click", () => {
console.log("Box clicked");
});
box.addEventListener("mouseover", () => {
console.log("Mouse over box");
});
box.addEventListener("mouseout", () => {
console.log("Mouse left box");
});
click β mouse click
β mouseover β cursor enters element
β mouseout β cursor leaves element
4οΈβ£ Keyboard Events
document.addEventListener("keydown", (event) => {
console.log("Key pressed:", event.key);
});
document.addEventListener("keyup", () => {
console.log("Key released");
});
5οΈβ£ Form Events
const form = document.querySelector("form");
form.addEventListener("submit", (e) => {
e.preventDefault();
console.log("Form submitted");
});
const input = document.getElementById("username");
input.addEventListener("input", () => {
console.log("User typing...");
});
6οΈβ£ Event Object
The event object contains details about the event.
document.addEventListener("click", (event) => {
console.log(event.target);
console.log(event.type);
});
7οΈβ£ Using this in Events
const button = document.querySelector(".myBtn");
button.addEventListener("click", function () {
this.style.backgroundColor = "green";
});
8οΈβ£ Multiple Events on One Element
const card = document.querySelector(".card");
card.addEventListener("mouseenter", () => {
console.log("Mouse entered");
});
card.addEventListener("mouseleave", () => {
console.log("Mouse left");
});
9οΈβ£ Event Delegation (Advanced & Important)
Event delegation allows handling events on multiple child elements using a single parent element.
const list = document.querySelector("ul");
list.addEventListener("click", (e) => {
if (e.target.tagName === "LI") {
console.log("Clicked item:", e.target.textContent);
}
});
π Removing an Event Listener
function sayHello() {
console.log("Hello!");
}
btn.addEventListener("click", sayHello);
btn.removeEventListener("click", sayHello);
1οΈβ£1οΈβ£ Page Load Events
window.addEventListener("load", () => {
console.log("Page fully loaded");
});
document.addEventListener("DOMContentLoaded", () => {
console.log("HTML loaded");
});
1οΈβ£2οΈβ£ Real-World Example: Button Counter
let count = 0;
const counterBtn = document.getElementById("counter");
counterBtn.addEventListener("click", () => {
count++;
console.log("Clicked:", count);
});
π Practice Tasks
- Change text on button click
- Show alert on mouse hover
- Detect key presses
- Validate form on submit
- Create a click counter
ES6+ JavaScript Features (Modern JavaScript)
ES6 (ECMAScript 2015) and later versions introduced powerful features that make JavaScript cleaner, shorter, faster, and easier to read. Modern JavaScript development heavily relies on ES6+ features.
1οΈβ£ Template Literals
Template literals use backticks (`) and allow
string interpolation and multi-line strings.
let name = "Alice";
let age = 22;
let message = `Hello ${name}, you are ${age} years old.`;
console.log(message);
let multiLine = ` This is line one This is line two This is line three `; console.log(multiLine);
2οΈβ£ Destructuring (Arrays & Objects)
Array Destructuring
let colors = ["red", "green", "blue"]; let [first, second] = colors; console.log(first); // red console.log(second); // green
Object Destructuring
let user = {
username: "john_doe",
email: "john@gmail.com",
age: 25
};
let { username, age } = user;
console.log(username);
console.log(age);
3οΈβ£ Default Parameters
Default parameters allow function parameters to have default values if no argument is passed.
function greet(name = "Guest") {
console.log(`Welcome ${name}`);
}
greet("Rahul");
greet();
4οΈβ£ Arrow Functions
Arrow functions provide a shorter syntax and do not bind their own this.
const add = (a, b) => a + b; console.log(add(5, 3));
const square = x => x * x; console.log(square(4));
5οΈβ£ Spread Operator (...)
The spread operator expands elements of an array or object.
With Arrays
let arr1 = [1, 2, 3]; let arr2 = [...arr1, 4, 5]; console.log(arr2);
With Objects
let user1 = { name: "Alex", age: 20 };
let user2 = { ...user1, city: "Delhi" };
console.log(user2);
6οΈβ£ Rest Operator (...)
The rest operator collects multiple values into an array.
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3, 4));
7οΈβ£ let and const
let and const provide block-scoped variables.
let count = 10; count = 20; const PI = 3.14; // PI = 4; β Error
8οΈβ£ Classes
Classes are a cleaner way to create objects and handle inheritance.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
let p1 = new Person("Aman", 23);
p1.greet();
9οΈβ£ JavaScript Modules (export / import)
Modules allow splitting code into reusable files.
Export (math.js)
export function add(a, b) {
return a + b;
}
export const PI = 3.14;
Import (main.js)
import { add, PI } from "./math.js";
console.log(add(2, 3));
console.log(PI);
π Optional Chaining (?.)
Prevents errors when accessing nested properties.
let userData = {};
console.log(userData.profile?.name);
π Practice Tasks
- Create a function using default parameters
- Use destructuring on an API response object
- Merge two arrays using spread operator
- Build a class for Student
- Create and import a module
Asynchronous JavaScript
Asynchronous JavaScript allows code to run without blocking the execution of other tasks. This is important for handling time-consuming operations like API calls, timers, file loading, and user interactions.
1οΈβ£ Synchronous vs Asynchronous
Synchronous Code (Blocking)
console.log("Start");
console.log("Middle");
console.log("End");
Asynchronous Code (Non-Blocking)
console.log("Start");
setTimeout(() => {
console.log("Async Task");
}, 2000);
console.log("End");
2οΈβ£ setTimeout()
setTimeout() executes a function
after a specified delay.
setTimeout(() => {
console.log("Executed after 1 second");
}, 1000);
Cancel setTimeout
let timer = setTimeout(() => {
console.log("Will not run");
}, 2000);
clearTimeout(timer);
3οΈβ£ setInterval()
setInterval() repeatedly executes
code at fixed time intervals.
let count = 0;
let intervalId = setInterval(() => {
count++;
console.log("Count:", count);
if (count === 5) {
clearInterval(intervalId);
}
}, 1000);
4οΈβ£ Callbacks
A callback is a function passed as an argument to be executed later.
function fetchData(callback) {
setTimeout(() => {
callback("Data received");
}, 1000);
}
fetchData((data) => {
console.log(data);
});
5οΈβ£ Promises
A Promise represents a value that will be available in the future.
const promise = new Promise((resolve, reject) => {
let success = true;
setTimeout(() => {
if (success) {
resolve("Task completed");
} else {
reject("Task failed");
}
}, 1000);
});
promise
.then(result => console.log(result))
.catch(error => console.log(error));
Promise States
- Pending
- Fulfilled
- Rejected
6οΈβ£ Promise Chaining
new Promise(resolve => resolve(5)) .then(num => num * 2) .then(result => console.log(result));
7οΈβ£ async / await
async/await makes asynchronous code
look like synchronous code.
function getData() {
return new Promise(resolve => {
setTimeout(() => resolve("Data loaded"), 1000);
});
}
async function showData() {
const result = await getData();
console.log(result);
}
showData();
8οΈβ£ Error Handling with try...catch
async function loadData() {
try {
let response = await Promise.reject("Network Error");
console.log(response);
} catch (error) {
console.log("Error:", error);
}
}
loadData();
9οΈβ£ Promise.all()
Runs multiple promises in parallel.
let p1 = Promise.resolve(10);
let p2 = Promise.resolve(20);
Promise.all([p1, p2]).then(values => {
console.log(values);
});
π Real-World Example: Fake API Call
function fakeApi() {
return new Promise(resolve => {
setTimeout(() => {
resolve({ user: "Admin", role: "Manager" });
}, 1500);
});
}
async function login() {
let data = await fakeApi();
console.log("Welcome", data.user);
}
login();
π Practice Tasks
- Create a countdown using setInterval
- Convert a callback to a promise
- Handle errors using try/catch
- Fetch data using async/await
- Run multiple promises using Promise.all