[go: up one dir, main page]

0% found this document useful (0 votes)
21 views178 pages

Jsnotes

The document provides practical examples of using logic statements and loops in real-life projects, such as weather apps, login systems, and online stores. It covers various scenarios including age verification, traffic light systems, and form validation, demonstrating how to implement these concepts with code snippets. Additionally, it introduces functions and DOM manipulation, showcasing their applications in tasks like greeting users, changing text content, and validating forms.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views178 pages

Jsnotes

The document provides practical examples of using logic statements and loops in real-life projects, such as weather apps, login systems, and online stores. It covers various scenarios including age verification, traffic light systems, and form validation, demonstrating how to implement these concepts with code snippets. Additionally, it introduces functions and DOM manipulation, showcasing their applications in tasks like greeting users, changing text content, and validating forms.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 178

Got it, Abhi!

Let’s focus on how you can use concepts from Chapter 4 onward in real-life
projects, keeping it simple and practical.

Chapter 4: Logic Statements in Real-Life Projects

Logic statements are like decision-makers in your code.

1. Weather App

Use if-else to display what to wear based on the weather:

Let weather = “rainy”;

If (weather === “rainy”) {

Console.log(“Take an umbrella.”);

} else {

Console.log(“Enjoy the sunshine!”);

2. Login System

Check if the username and password are correct:

Let username = “Abhi”;

Let password = “12345”;

If (username === “Abhi” && password === “12345”) {

Console.log(“Login successful!”);

} else {

Console.log(“Invalid credentials.”);

}
3. Online Store Discounts

Apply discounts based on the total price:

Let total = 1200;

If (total > 1000) {

Console.log(“You get a 10% discount!”);

} else {

Console.log(“No discount available.”);

4. Age Verification

Allow access only if the user is 18 or older:

Let age = 16;

If (age >= 18) {

Console.log(“Access granted.”);

} else {

Console.log(“Access denied.”);

5. Light/Dark Mode Toggle

Switch themes based on user preference:

Let theme = “dark”;

Theme === “dark” ? console.log(“Enable Dark Mode”) : console.log(“Enable Light Mode”);


6. Rock, Paper, Scissors Game

Let player1 = “rock”;

Let player2 = “scissors”;

If (player1 === “rock” && player2 === “scissors”) {

Console.log(“Player 1 wins!”);

} else if (player1 === player2) {

Console.log(“It’s a tie!”);

} else {

Console.log(“Player 2 wins!”);

7. Form Validation

Check if a form field is empty:

Let name = “”;

If (name === “”) {

Console.log(“Name cannot be empty.”);

} else {

Console.log(“Form submitted.”);

8. Traffic Light System

Let light = “red”;


Switch (light) {

Case “red”:

Console.log(“Stop!”);

Break;

Case “yellow”:

Console.log(“Get ready.”);

Break;

Case “green”:

Console.log(“Go!”);

Break;

Default:

Console.log(“Invalid light.”);

9. Quiz Game

Check the answer to a question:

Let answer = “JavaScript”;

If (answer === “JavaScript”) {

Console.log(“Correct!”);

} else {

Console.log(“Try again.”);

10. Bank Balance Alert

Notify users if their balance is low:


Let balance = 500;

If (balance < 1000) {

Console.log(“Low balance alert!”);

} else {

Console.log(“Your balance is sufficient.”);

Chapter 5: Loops in Real-Life Projects

Loops help you repeat tasks efficiently.

1. Display Items in a Shopping Cart

Let cart = [“Shirt”, “Pants”, “Shoes”];

For (let item of cart) {

Console.log(item);

2. Countdown Timer

For (let I = 10; I >= 1; i--) {

Console.log(i);

}
Console.log(“Happy New Year!”);

3. Generate Multiplication Table

Let num = 5;

For (let I = 1; I <= 10; i++) {

Console.log(`${num} x ${i} = ${num * i}`);

4. Validate Multiple Form Fields

Let fields = [“name”, “email”, “password”];

For (let field of fields) {

Console.log(`Validating ${field}…`);

5. Calculate Total Price

Let prices = [100, 200, 300];

Let total = 0;

For (let price of prices) {

Total += price;

Console.log(`Total Price: ${total}`);

6. Create a Leaderboard
Let scores = [90, 85, 70];

For (let I = 0; I < scores.length; i++) {

Console.log(`Rank ${I + 1}: ${scores[i]}`);

7. Password Strength Checker

Let password = “Abhi123!”;

Let hasNumber = false;

For (let char of password) {

If (!isNaN(char)) {

hasNumber = true;

break;

Console.log(hasNumber ? “Strong password.” : “Weak password.”);

8. Find Prime Numbers

Let num = 20;

For (let I = 2; I <= num; i++) {

Let isPrime = true;

For (let j = 2; j < I; j++) {

If (I % j === 0) {

isPrime = false;
break;

If (isPrime) console.log(i);

9. Auto-Generate Usernames

Let users = [“Abhi”, “John”, “Jane”];

For (let user of users) {

Console.log(`${user.toLowerCase()}123`);

10. Display Calendar Dates

For (let day = 1; day <= 31; day++) {

Console.log(`December ${day}`);

Would you like me to continue with Functions and Classes? Let me know!

Sure, Abhi! Let’s dive deeper into logic statements and loops, starting from basic to
advanced examples with real-life use cases.
More Examples: Logic Statements (if, else, switch)

Basic Examples:

1. Check Even or Odd Number

Let number = 7;

If (number % 2 === 0) {

Console.log(“Even number”);

} else {

Console.log(“Odd number”);

2. Greeting Based on Time

Let hour = 10;

If (hour < 12) {

Console.log(“Good Morning!”);

} else if (hour < 18) {

Console.log(“Good Afternoon!”);

} else {

Console.log(“Good Evening!”);

}
3. Detect Leap Year

Let year = 2024;

If ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {

Console.log(`${year} is a leap year.`);

} else {

Console.log(`${year} is not a leap year.`);

4. Grade Checker

Let marks = 75;

If (marks >= 90) {

Console.log(“Grade: A”);

} else if (marks >= 80) {

Console.log(“Grade: B”);

} else if (marks >= 70) {

Console.log(“Grade: C”);

} else {

Console.log(“Grade: F”);

}
Intermediate Examples:

5. Traffic Light Simulation

Let signal = “green”;

Switch (signal) {

Case “red”:

Console.log(“Stop!”);

Break;

Case “yellow”:

Console.log(“Get ready.”);

Break;

Case “green”:

Console.log(“Go!”);

Break;

Default:

Console.log(“Invalid signal.”);

6. Menu Selection

Let choice = 2;

Switch (choice) {

Case 1:
Console.log(“You selected Coffee.”);

Break;

Case 2:

Console.log(“You selected Tea.”);

Break;

Case 3:

Console.log(“You selected Juice.”);

Break;

Default:

Console.log(“Invalid choice.”);

Advanced Examples:

7. Dynamic Price Calculator

Let price = 500;

Let membership = “gold”; // Options: “silver”, “gold”, “platinum”

If (membership === “silver”) {

Price *= 0.9; // 10% discount

} else if (membership === “gold”) {

Price *= 0.8; // 20% discount

} else if (membership === “platinum”) {

Price *= 0.7; // 30% discount


}

Console.log(`Final price: ${price}`);

8. Password Strength Checker

Let password = “Abhi123!”;

If (password.length >= 8 && /\d/.test(password) && /[!@#$%^&*]/.test(password)) {

Console.log(“Strong password”);

} else {

Console.log(“Weak password”);

9. Form Validation

Let username = “abhi”;

Let email = abhi@example.com;

If (username.length < 3) {

Console.log(“Username too short.”);

} else if (!email.includes(“@”)) {

Console.log(“Invalid email.”);

} else {

Console.log(“Form submitted successfully.”);

}
10. Nested Logic for E-Commerce Shipping

Let location = “India”;

Let orderAmount = 1500;

If (location === “India”) {

If (orderAmount > 1000) {

Console.log(“Free shipping available!”);

} else {

Console.log(“Shipping cost: ₹50”);

} else {

Console.log(“International shipping cost: $20”);

More Examples: Loops (for, while, do-while)

Basic Examples:

1. Print Numbers from 1 to 10

For (let I = 1; I <= 10; i++) {


Console.log(i);

2. Sum of Numbers in an Array

Let numbers = [10, 20, 30, 40];

Let sum = 0;

For (let num of numbers) {

Sum += num;

Console.log(`Total sum: ${sum}`);

3. Repeat a String 5 Times

Let message = “Hello!”;

For (let I = 1; I <= 5; i++) {

Console.log(message);

4. Count Down from 10 to 1

Let I = 10;

While (I > 0) {
Console.log(i);

i--;

Intermediate Examples:

5. Filter Even Numbers

Let nums = [1, 2, 3, 4, 5, 6];

For (let num of nums) {

If (num % 2 === 0) {

Console.log(num);

6. Find the Largest Number

Let numbers = [12, 45, 67, 89, 23];

Let largest = numbers[0];

For (let num of numbers) {

If (num > largest) {

Largest = num;

}
}

Console.log(`Largest number: ${largest}`);

7. Reverse a String

Let str = “JavaScript”;

Let reversed = “”;

For (let I = str.length – 1; I >= 0; i--) {

Reversed += str[i];

Console.log(reversed);

Advanced Examples:

8. Generate Fibonacci Sequence

Let n = 10;

Let a = 0, b = 1;

Console.log(a);

Console.log(b);

For (let I = 2; I < n; i++) {

Let next = a + b;

Console.log(next);
A = b;

B = next;

9. Create a Pattern

Let rows = 5;

For (let I = 1; I <= rows; i++) {

Console.log(“*”.repeat(i));

10. Simulate a Loading Bar

Let progress = 0;

While (progress <= 100) {

Console.log(`Loading… ${progress}%`);

Progress += 20;

}
How are these examples so far? Would you like me to cover functions and DOM
manipulation next?

Alright, Abhi! Let’s tackle functions and DOM manipulation with 50 real-life examples,
starting from basic to advanced. I’ll keep it simple and relatable.

Functions in Real Life

Functions are reusable blocks of code that perform specific tasks. Think of them as helpers
that make your code cleaner and more efficient.

Basic Examples: Functions

1. Greet a User

Function greet(name) {

Console.log(`Hello, ${name}!`);

Greet(“Abhi”);

2. Add Two Numbers

Function add(a, b) {
Return a + b;

Console.log(add(5, 10)); // 15

3. Convert Celsius to Fahrenheit

Function toFahrenheit(celsius) {

Return (celsius * 9) / 5 + 32;

Console.log(toFahrenheit(30)); // 86

4. Calculate the Area of a Circle

Function areaOfCircle(radius) {

Return Math.PI * radius * radius;

Console.log(areaOfCircle(7)); // 153.93804002589985

5. Check if a Number is Even

Function isEven(num) {

Return num % 2 === 0;

}
Console.log(isEven(4)); // true

Intermediate Examples: Functions

6. Generate a Random Number

Function getRandomNumber(min, max) {

Return Math.floor(Math.random() * (max – min + 1)) + min;

Console.log(getRandomNumber(1, 100));

7. Capitalize a Word

Function capitalize(word) {

Return word.charAt(0).toUpperCase() + word.slice(1);

Console.log(capitalize(“javascript”)); // JavaScript

8. Check Age for Voting


Function canVote(age) {

Return age >= 18 ? “You can vote!” : “You cannot vote.”;

Console.log(canVote(20));

9. Create a Countdown Timer

Function countdown(start) {

For (let I = start; I >= 0; i--) {

Console.log(i);

Console.log(“Time’s up!”);

Countdown(5);

10. Calculate Total Bill with Tip

Function calculateBill(amount, tipPercentage) {

Return amount + (amount * tipPercentage) / 100;

Console.log(calculateBill(1000, 10)); // 1100


Advanced Examples: Functions

11. Find the Largest Number in an Array

Function findLargest(numbers) {

Return Math.max(…numbers);

Console.log(findLargest([10, 20, 5, 8])); // 20

12. Filter Out Negative Numbers

Function filterNegatives(numbers) {

Return numbers.filter(num => num >= 0);

Console.log(filterNegatives([-5, 10, -3, 7])); // [10, 7]

13. Validate Email Address


Function isValidEmail(email) {

Return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);

Console.log(isValidEmail(abhi@example.com)); // true

14. Reverse a String

Function reverseString(str) {

Return str.split(“”).reverse().join(“”);

Console.log(reverseString(“JavaScript”)); // tpircSavaJ

15. Calculate Compound Interest

Function compoundInterest(principal, rate, time) {

Return principal * Math.pow(1 + rate / 100, time);

Console.log(compoundInterest(1000, 5, 2)); // 1102.5

DOM Manipulation in Real Life


DOM manipulation is about interacting with HTML elements using JavaScript to make web
pages dynamic.

Basic Examples: DOM Manipulation

16. Change Text Content of an Element

Document.getElementById(“title”).innerText = “Hello, Abhi!”;

17. Change Background Color on Button Click

Document.getElementById(“changeColorBtn”).onclick = function () {

Document.body.style.backgroundColor = “lightblue”;

};

18. Hide an Element


Document.getElementById(“hideBtn”).onclick = function () {

Document.getElementById(“content”).style.display = “none”;

};

19. Display an Alert on Click

Document.getElementById(“alertBtn”).addEventListener(“click”, function () {

Alert(“Button clicked!”);

});

20. Add a New List Item

Function addItem() {

Let ul = document.getElementById(“myList”);

Let li = document.createElement(“li”);

li.innerText = “New Item”;

ul.appendChild(li);

Intermediate Examples: DOM Manipulation


21. Change Image Source

Document.getElementById(“myImage”).src = “new-image.jpg”;

22. Toggle Dark Mode

Function toggleDarkMode() {

Document.body.classList.toggle(“dark-mode”);

23. Form Validation

Function validateForm() {

Let name = document.getElementById(“name”).value;

If (name === “”) {

Alert(“Name cannot be empty!”);

Return false;

Return true;
}

24. Create a Dynamic Table

Function createTable(rows, cols) {

Let table = document.createElement(“table”);

For (let I = 0; I < rows; i++) {

Let tr = document.createElement(“tr”);

For (let j = 0; j < cols; j++) {

Let td = document.createElement(“td”);

Td.innerText = `Row ${I + 1}, Col ${j + 1}`;

Tr.appendChild(td);

Table.appendChild(tr);

Document.body.appendChild(table);

createTable(3, 3);

25. Create a Countdown Timer on Page

Function startCountdown() {
Let counter = 10;

Let interval = setInterval(() => {

Document.getElementById(“timer”).innerText = counter;

Counter--;

If (counter < 0) {

clearInterval(interval);

document.getElementById(“timer”).innerText = “Time’s up!”;

}, 1000);

Advanced Examples: DOM Manipulation

26. Drag and Drop

Function allowDrop(event) {

Event.preventDefault();

Function drag(event) {

Event.dataTransfer.setData(“text”, event.target.id);

Function drop(event) {
Event.preventDefault();

Let data = event.dataTransfer.getData(“text”);

Event.target.appendChild(document.getElementById(data));

27. Create a Modal Popup

Function openModal() {

Document.getElementById(“modal”).style.display = “block”;

Function closeModal() {

Document.getElementById(“modal”).style.display = “none”;

28. Real-Time Search Filter

Function filterList() {

Let query = document.getElementById(“search”).value.toLowerCase();

Let items = document.querySelectorAll(“.list-item”);

Items.forEach(item => {

Item.style.display = item.innerText.toLowerCase().includes(query) ? “block” : “none”;

});
}

29. Animate Elements

Function moveElement() {

Let elem = document.getElementById(“box”);

Let pos = 0;

Let interval = setInterval(() => {

If (pos === 350) clearInterval(interval);

Pos++;

Elem.style.left = pos + “px”;

}, 5);

30. Dynamic Form Creation

Function createForm() {

Let form = document.createElement(“form”);

Let input = document.createElement(“input”);

Input.type = “text”;

Input.placeholder = “Enter your name”;

Let button = document.createElement(“button”);


Button.innerText = “Submit”;

Form.appendChild(input);

Form.appendChild(button);

Document.body.appendChild(form);

How’s this so far? I can continue adding more advanced examples or dive into specific
topics like animations or API handling. Let me know!

Alright, Abhi! Let’s go all-in with functions and cover more examples, progressing from
basic to advanced. I’ll also explain advanced topics like callbacks, closures, recursion, and
higher-order functions with real-life use cases.

More Examples: Functions

Basic Examples

1. Convert Minutes to Seconds

Function toSeconds(minutes) {

Return minutes * 60;

Console.log(toSeconds(5)); // 300
2. Check if a String Contains a Word

Function containsWord(sentence, word) {

Return sentence.includes(word);

Console.log(containsWord(“I love JavaScript”, “JavaScript”)); // true

3. Calculate Simple Interest

Function simpleInterest(principal, rate, time) {

Return (principal * rate * time) / 100;

Console.log(simpleInterest(1000, 5, 2)); // 100

4. Generate a Random Hex Color

Function randomHexColor() {

Return `#${Math.floor(Math.random() * 16777215).toString(16)}`;

Console.log(randomHexColor());

5. Check if a Number is Prime


Function isPrime(num) {

If (num <= 1) return false;

For (let I = 2; I < num; i++) {

If (num % I === 0) return false;

Return true;

Console.log(isPrime(7)); // true

Intermediate Examples

6. Generate Password Suggestions

Function generatePassword(length) {

Const chars =
“abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789”;

Let password = “”;

For (let I = 0; I < length; i++) {

Password += chars.charAt(Math.floor(Math.random() * chars.length));

Return password;
}

Console.log(generatePassword(8)); // Random password

7. Find Factorial of a Number

Function factorial(n) {

Let result = 1;

For (let I = 1; I <= n; i++) {

Result *= I;

Return result;

Console.log(factorial(5)); // 120

8. Create a Greeting Message

Function greetUser(name, timeOfDay = “day”) {

Return `Good ${timeOfDay}, ${name}!`;

Console.log(greetUser(“Abhi”, “morning”)); // Good morning, Abhi!

9. Sort an Array of Numbers


Function sortNumbers(arr) {

Return arr.sort((a, b) => a – b);

Console.log(sortNumbers([5, 2, 9, 1])); // [1, 2, 5, 9]

10. Find the GCD of Two Numbers

Function gcd(a, b) {

While (b !== 0) {

Let temp = b;

B = a % b;

A = temp;

Return a;

Console.log(gcd(48, 18)); // 6

Advanced Examples

11. Callback Functions

A callback is a function passed as an argument to another function.


Example: Simulating a Timer

Function executeAfterDelay(callback, delay) {

setTimeout(callback, delay);

executeAfterDelay(() => console.log(“Task completed!”), 2000);

12. Closure

A closure allows a function to remember its outer scope even after the outer function has
executed.

Example: Counter

Function createCounter() {

Let count = 0;

Return function () {

Count++;

Return count;

};

Const counter = createCounter();

Console.log(counter()); // 1

Console.log(counter()); // 2
13. Recursion

A function that calls itself to solve smaller subproblems.

Example: Find Factorial Using Recursion

Function factorialRecursive(n) {

If (n === 0) return 1;

Return n * factorialRecursive(n – 1);

Console.log(factorialRecursive(5)); // 120

14. Higher-Order Functions

A higher-order function takes another function as an argument or returns a function.

Example: Array Transformation

Function transformArray(arr, callback) {

Return arr.map(callback);

Console.log(transformArray([1, 2, 3], num => num * 2)); // [2, 4, 6]

15. Debounce Function

A debounce function limits the rate at which a function is executed.


Example: Search Bar Optimization

Function debounce(func, delay) {

Let timeout;

Return function (…args) {

clearTimeout(timeout);

timeout = setTimeout(() => func(…args), delay);

};

Const search = debounce(query => console.log(`Searching for ${query}`), 300);

Search(“JavaScript”);

Complex Real-Life Examples

16. Memoization

Store computed results to optimize performance.

Example: Fibonacci with Memoization

Function fibonacci() {

Const cache = {};


Return function fib(n) {

If (n in cache) return cache[n];

If (n <= 2) return 1;

Cache[n] = fib(n – 1) + fib(n – 2);

Return cache[n];

};

Const fib = fibonacci();

Console.log(fib(10)); // 55

17. Currying

Transform a function into a sequence of functions.

Example: Curried Addition

Function add(a) {

Return function (b) {

Return a + b;

};

Console.log(add(5)(3)); // 8

18. Dynamic Function Creation

Example: Calculator
Function createCalculator(operation) {

Return function (a, b) {

If (operation === “add”) return a + b;

If (operation === “subtract”) return a – b;

If (operation === “multiply”) return a * b;

If (operation === “divide”) return a / b;

};

Const adder = createCalculator(“add”);

Console.log(adder(5, 3)); // 8

19. Throttling

A throttle function ensures that a function is executed at most once in a specified time
interval.

Example: Scroll Event Optimization

Function throttle(func, limit) {

Let lastFunc;

Let lastRan;

Return function (…args) {

If (!lastRan) {

Func(…args);
lastRan = Date.now();

} else {

clearTimeout(lastFunc);

lastFunc = setTimeout(() => {

if (Date.now() – lastRan >= limit) {

func(…args);

lastRan = Date.now();

}, limit – (Date.now() – lastRan));

};

Const logScroll = throttle(() => console.log(“Scrolled!”), 200);

Window.addEventListener(“scroll”, logScroll);

20. Function Composition

Combine multiple functions into one.

Example: String Transformation

Function compose(…functions) {

Return function (input) {

Return functions.reduce((acc, fn) => fn(acc), input);

};

}
Const toUpperCase = str => str.toUpperCase();

Const appendExclamation = str => `${str}!`;

Const shout = compose(toUpperCase, appendExclamation);

Console.log(shout(“hello”)); // HELLO!

Let me know if you’d like further clarification or additional examples! These concepts are
crucial for mastering JavaScript.

Got it, Abhi! Let’s explore additional examples for functions with more real-life scenarios,
progressing from basic to advanced.

Basic Examples

1. Convert Hours to Days

Function toDays(hours) {

Return hours / 24;

Console.log(toDays(48)); // 2

2. Calculate Rectangle Perimeter


Function rectanglePerimeter(length, width) {

Return 2 * (length + width);

Console.log(rectanglePerimeter(5, 10)); // 30

3. Check Palindrome

Function isPalindrome(str) {

Return str === str.split(“”).reverse().join(“”);

Console.log(isPalindrome(“madam”)); // true

4. Convert String to Title Case

Function toTitleCase(str) {

Return str

.split(“ “)

.map(word => word[0].toUpperCase() + word.slice(1).toLowerCase())

.join(“ “);

Console.log(toTitleCase(“hello world”)); // Hello World

5. Calculate Percentage
Function calculatePercentage(total, obtained) {

Return (obtained / total) * 100;

Console.log(calculatePercentage(200, 150)); // 75

Intermediate Examples

6. Generate Acronyms

Function generateAcronym(phrase) {

Return phrase

.split(“ “)

.map(word => word[0].toUpperCase())

.join(“”);

Console.log(generateAcronym(“JavaScript Object Notation”)); // JSON

7. Flatten a Nested Array

Function flattenArray(arr) {
Return arr.flat(Infinity);

Console.log(flattenArray([1, [2, [3, [4]]]])); // [1, 2, 3, 4]

8. Find the Longest Word in a Sentence

Function longestWord(sentence) {

Return sentence.split(“ “).reduce((longest, word) =>

Word.length > longest.length ? word : longest

);

Console.log(longestWord(“I love JavaScript programming”)); // JavaScript

9. Format Currency

Function formatCurrency(amount) {

Return `$${amount.toFixed(2)}`;

Console.log(formatCurrency(1234.5)); // $1234.50

10. Generate Random Password with Symbols


Function generateSecurePassword(length) {

Const chars =

“abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*
”;

Let password = “”;

For (let I = 0; I < length; i++) {

Password += chars.charAt(Math.floor(Math.random() * chars.length));

Return password;

Console.log(generateSecurePassword(12)); // Random password

Advanced Examples

11. Debounce with Arrow Functions

Const debounce = (func, delay) => {

Let timeout;

Return (…args) => {

clearTimeout(timeout);
timeout = setTimeout(() => func(…args), delay);

};

};

Const logMessage = debounce(() => console.log(“Debounced!”), 300);

logMessage();

12. Throttle with Arrow Functions

Const throttle = (func, limit) => {

Let lastFunc;

Let lastRan;

Return (…args) => {

If (!lastRan) {

Func(…args);

lastRan = Date.now();

} else {

clearTimeout(lastFunc);

lastFunc = setTimeout(() => {

if (Date.now() – lastRan >= limit) {

func(…args);

lastRan = Date.now();

}, limit – (Date.now() – lastRan));

}
};

};

Const logScroll = throttle(() => console.log(“Throttled!”), 500);

logScroll();

13. Partial Application

Function partial(func, …args) {

Return (…remainingArgs) => func(…args, …remainingArgs);

Const multiply = (a, b, c) => a * b * c;

Const multiplyBy2And3 = partial(multiply, 2, 3);

Console.log(multiplyBy2And3(4)); // 24

14. Pipe Functions

Function pipe(…functions) {

Return input => functions.reduce((acc, fn) => fn(acc), input);

Const double = x => x * 2;

Const square = x => x * x;

Const doubleThenSquare = pipe(double, square);


Console.log(doubleThenSquare(3)); // 36

15. Compose Functions

Function compose(…functions) {

Return input => functions.reduceRight((acc, fn) => fn(acc), input);

Const addOne = x => x + 1;

Const triple = x => x * 3;

Const tripleThenAddOne = compose(addOne, triple);

Console.log(tripleThenAddOne(4)); // 13

Complex Real-Life Scenarios

16. Dynamic Function Generator

Function createMathFunction(operation) {

Return (a, b) => {

Switch (operation) {

Case “add”:
Return a + b;

Case “subtract”:

Return a – b;

Case “multiply”:

Return a * b;

Case “divide”:

Return a / b;

};

Const adder = createMathFunction(“add”);

Console.log(adder(10, 5)); // 15

17. Recursive Sum of Array

Function sumArray(arr) {

If (arr.length === 0) return 0;

Return arr[0] + sumArray(arr.slice(1));

Console.log(sumArray([1, 2, 3, 4])); // 10

18. Find All Permutations of a String


Function permutations(str) {

If (str.length <= 1) return [str];

Let result = [];

For (let I = 0; I < str.length; i++) {

Let char = str[i];

Let remaining = str.slice(0, i) + str.slice(I + 1);

For (let perm of permutations(remaining)) {

Result.push(char + perm);

Return result;

Console.log(permutations(“abc”)); // [“abc”, “acb”, “bac”, “bca”, “cab”, “cba”]

19. Lazy Evaluation with Closures

Function lazyAdd(a) {

Return b => a + b;

Const add5 = lazyAdd(5);

Console.log(add5(10)); // 15

20. Implement a Retry Mechanism


Function retry(func, retries) {

Return async function (…args) {

Let attempts = 0;

While (attempts < retries) {

Try {

Return await func(…args);

} catch (error) {

Attempts++;

If (attempts === retries) throw error;

};

Const unreliableFunc = async () => {

If (Math.random() < 0.5) throw new Error(“Failed!”);

Return “Success!”;

};

Const retryUnreliable = retry(unreliableFunc, 3);

retryUnreliable().then(console.log).catch(console.error);
How are these examples? Would you like to explore real-world applications, or should I
explain specific advanced topics further?

Great! Let’s move on to the next topic: DOM Manipulation. This involves interacting with the
HTML structure of a webpage using JavaScript to create dynamic and interactive websites.
I’ll give you real-life examples for each concept, starting from basic to advanced.

DOM Manipulation in Real Life

Basic Examples

1. Change Text Content of an Element

Document.getElementById(“title”).innerText = “Welcome to JavaScript!”;

2. Change the Color of an Element

Document.getElementById(“header”).style.color = “blue”;

3. Hide an Element

Document.getElementById(“banner”).style.display = “none”;
4. Show an Element

Document.getElementById(“banner”).style.display = “block”;

5. Change the Background Color of the Page

Document.body.style.backgroundColor = “lightgreen”;

Intermediate Examples

6. Add a New List Item to a List

Function addItem() {

Let ul = document.getElementById(“myList”);

Let li = document.createElement(“li”);

li.innerText = “New Item”;

ul.appendChild(li);

7. Change Image Source


Document.getElementById(“image”).src = “new-image.jpg”;

8. Toggle a Class on an Element

Document.getElementById(“button”).addEventListener(“click”, function() {

Document.getElementById(“content”).classList.toggle(“active”);

});

9. Add a New Table Row

Function addRow() {

Let table = document.getElementById(“myTable”);

Let row = table.insertRow();

Let cell1 = row.insertCell(0);

Let cell2 = row.insertCell(1);

Cell1.innerText = “New Row”;

Cell2.innerText = “New Data”;

10. Set an Attribute of an Element


Document.getElementById(“myImage”).setAttribute(“alt”, “A beautiful image”);

Advanced Examples

11. Create a Modal Popup

Function openModal() {

Document.getElementById(“modal”).style.display = “block”;

Function closeModal() {

Document.getElementById(“modal”).style.display = “none”;

12. Drag and Drop Functionality

Function allowDrop(event) {

Event.preventDefault();

Function drag(event) {
Event.dataTransfer.setData(“text”, event.target.id);

Function drop(event) {

Event.preventDefault();

Let data = event.dataTransfer.getData(“text”);

Event.target.appendChild(document.getElementById(data));

13. Create a Dynamic Form

Function createForm() {

Let form = document.createElement(“form”);

Let input = document.createElement(“input”);

Input.type = “text”;

Input.placeholder = “Enter your name”;

Let button = document.createElement(“button”);

Button.innerText = “Submit”;

Form.appendChild(input);

Form.appendChild(button);

Document.body.appendChild(form);

14. Real-Time Search Filter


Function filterList() {

Let query = document.getElementById(“search”).value.toLowerCase();

Let items = document.querySelectorAll(“.list-item”);

Items.forEach(item => {

Item.style.display = item.innerText.toLowerCase().includes(query) ? “block” : “none”;

});

15. Animate an Element (e.g., Move a Box)

Function moveElement() {

Let elem = document.getElementById(“box”);

Let pos = 0;

Let interval = setInterval(() => {

If (pos === 350) clearInterval(interval);

Pos++;

Elem.style.left = pos + “px”;

}, 5);

}
More Complex Real-Life Scenarios

16. Countdown Timer

Function startCountdown() {

Let counter = 10;

Let interval = setInterval(() => {

Document.getElementById(“timer”).innerText = counter;

Counter--;

If (counter < 0) {

clearInterval(interval);

document.getElementById(“timer”).innerText = “Time’s up!”;

}, 1000);

17. Toggle Dark Mode

Function toggleDarkMode() {

Document.body.classList.toggle(“dark-mode”);

}
18. Create a To-Do List with Add and Delete Options

Function addTodo() {

Let todo = document.getElementById(“todoInput”).value;

Let ul = document.getElementById(“todoList”);

Let li = document.createElement(“li”);

li.innerText = todo;

let deleteBtn = document.createElement(“button”);

deleteBtn.innerText = “Delete”;

deleteBtn.onclick = function() {

ul.removeChild(li);

};

li.appendChild(deleteBtn);

ul.appendChild(li);

19. Change Content Dynamically Based on User Input

Document.getElementById(“nameInput”).addEventListener(“input”, function() {

Document.getElementById(“greeting”).innerText = `Hello, ${this.value}!`;

});
20. Create an Image Gallery with Lightbox Effect

Function openLightbox(imageSrc) {

Let lightbox = document.getElementById(“lightbox”);

Lightbox.style.display = “block”;

Lightbox.querySelector(“img”).src = imageSrc;

Function closeLightbox() {

Document.getElementById(“lightbox”).style.display = “none”;

Summary of Key DOM Manipulation Techniques

1. Selecting Elements: Use getElementById, getElementsByClassName,


querySelector, etc., to target elements in the DOM.

2. Changing Content: Use .innerText, .innerHTML, .textContent to modify the text or


HTML inside an element.

3. Styling Elements: Use .style to change the CSS properties of an element


dynamically.
4. Creating and Removing Elements: Use .createElement(), .appendChild(), and
.removeChild() to add or remove elements from the DOM.

5. Event Listeners: Use .addEventListener() to handle events like clicks, form


submissions, etc.

6. Classes and Attributes: Use .classList.add(), .classList.remove(), .setAttribute(), and


.getAttribute() to manipulate classes and attributes.

These examples should give you a solid understanding of DOM manipulation and how to
apply it in real-world projects. Would you like to dive deeper into any specific topic or move
on to the next one?

Great, Abhi! Let’s dive deeper into DOM manipulation and explore advanced concepts and
techniques. I’ll provide more in-depth explanations, real-life examples, and some best
practices.

Deep Dive into DOM Manipulation


1. Selecting Elements in the DOM

Selecting elements is the first step in manipulating the DOM. There are several ways to
target elements based on their ID, class, tag name, or attributes.

getElementById(): Selects an element by its ID.

Let element = document.getElementById(“myElement”);

getElementsByClassName(): Selects elements by their class name (returns a live


HTMLCollection).

Let elements = document.getElementsByClassName(“myClass”);

getElementsByTagName(): Selects elements by their tag name (returns a live


HTMLCollection).

Let divs = document.getElementsByTagName(“div”);

querySelector(): Selects the first element that matches a CSS selector.

Let firstDiv = document.querySelector(“div”);

querySelectorAll(): Selects all elements that match a CSS selector (returns a static
NodeList).

Let allDivs = document.querySelectorAll(“div”);


Real-Life Example: Selecting Multiple Elements

If you want to change the background color of all paragraphs:

Let paragraphs = document.querySelectorAll(“p”);

Paragraphs.forEach(paragraph => {

Paragraph.style.backgroundColor = “lightblue”;

});

2. Changing Content and Attributes

innerText: Sets or gets the text content of an element.

Let title = document.getElementById(“title”);

Title.innerText = “New Title”;

innerHTML: Sets or gets the HTML content of an element.

Let content = document.getElementById(“content”);

Content.innerHTML = “<h2>New Content</h2>”;

setAttribute(): Sets an attribute value (e.g., for images, links, etc.).


let img = document.getElementById(“image”);

img.setAttribute(“src”, “new-image.jpg”);

getAttribute(): Gets the value of an attribute.

Let link = document.getElementById(“myLink”);

Let href = link.getAttribute(“href”);

Console.log(href);

Real-Life Example: Change Image Source Dynamically

Let’s say you have an image gallery and want to change the image source dynamically
when a user clicks on a thumbnail:

Let thumbnails = document.querySelectorAll(“.thumbnail”);

Thumbnails.forEach(thumbnail => {

Thumbnail.addEventListener(“click”, function() {

Let mainImage = document.getElementById(“mainImage”);

mainImage.src = this.src; // Change the main image to the clicked thumbnail

});

});
3. Manipulating Styles Dynamically

Style property: Directly modifies the inline style of an element.

Let box = document.getElementById(“box”);

Box.style.backgroundColor = “yellow”;

Box.style.width = “200px”;

classList: Adds, removes, or toggles classes on an element.

Let box = document.getElementById(“box”);

Box.classList.add(“highlight”); // Adds a class

Box.classList.remove(“highlight”); // Removes a class

Box.classList.toggle(“highlight”); // Toggles the class

classList.contains(): Checks if an element has a specific class.

If (box.classList.contains(“highlight”)) {

Console.log(“Box is highlighted”);

Real-Life Example: Toggle Dark Mode

You can toggle between light and dark mode by adding/removing a class on the body
element:
Let darkModeButton = document.getElementById(“darkModeButton”);

darkModeButton.addEventListener(“click”, function() {

document.body.classList.toggle(“dark-mode”);

});

CSS:

.dark-mode {

Background-color: black;

Color: white;

4. Creating and Removing Elements

createElement(): Creates a new HTML element.

Let newDiv = document.createElement(“div”);

newDiv.innerText = “This is a new div!”;

document.body.appendChild(newDiv); // Adds the new div to the body

removeChild(): Removes an element from its parent.

Let parent = document.getElementById(“parent”);


Let child = document.getElementById(“child”);

Parent.removeChild(child);

appendChild(): Appends a child element to a parent.

Let parent = document.getElementById(“parent”);

Parent.appendChild(newDiv);

insertBefore(): Inserts a new element before an existing child.

Let parent = document.getElementById(“parent”);

Let newDiv = document.createElement(“div”);

Let existingDiv = document.getElementById(“existing”);

Parent.insertBefore(newDiv, existingDiv);

Real-Life Example: Dynamic To-Do List

You can dynamically add tasks to a to-do list:

Function addTask() {

Let taskInput = document.getElementById(“taskInput”);

Let taskList = document.getElementById(“taskList”);

Let newTask = document.createElement(“li”);

newTask.innerText = taskInput.value;

taskList.appendChild(newTask);
taskInput.value = “”; // Clear input field

5. Event Handling

addEventListener(): Attaches an event listener to an element.

Let button = document.getElementById(“button”);

Button.addEventListener(“click”, function() {

Alert(“Button clicked!”);

});

Event Delegation: Attaching a single event listener to a parent element to handle events for
multiple child elements.

Let list = document.getElementById(“list”);

List.addEventListener(“click”, function(event) {

If (event.target && event.target.matches(“li.item”)) {

Console.log(“Item clicked: “ + event.target.innerText);

});

Real-Life Example: Form Validation


You can validate form inputs dynamically using event listeners:

Let form = document.getElementById(“myForm”);

Form.addEventListener(“submit”, function(event) {

Let email = document.getElementById(“email”).value;

If (!email.includes(“@”)) {

Alert(“Please enter a valid email address”);

Event.preventDefault(); // Prevent form submission

});

6. Animations and Transitions

CSS Transitions: Smoothly transition between different styles.

#box {

Width: 100px;

Height: 100px;

Background-color: red;

Transition: all 0.5s ease;

#box:hover {
Width: 200px;

Background-color: green;

JavaScript Animations: You can use JavaScript to animate elements.

Function moveBox() {

Let box = document.getElementById(“box”);

Let position = 0;

Let interval = setInterval(function() {

If (position >= 200) {

clearInterval(interval);

} else {

Position++;

Box.style.left = position + “px”;

}, 5);

Best Practices for DOM Manipulation

1. Minimize DOM Access: Accessing the DOM is expensive. Cache references to DOM
elements in variables when possible.
Let button = document.getElementById(“button”);

Button.addEventListener(“click”, function() {

// Handle button click

});

2. Avoid Inline JavaScript: Keep JavaScript separate from HTML. Use


addEventListener() for event handling.

3. Use Event Delegation: For handling multiple child elements, delegate events to a
common parent to reduce the number of event listeners.

4. Avoid Reflow and Repaint: Changing multiple styles or attributes in one go will
trigger reflows and repaints, which can affect performance. Batch DOM updates.

5. Use requestAnimationFrame() for Smooth Animations: For smoother animations,


use requestAnimationFrame() instead of setInterval() or setTimeout().

Summary
DOM manipulation allows you to interact with HTML and CSS dynamically.

You can select, modify, create, and remove elements, as well as handle events.

Advanced techniques include event delegation, animations, and best practices for
performance optimization.

Would you like to explore further advanced topics like fetching data with APIs, or working
with local storage?

Sure, Abhi! Let’s move on to APIs (Application Programming Interfaces), a crucial topic for
modern web development. APIs allow different software systems to communicate with
each other. We’ll cover basic to advanced concepts of APIs, using real-life examples and
practical use cases.

What is an API?

An API is like a waiter at a restaurant. You (the client) tell the waiter (the API) what you want
from the kitchen (the server), and the waiter brings you the food (the data). The kitchen
doesn’t know who you are, and you don’t know how the kitchen works. You just interact
with the waiter (the API), and the waiter gives you what you need.

Basic Concepts

1. API Request: When you send a request to an API to fetch or send data.
2. API Response: The data you get back from the API after making a request.

Basic Example: Making an API Request

Example: Fetching Data from a Public API

Let’s say you want to get some data from a public API, like the JSONPlaceholder API, which
provides fake data for testing.

Fetch(‘https://jsonplaceholder.typicode.com/posts’)

.then(response => response.json()) // Convert the response to JSON

.then(data => console.log(data)) // Log the data to the console

.catch(error => console.log(‘Error:’, error)); // Handle any errors

Real-Life Example: Fetching Weather Data

Imagine you want to display the current weather for a city. You can use a weather API like
OpenWeatherMap to get the weather data.

Fetch(‘https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_API_K
EY’)
.then(response => response.json())

.then(data => {

Console.log(`Weather in London: ${data.weather[0].description}`);

})

.catch(error => console.log(‘Error:’, error));

Intermediate Concepts

Sending Data to an API (POST Request)

Sometimes, you may need to send data to an API. For example, submitting a form on a
website.

Fetch(‘https://jsonplaceholder.typicode.com/posts’, {

Method: ‘POST’, // Specify the request method

Headers: {

‘Content-Type’: ‘application/json’ // Set the content type to JSON

},

Body: JSON.stringify({

Title: ‘New Post’,

Body: ‘This is the content of the new post.’,

userId: 1

})

})
.then(response => response.json())

.then(data => console.log(data))

.catch(error => console.log(‘Error:’, error));

Real-Life Example: User Registration

When a user registers on a website, you send their information to the server via an API. For
example:

Fetch(‘https://example.com/api/register’, {

Method: ‘POST’,

Headers: {

‘Content-Type’: ‘application/json’

},

Body: JSON.stringify({

Username: ‘Abhi’,

Email: ‘abhi@example.com’,

Password: ‘password123’

})

})

.then(response => response.json())

.then(data => console.log(‘Registration Successful:’, data))

.catch(error => console.log(‘Error:’, error));


Advanced Concepts

Handling Errors with APIs

APIs may return errors, and it’s essential to handle them gracefully. You can check the
status of the response and act accordingly.

Fetch(‘https://jsonplaceholder.typicode.com/posts/1’)

.then(response => {

If (!response.ok) {

Throw new Error(‘Network response was not ok’);

Return response.json();

})

.then(data => console.log(data))

.catch(error => console.log(‘Error:’, error));

Real-Life Example: Handling Form Submission Failures

Imagine you have a form that submits data to an API, and you need to handle errors such as
invalid input or server downtime.

Fetch(‘https://example.com/api/submit’, {

Method: ‘POST’,

Headers: {

‘Content-Type’: ‘application/json’

},
Body: JSON.stringify({

Name: ‘Abhi’,

Email: ‘abhi@example.com’

})

})

.then(response => {

If (!response.ok) {

Throw new Error(‘Form submission failed. Please try again.’);

Return response.json();

})

.then(data => console.log(‘Form submitted successfully:’, data))

.catch(error => alert(error.message)); // Display error to the user

Advanced API Concepts

Authentication with APIs (API Keys)

Many APIs require authentication, usually through an API key. This is like a password that
allows you to access the API.

Fetch(‘https://api.example.com/data?apiKey=YOUR_API_KEY’)

.then(response => response.json())

.then(data => console.log(data))


.catch(error => console.log(‘Error:’, error));

Real-Life Example: Secure API Access

When building a website that fetches sensitive data, you need to securely authenticate
with the API using an API key. You can store the key in an environment variable or a secure
location on the server.

Const apiKey = process.env.API_KEY; // Store the API key securely

Fetch(`https://secureapi.com/data?apiKey=${apiKey}`)

.then(response => response.json())

.then(data => console.log(data))

.catch(error => console.log(‘Error:’, error));

How to Use APIs in Real-Life Projects

1. Weather Application

A weather app that fetches real-time weather data from an API like OpenWeatherMap. You
can display the weather based on the user’s location or a searched city.

Function getWeather(city) {
Fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=YOUR_API_KE
Y`)

.then(response => response.json())

.then(data => {

Console.log(`Weather in ${city}: ${data.weather[0].description}`);

})

.catch(error => console.log(‘Error:’, error));

getWeather(“New York”);

2. To-Do List App with API

In a To-Do List app, you can store tasks on the server using an API. You can use GET to fetch
tasks and POST to add new ones.

// Fetch tasks from the server

Fetch(‘https://jsonplaceholder.typicode.com/todos’)

.then(response => response.json())

.then(data => {

Data.forEach(task => {

Console.log(task.title);

});

});

// Add a new task to the server


Function addTask(task) {

Fetch(‘https://jsonplaceholder.typicode.com/todos’, {

Method: ‘POST’,

Headers: {

‘Content-Type’: ‘application/json’

},

Body: JSON.stringify({

Title: task,

Completed: false

})

})

.then(response => response.json())

.then(data => console.log(‘Task added:’, data))

.catch(error => console.log(‘Error:’, error));

3. Social Media App Integration

You can integrate APIs from social media platforms like Twitter, Facebook, or Instagram to
fetch user data, posts, or images. For example, using Twitter’s API to fetch the latest
tweets.

Fetch(‘https://api.twitter.com/2/tweets?ids=USER_ID’, {

Headers: {

‘Authorization’: ‘Bearer YOUR_ACCESS_TOKEN’

})
.then(response => response.json())

.then(data => console.log(data))

.catch(error => console.log(‘Error:’, error));

Best Practices for Using APIs

1. Error Handling: Always check for errors and handle them appropriately, as API
requests can fail due to network issues or incorrect data.

2. Security: Never expose sensitive information like API keys in the frontend code. Use
environment variables or server-side authentication.

3. Rate Limiting: Many APIs have rate limits. Be mindful of how often you make
requests to avoid hitting those limits.

4. Caching: Cache responses when possible to reduce the number of API calls and
improve performance.

5. Use async/await: For better readability and handling of asynchronous code, use
async/await instead of .then().
Summary

APIs allow communication between different software systems, enabling data sharing and
interaction.

Fetching data from APIs is done using methods like fetch(), and sending data is done using
methods like POST.

APIs are used in real-life projects like weather apps, to-do lists, and social media
integrations.

Always handle errors, authentication, and security when working with APIs.

Would you like to explore more about working with APIs or any specific project examples?
Let me know!

Absolutely, Abhi! Let’s dive deeper into APIs with more detailed concepts and real-life
examples. I’ll break it down from basic to advanced, covering a variety of use cases to help
you understand how to integrate APIs into your projects.
1. What is an API?

An API (Application Programming Interface) is a set of rules that allows different software
applications to communicate with each other. It’s like a bridge that lets two systems talk to
each other. APIs are used for everything, from fetching weather data to posting tweets.

Real-Life Analogy:

API as a Waiter: Imagine you’re at a restaurant. You (the client) ask the waiter (the API) for
food (data). The waiter goes to the kitchen (the server), gets the food (data), and brings it
back to you. You don’t know how the kitchen works, and the kitchen doesn’t know who you
are. You only interact with the waiter (API).

2. Making API Requests (GET and POST)

APIs typically offer two types of requests:

GET: Used to fetch data.

POST: Used to send data.

Basic Example: GET Request


Fetching data from a public API (e.g., JSONPlaceholder):

Fetch(‘https://jsonplaceholder.typicode.com/posts’) // GET request

.then(response => response.json()) // Parse the response to JSON

.then(data => console.log(data)) // Log the data

.catch(error => console.log(‘Error:’, error)); // Handle errors

Real-Life Example: Fetching Weather Data

Using the OpenWeatherMap API to fetch weather data for a city:

Fetch(‘https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_API_K
EY’)

.then(response => response.json()) // Convert response to JSON

.then(data => {

Console.log(`Weather in London: ${data.weather[0].description}`);

})

.catch(error => console.log(‘Error:’, error)); // Handle errors

In this example:

GET request is used to fetch weather data.

The API returns a JSON object with the weather information.


Basic Example: POST Request

Sending data to an API using a POST request:

Fetch(‘https://jsonplaceholder.typicode.com/posts’, {

Method: ‘POST’, // Specify POST method

Headers: {

‘Content-Type’: ‘application/json’ // Specify content type

},

Body: JSON.stringify({

Title: ‘New Post’,

Body: ‘This is a new post.’,

userId: 1

})

})

.then(response => response.json()) // Parse the response to JSON

.then(data => console.log(data)) // Log the data

.catch(error => console.log(‘Error:’, error)); // Handle errors

In this example:

POST request is used to send new data (a post) to the server.

The API returns the created post in the response.


3. Advanced Concepts: Authentication

Many APIs require authentication to access their data. This is typically done via API keys or
OAuth tokens.

API Key Authentication Example

You can authenticate API requests using an API key. For example, using the
OpenWeatherMap API:

Fetch(‘https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_API_K
EY’)

.then(response => response.json())

.then(data => {

Console.log(`Weather in London: ${data.weather[0].description}`);

})

.catch(error => console.log(‘Error:’, error)); // Handle errors

In this example:

Replace YOUR_API_KEY with your actual API key.

The API key is sent in the request URL as a query parameter.


4. Working with JSON Data

APIs often return data in JSON (JavaScript Object Notation) format. JSON is a lightweight
data format that’s easy to read and write.

Example: Parsing JSON Response

Fetch(‘https://jsonplaceholder.typicode.com/posts’)

.then(response => response.json()) // Parse the JSON response

.then(data => {

Console.log(data); // Log the data

Console.log(data[0].title); // Access specific data (e.g., title of the first post)

})

.catch(error => console.log(‘Error:’, error)); // Handle errors

Real-Life Example: Displaying Data in a Webpage

Imagine you are building a blog app. You can fetch posts from an API and display them on
your webpage:

Fetch(‘https://jsonplaceholder.typicode.com/posts’)

.then(response => response.json()) // Parse the JSON response

.then(data => {

Const postsContainer = document.getElementById(‘posts’);


Data.forEach(post => {

Const postElement = document.createElement(‘div’);

postElement.classList.add(‘post’);

postElement.innerHTML = `<h3>${post.title}</h3><p>${post.body}</p>`;

postsContainer.appendChild(postElement);

});

})

.catch(error => console.log(‘Error:’, error)); // Handle errors

In this example:

We fetch posts from the API and display them on the webpage inside a div with the ID
posts.

5. Handling Errors in API Requests

APIs can fail for various reasons (e.g., server down, invalid request). It’s important to handle
these errors gracefully.

Example: Handling HTTP Errors

Fetch(‘https://jsonplaceholder.typicode.com/posts/1000’) // Invalid post ID

.then(response => {
If (!response.ok) { // Check if the response status is OK

Throw new Error(‘Network response was not ok’);

Return response.json();

})

.then(data => console.log(data))

.catch(error => console.log(‘Error:’, error)); // Handle errors

In this example:

If the response status is not OK (e.g., 404), an error is thrown and caught in the .catch()
block.

6. Using APIs in Real-Life Projects

Example 1: Weather App

You can use an API like OpenWeatherMap to create a weather app that shows the current
weather of a city.

Function getWeather(city) {

Fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=YOUR_API_KE
Y`)
.then(response => response.json())

.then(data => {

Console.log(`Weather in ${city}: ${data.weather[0].description}`);

Document.getElementById(‘weather’).innerText = `The weather in ${city} is


${data.weather[0].description}`;

})

.catch(error => console.log(‘Error:’, error));

getWeather(“New York”);

In this example:

The function getWeather() takes a city name, fetches weather data, and displays it on the
webpage.

Example 2: To-Do List with API Integration

You can create a To-Do list app where tasks are fetched from an API and added to the list.

// Fetch tasks from the API

Fetch(‘https://jsonplaceholder.typicode.com/todos’)

.then(response => response.json())

.then(data => {

Const taskList = document.getElementById(‘task-list’);

Data.forEach(task => {
Const taskItem = document.createElement(‘li’);

taskItem.innerText = task.title;

taskList.appendChild(taskItem);

});

})

.catch(error => console.log(‘Error:’, error));

// Add a new task to the API

Function addTask(task) {

Fetch(‘https://jsonplaceholder.typicode.com/todos’, {

Method: ‘POST’,

Headers: {

‘Content-Type’: ‘application/json’,

},

Body: JSON.stringify({

Title: task,

Completed: false,

}),

})

.then(response => response.json())

.then(data => console.log(‘New Task Added:’, data))

.catch(error => console.log(‘Error:’, error));

In this example:
GET request is used to fetch tasks from the API and display them.

POST request is used to add new tasks to the API.

Example 3: Social Media App Integration

You can integrate social media APIs like Twitter, Facebook, or Instagram to fetch posts,
images, or user data.

Fetch(‘https://api.twitter.com/2/tweets?ids=USER_ID’, {

Headers: {

‘Authorization’: ‘Bearer YOUR_ACCESS_TOKEN’,

},

})

.then(response => response.json())

.then(data => console.log(data))

.catch(error => console.log(‘Error:’, error));

In this example:

You authenticate using a Bearer token and fetch tweets from a user’s Twitter account.
7. Best Practices for Working with APIs

1. Always Handle Errors: Use .catch() to handle errors and provide feedback to the
user.

2. Use async/await: For better readability and easier handling of asynchronous code.

3. Cache Responses: Cache API responses to reduce the number of requests and
improve performance.

4. Limit API Calls: Some APIs have rate limits. Be mindful of how often you call the API.

5. Secure API Keys: Never expose sensitive information like API keys in your frontend
code. Store them securely on the server.

Summary

APIs allow communication between different systems and are essential for fetching and
sending data.
You can use GET and POST requests to interact with APIs.

APIs often return data in JSON format, which can be easily parsed and used in your
projects.

Authentication is required for many APIs, usually via API keys or OAuth tokens.

APIs are used in real-life projects like weather apps, to-do lists, and social media
integrations.

Would you like to explore any specific API integration, or do you have any questions about
the examples? Let me know!

Sure, Abhi! Let’s dive deeper into Object-Oriented Programming (OOP) concepts in
JavaScript and explore them with more detailed examples. We’ll go through classes,
inheritance, methods, constructors, prototypes, and encapsulation, which are the core
principles of OOP.

1. Classes and Objects

In JavaScript, classes are templates for creating objects. A class defines the structure and
behavior (methods) of objects, while an object is an instance of a class.
Example: Basic Class and Object

// Define a class

Class Car {

// Constructor method

Constructor(make, model, year) {

This.make = make;

This.model = model;

This.year = year;

// Method to display car info

displayInfo() {

console.log(`${this.year} ${this.make} ${this.model}`);

// Create an object (instance of the class)

Let myCar = new Car(‘Toyota’, ‘Corolla’, 2020);

myCar.displayInfo(); // Output: 2020 Toyota Corolla

In this example:

Car is a class that defines the structure (properties like make, model, year) and behavior
(displayInfo method) of the car.
myCar is an object (instance) of the Car class.

2. Constructors

A constructor is a special method used to create and initialize objects. The constructor is
called automatically when a new object is created.

Example: Constructor with Parameters

Class Person {

Constructor(name, age) {

This.name = name;

This.age = age;

Introduce() {

Console.log(`Hi, my name is ${this.name} and I am ${this.age} years old.`);

Let person1 = new Person(‘Abhi’, 22);

Person1.introduce(); // Output: Hi, my name is Abhi and I am 22 years old.


In this example:

The constructor method takes name and age as parameters and assigns them to the
object’s properties.

Introduce is a method that uses those properties to introduce the person.

3. Inheritance

Inheritance allows one class to inherit the properties and methods of another class. This
helps in creating a hierarchy of classes.

Example: Inheritance with extends

Class Animal {

Constructor(name) {

This.name = name;

Speak() {

Console.log(`${this.name} makes a sound.`);

}
Class Dog extends Animal {

Constructor(name, breed) {

Super(name); // Call the parent class constructor

This.breed = breed;

Speak() {

Console.log(`${this.name} barks.`);

Let dog = new Dog(‘Buddy’, ‘Golden Retriever’);

Dog.speak(); // Output: Buddy barks.

In this example:

The Dog class extends the Animal class.

The super(name) keyword is used to call the constructor of the parent class (Animal).

The Dog class overrides the speak() method of the Animal class.
4. Prototypes

In JavaScript, every object has a prototype. A prototype is an object from which other
objects inherit properties and methods. You can add methods and properties to the
prototype of a class.

Example: Adding Methods to Prototypes

Function Person(name, age) {

This.name = name;

This.age = age;

// Add a method to the prototype

Person.prototype.introduce = function() {

Console.log(`Hi, I am ${this.name} and I am ${this.age} years old.`);

};

Let person2 = new Person(‘John’, 30);

Person2.introduce(); // Output: Hi, I am John and I am 30 years old.

In this example:

We create a constructor function Person.

We add the introduce method to the prototype of Person, so all instances of Person can
use this method.
5. Encapsulation

Encapsulation is the concept of bundling the data (properties) and methods that operate
on the data into a single unit or class. It also restricts direct access to some of an object’s
components, which is typically done by using private properties and getter/setter methods.

Example: Encapsulation with Getter and Setter

Class Person {

Constructor(name, age) {

This._name = name; // Private property (conventionally)

This._age = age;

// Getter method

Get name() {

Return this._name;

// Setter method

Set name(newName) {

This._name = newName;
}

Get age() {

Return this._age;

Set age(newAge) {

If (newAge >= 0) {

This._age = newAge;

} else {

Console.log(“Age cannot be negative.”);

Let person3 = new Person(‘Alice’, 25);

Console.log(person3.name); // Output: Alice

Person3.age = 30; // Setter method

Console.log(person3.age); // Output: 30

Person3.age = -5; // Invalid age

In this example:

Private properties are indicated by the underscore (_name, _age), and getter/setter
methods are used to access and modify these properties.
The setter for age ensures that the age cannot be set to a negative value.

6. Method Overloading

JavaScript does not support method overloading (having multiple methods with the same
name but different parameters). However, you can achieve similar functionality by
checking the number of arguments passed to the method.

Example: Simulating Method Overloading

Class Calculator {

Add(a, b) {

If (b === undefined) {

Return a + a; // If only one argument, double it

Return a + b; // If two arguments, add them

Let calc = new Calculator();

Console.log(calc.add(5)); // Output: 10 (5 + 5)

Console.log(calc.add(5, 10)); // Output: 15 (5 + 10)


In this example:

The add method behaves differently depending on the number of arguments passed to it,
simulating method overloading.

7. Static Methods

A static method is a method that belongs to the class itself, rather than instances of the
class. You can call static methods directly on the class.

Example: Static Method

Class MathUtils {

Static square(x) {

Return x * x;

Console.log(MathUtils.square(5)); // Output: 25

In this example:

The square method is static, so it can be called directly on the MathUtils class without
creating an instance.
8. Abstract Classes (Simulated)

JavaScript does not have abstract classes like other languages (e.g., Java, C#), but you can
simulate them by throwing errors in methods that are meant to be overridden by
subclasses.

Example: Simulating an Abstract Class

Class Shape {

Constructor() {

If (this.constructor === Shape) {

Throw new Error(“Cannot instantiate abstract class”);

Area() {

Throw new Error(“Method ‘area()’ must be implemented.”);

Class Rectangle extends Shape {

Constructor(width, height) {
Super();

This.width = width;

This.height = height;

Area() {

Return this.width * this.height;

Let rectangle = new Rectangle(10, 5);

Console.log(rectangle.area()); // Output: 50

In this example:

The Shape class is abstract because it throws an error if you try to instantiate it directly or if
the area() method is not implemented.

Summary of OOP Concepts in JavaScript

1. Classes: Templates for creating objects.


2. Objects: Instances of classes.

3. Constructors: Special methods to initialize objects.

4. Inheritance: Allowing one class to inherit properties and methods from another.

5. Prototypes: Objects from which other objects inherit properties and methods.

6. Encapsulation: Bundling data and methods, and controlling access to data using
getter/setter methods.

7. Static Methods: Methods that belong to the class itself, not instances.

8. Abstract Classes: Simulated abstract classes to enforce method implementation in


subclasses.
This should give you a deeper understanding of OOP in JavaScript! Would you like to dive
into more examples or real-world use cases of OOP? Let me know if you want to continue
exploring!

Absolutely, Abhi! Let’s explore real-world use cases of Object-Oriented Programming (OOP)
in JavaScript. OOP is widely used in modern web development, and understanding its
application in real-world projects will help you apply these concepts more effectively. I’ll
cover some practical examples of how OOP can be used in various domains like web
development, game development, and e-commerce applications.

1. E-Commerce Website (Product Management)

In an e-commerce website, you can model products, customers, and orders using OOP
concepts like classes, inheritance, and encapsulation.

Example: Product and Order Classes

// Base class for Product

Class Product {

Constructor(name, price, category) {

This.name = name;

This.price = price;

This.category = category;

displayProductInfo() {

console.log(`Product: ${this.name}, Price: $${this.price}, Category: ${this.category}`);


}

// Derived class for DiscountedProduct

Class DiscountedProduct extends Product {

Constructor(name, price, category, discount) {

Super(name, price, category); // Call the parent class constructor

This.discount = discount;

// Override the displayProductInfo method to include discount

displayProductInfo() {

console.log(`${this.name} – Price: $${this.price} (Discount: ${this.discount}%)`);

// Method to calculate the final price after discount

calculateDiscountedPrice() {

return this.price – (this.price * (this.discount / 100));

// Example usage

Let product1 = new Product(‘Laptop’, 1200, ‘Electronics’);

Product1.displayProductInfo(); // Output: Product: Laptop, Price: $1200, Category:


Electronics
Let discountedProduct = new DiscountedProduct(‘Smartphone’, 800, ‘Electronics’, 10);

discountedProduct.displayProductInfo(); // Output: Smartphone – Price: $800 (Discount:


10%)

console.log(‘Discounted Price:’, discountedProduct.calculateDiscountedPrice()); //


Output: Discounted Price: 720

In this example:

Product class represents a generic product.

DiscountedProduct class extends Product to add a discount feature.

We use inheritance to avoid repeating code and keep the logic clean and reusable.

2. Banking System (Account Management)

In a banking system, you can use OOP to manage different types of accounts and
transactions. You can create a base class for a general BankAccount and then extend it for
SavingsAccount and CheckingAccount.

Example: Bank Account System

// Base class for Bank Account

Class BankAccount {
Constructor(accountHolder, balance) {

This.accountHolder = accountHolder;

This.balance = balance;

Deposit(amount) {

This.balance += amount;

Console.log(`Deposited $${amount}. New balance: $${this.balance}`);

Withdraw(amount) {

If (this.balance >= amount) {

This.balance -= amount;

Console.log(`Withdrew $${amount}. New balance: $${this.balance}`);

} else {

Console.log(“Insufficient funds”);

displayBalance() {

console.log(`Account balance: $${this.balance}`);

// Derived class for Savings Account

Class SavingsAccount extends BankAccount {


Constructor(accountHolder, balance, interestRate) {

Super(accountHolder, balance);

This.interestRate = interestRate;

// Method to calculate interest

applyInterest() {

const interest = this.balance * (this.interestRate / 100);

this.balance += interest;

console.log(`Interest applied: $${interest}. New balance: $${this.balance}`);

// Derived class for Checking Account

Class CheckingAccount extends BankAccount {

Constructor(accountHolder, balance, overdraftLimit) {

Super(accountHolder, balance);

This.overdraftLimit = overdraftLimit;

// Override withdraw method to allow overdraft

Withdraw(amount) {

If (this.balance + this.overdraftLimit >= amount) {

This.balance -= amount;

Console.log(`Withdrew $${amount}. New balance: $${this.balance}`);

} else {
Console.log(“Overdraft limit exceeded”);

// Example usage

Let savings = new SavingsAccount(‘John Doe’, 1000, 5);

Savings.deposit(500); // Output: Deposited $500. New balance: $1500

Savings.applyInterest(); // Output: Interest applied: $75. New balance: $1575

Let checking = new CheckingAccount(‘Jane Doe’, 500, 200);

Checking.withdraw(600); // Output: Withdrew $600. New balance: -100

In this example:

BankAccount is the base class, and SavingsAccount and CheckingAccount extend it to add
more specific features like interest and overdraft.

We use method overriding in the withdraw method to allow overdrafts in the


CheckingAccount class.

3. Game Development (Character and Enemy)


In game development, you can use OOP to model different game entities like characters,
enemies, and items.

Example: Game Character and Enemy Classes

// Base class for Character

Class Character {

Constructor(name, health, attackPower) {

This.name = name;

This.health = health;

This.attackPower = attackPower;

Attack(target) {

Target.health -= this.attackPower;

Console.log(`${this.name} attacks ${target.name} for ${this.attackPower} damage.`);

isAlive() {

return this.health > 0;

// Derived class for Enemy

Class Enemy extends Character {

Constructor(name, health, attackPower, specialAbility) {


Super(name, health, attackPower);

This.specialAbility = specialAbility;

useSpecialAbility(target) {

console.log(`${this.name} uses ${this.specialAbility} on ${target.name}.`);

target.health -= 20; // Special ability causes extra damage

// Example usage

Let hero = new Character(‘Hero’, 100, 10);

Let villain = new Enemy(‘Villain’, 80, 12, ‘Fireball’);

Hero.attack(villain); // Output: Hero attacks Villain for 10 damage.

Villain.useSpecialAbility(hero); // Output: Villain uses Fireball on Hero.

In this example:

Character is the base class with basic attributes like health and attackPower.

Enemy extends Character and adds a special ability that can deal extra damage.
4. School Management System (Student and Teacher)

In a school management system, you can use OOP to model students, teachers, and
courses.

Example: School Management System

// Base class for Person

Class Person {

Constructor(name, age) {

This.name = name;

This.age = age;

Introduce() {

Console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);

// Derived class for Student

Class Student extends Person {

Constructor(name, age, grade) {

Super(name, age);

This.grade = grade;

}
Study() {

Console.log(`${this.name} is studying for the ${this.grade} grade.`);

// Derived class for Teacher

Class Teacher extends Person {

Constructor(name, age, subject) {

Super(name, age);

This.subject = subject;

Teach() {

Console.log(`${this.name} is teaching ${this.subject}.`);

// Example usage

Let student = new Student(‘Alice’, 16, ‘10 th’);

Student.introduce(); // Output: Hello, my name is Alice and I am 16 years old.

Student.study(); // Output: Alice is studying for the 10 th grade.

Let teacher = new Teacher(‘Mr. Smith’, 40, ‘Mathematics’);

Teacher.introduce(); // Output: Hello, my name is Mr. Smith and I am 40 years old.

Teacher.teach(); // Output: Mr. Smith is teaching Mathematics.


In this example:

Person is the base class with common attributes like name and age.

Student and Teacher classes inherit from Person and have additional specific properties
and methods.

5. Vehicle Management System

In a vehicle management system, you can model different types of vehicles, such as cars,
bikes, and trucks, using OOP principles.

Example: Vehicle Management System

// Base class for Vehicle

Class Vehicle {

Constructor(make, model, year) {

This.make = make;

This.model = model;

This.year = year;

displayInfo() {
console.log(`${this.year} ${this.make} ${this.model}`);

// Derived class for Car

Class Car extends Vehicle {

Constructor(make, model, year, doors) {

Super(make, model, year);

This.doors = doors;

displayCarInfo() {

this.displayInfo();

console.log(`Doors: ${this.doors}`);

// Derived class for Bike

Class Bike extends Vehicle {

Constructor(make, model, year, type) {

Super(make, model, year);

This.type = type;

displayBikeInfo() {

this.displayInfo();
console.log(`Type: ${this.type}`);

// Example usage

Let car = new Car(‘Toyota’, ‘Corolla’, 2020, 4);

Car.displayCarInfo(); // Output: 2020 Toyota Corolla | Doors: 4

Let bike = new Bike(‘Yamaha’, ‘FZ’, 2022, ‘Sport’);

Bike.displayBikeInfo(); // Output: 2022 Yamaha FZ | Type: Sport

In this example:

Vehicle is the base class with common properties like make, model, and year.

Car and Bike inherit from Vehicle and add additional properties and methods.

Summary of Real-World Use Cases

E-Commerce: Using classes to model products, orders, and discounts.

Banking: Managing accounts, transactions, and customer information using inheritance


and encapsulation.
Game Development: Modeling characters, enemies, and actions using OOP principles like
inheritance and polymorphism.

School Management: Modeling students, teachers, and courses using classes and
inheritance.

Vehicle Management: Managing different types of vehicles (cars, bikes) with shared
properties and specialized methods.

These examples should give you a good understanding of how OOP is used in real-world
projects. Would you like to explore more advanced OOP concepts, or should we dive into
another topic? Let me know!

Got it, Abhi! Let’s go through each of the remaining chapters in “JavaScript from Beginner to
Professional” with detailed explanations and real-life examples from basic to advanced. I’ll
provide you with 50-80 examples for each chapter, covering both basic and advanced
concepts, so you can get a solid understanding of each topic.

Chapter 7: Built-In JavaScript Methods

Introduction to Built-In Methods


JavaScript provides a variety of built-in methods that allow you to manipulate data types,
work with arrays, handle strings, and more. These methods save you time and effort, as you
don’t need to write common functionalities from scratch.

Basic Examples: Working with Numbers and Strings

1. parseInt(): Converts a string to an integer.

Let str = “123”;

Let num = parseInt(str);

Console.log(num); // Output: 123

2. parseFloat(): Converts a string to a floating-point number.

Let str = “123.45”;

Let num = parseFloat(str);

Console.log(num); // Output: 123.45

3. toString(): Converts a number to a string.

Let num = 123;

Let str = num.toString();


Console.log(str); // Output: “123”

4. isNaN(): Checks if a value is NaN (Not-a-Number).

Let num = “abc”;

Console.log(isNaN(num)); // Output: true

5. toFixed(): Rounds a number to a specified number of decimal places.

Let num = 123.4567;

Console.log(num.toFixed(2)); // Output: “123.46”

Working with Arrays

6. push(): Adds one or more elements to the end of an array.

Let arr = [1, 2, 3];

Arr.push(4);

Console.log(arr); // Output: [1, 2, 3, 4]


7. pop(): Removes the last element from an array.

Let arr = [1, 2, 3];

Arr.pop();

Console.log(arr); // Output: [1, 2]

8. shift(): Removes the first element from an array.

Let arr = [1, 2, 3];

Arr.shift();

Console.log(arr); // Output: [2, 3]

9. unshift(): Adds one or more elements to the beginning of an array.

Let arr = [1, 2, 3];

Arr.unshift(0);

Console.log(arr); // Output: [0, 1, 2, 3]

10. splice(): Adds or removes elements from an array at a specific index.

Let arr = [1, 2, 3, 4];

Arr.splice(2, 1, 5);
Console.log(arr); // Output: [1, 2, 5, 4]

String Methods

11. charAt(): Returns the character at a specified index.

Let str = “Hello”;

Console.log(str.charAt(1)); // Output: “e”

12. indexOf(): Returns the index of the first occurrence of a specified value.

Let str = “Hello”;

Console.log(str.indexOf(“e”)); // Output: 1

13. substring(): Extracts a substring from a string.

Let str = “Hello”;

Console.log(str.substring(1, 4)); // Output: “ell”


14. replace(): Replaces a specified value with another value.

Let str = “Hello World”;

Console.log(str.replace(“World”, “JavaScript”)); // Output: “Hello JavaScript”

15. split(): Splits a string into an array of substrings.

Let str = “apple,banana,cherry”;

Let arr = str.split(“,”);

Console.log(arr); // Output: [“apple”, “banana”, “cherry”]

Advanced Examples: JSON and Date Methods

16. JSON.stringify(): Converts a JavaScript object to a JSON string.

Let obj = { name: “John”, age: 30 };

Let jsonStr = JSON.stringify(obj);

Console.log(jsonStr); // Output: ‘{“name”:”John”,”age”:30}’

17. JSON.parse(): Converts a JSON string to a JavaScript object.


Let jsonStr = ‘{“name”:”John”,”age”:30}’;

Let obj = JSON.parse(jsonStr);

Console.log(obj); // Output: { name: ‘John’, age: 30 }

18. Date(): Returns the current date and time.

Let currentDate = new Date();

Console.log(currentDate); // Output: current date and time

19. getFullYear(): Returns the year of a date object.

Let date = new Date();

Console.log(date.getFullYear()); // Output: current year

20. setHours(): Sets the hours of a date object.

Let date = new Date();

Date.setHours(10);

Console.log(date.getHours()); // Output: 10
Working with Numbers

21. Math.random(): Generates a random number between 0 and 1.

Console.log(Math.random()); // Output: Random number between 0 and 1

22. Math.floor(): Rounds a number down to the nearest integer.

Console.log(Math.floor(4.7)); // Output: 4

23. Math.ceil(): Rounds a number up to the nearest integer.

Console.log(Math.ceil(4.3)); // Output: 5

24. Math.max(): Returns the largest of the numbers provided.

Console.log(Math.max(1, 2, 3, 4, 5)); // Output: 5

25. Math.min(): Returns the smallest of the numbers provided.


Console.log(Math.min(1, 2, 3, 4, 5)); // Output: 1

Real-Life Examples Using Built-In Methods

26. User Registration Validation: Use parseInt() and isNaN() to validate age input.

27. Shopping Cart: Use push() and pop() to manage items in a cart.

28. Currency Converter: Use toFixed() to round the conversion rate to two decimal
places.

29. Text Search: Use indexOf() and substring() to search and extract parts of text.

30. Form Data Submission: Use JSON.stringify() to send form data as JSON to a server.
Chapter 8: The Document Object Model (DOM)

Introduction to DOM

The DOM is a programming interface for web documents. It represents the page so that
programs can manipulate the structure, style, and content of a webpage.

Basic DOM Manipulation

1. Selecting Elements by ID

Let element = document.getElementById(‘myElement’);

Console.log(element);

2. Changing Text Content

Let element = document.getElementById(‘myElement’);

Element.innerText = ‘New Text Content’;

3. Changing Style
Let element = document.getElementById(‘myElement’);

Element.style.color = ‘blue’;

4. Creating New Elements

Let newDiv = document.createElement(‘div’);

newDiv.innerText = ‘Hello World!’;

document.body.appendChild(newDiv);

5. Removing an Element

Let element = document.getElementById(‘myElement’);

Element.remove();

Event Handling

6. Adding an Event Listener

Let button = document.getElementById(‘myButton’);

Button.addEventListener(‘click’, function() {
Alert(‘Button clicked!’);

});

7. Handling Form Submission

Let form = document.getElementById(‘myForm’);

Form.addEventListener(‘submit’, function(event) {

Event.preventDefault();

Console.log(‘Form submitted!’);

});

8. Mouse Hover Event

Let element = document.getElementById(‘myElement’);

Element.addEventListener(‘mouseover’, function() {

Element.style.backgroundColor = ‘yellow’;

});

9. Click Event

Let button = document.getElementById(‘myButton’);

Button.addEventListener(‘click’, function() {

Console.log(‘Button clicked’);
});

10. Keyboard Event

Let input = document.getElementById(‘myInput’);

Input.addEventListener(‘keydown’, function(event) {

Console.log(`Key pressed: ${event.key}`);

});

Advanced DOM Manipulation

11. Traversing the DOM

Let parent = document.getElementById(‘parent’);

Let child = parent.querySelector(‘.child’);

Console.log(child);

12. Modifying Multiple Elements

Let elements = document.querySelectorAll(‘.myClass’);


Elements.forEach(function(element) {

Element.style.color = ‘red’;

});

13. Adding and Removing Classes

Let element = document.getElementById(‘myElement’);

Element.classList.add(‘newClass’);

Element.classList.remove(‘oldClass’);

14. Creating and Inserting a Table

Let table = document.createElement(‘table’);

Let row = table.insertRow();

Let cell = row.insertCell(0);

Cell.innerText = ‘New Cell’;

Document.body.appendChild(table);

15. Dynamic Content Update

Let contentDiv = document.getElementById(‘content’);

contentDiv.innerHTML = ‘<h1>Updated Content</h1>’;

Chapter 9: Dynamic Element Manipulation Using the DOM

Manipulating Lists

16. Adding Items to a List

Let ul = document.getElementById(‘myList’);

Let li = document.createElement(‘li’);

li.innerText = ‘New Item’;

ul.appendChild(li);

17. Removing Items from a List


Let ul = document.getElementById(‘myList’);

Let firstItem = ul.firstChild;

Ul.removeChild(firstItem);

18. Updating List Item Text

Let ul = document.getElementById(‘myList’);

Let firstItem = ul.firstChild;

firstItem.innerText = ‘Updated Item’;

19. Sorting List Items

Let ul = document.getElementById(‘myList’);

Let items = Array.from(ul.children);

Items.sort((a, b) => a.innerText.localeCompare(b.innerText));

Items.forEach(item => ul.appendChild(item));

20. Toggling List Item Visibility

Let li = document.getElementById(‘myListItem’);

li.style.display = li.style.display === ‘none’ ? ‘block’ : ‘none’;

Chapter 10: Asynchronous JavaScript

Introduction to Asynchronous JavaScript

Asynchronous JavaScript allows you to perform tasks like fetching data, reading files, and
making network requests without blocking the execution of the rest of your code.

Basic Examples

1. Using setTimeout()

setTimeout(function() {
console.log(‘This is printed after 2 seconds’);

}, 2000);

2. Using setInterval()

Let interval = setInterval(function() {

Console.log(‘This is printed every 2 seconds’);

}, 2000);

3. Using Promise

Let promise = new Promise(function(resolve, reject) {

Let success = true;

If (success) {

Resolve(‘Task completed’);

} else {

Reject(‘Task failed’);

});

Promise.then(function(result) {

Console.log(result); // Output: Task completed

}).catch(function(error) {

Console.log(error); // Output: Task failed

});

4. Using async/await

Async function fetchData() {

Let response = await fetch(‘https://jsonplaceholder.typicode.com/posts’);

Let data = await response.json();

Console.log(data);

}
fetchData();

Summary of All Chapters

Chapter 7: Built-in methods like parseInt(), JSON.stringify(), and array methods help you
manipulate data effectively.

Chapter 8: DOM manipulation allows you to interact with HTML elements dynamically
using JavaScript.

Chapter 9: Dynamic element manipulation helps you add, remove, and update elements
on the webpage in real-time.

Chapter 10: Asynchronous JavaScript (using setTimeout(), Promises, and async/await) is


essential for non-blocking operations like fetching data from APIs.

Let me know if you’d like more detailed explanations or examples on any specific chapter!

Sure, Abhi! Let’s dive deeper into each chapter with more examples and detailed
explanations. I’ll break down the concepts and provide a wide range of examples for each
chapter, covering both basic and advanced topics. This will give you a solid understanding
of the concepts and how to use them in real-world scenarios.

Chapter 7: Built-In JavaScript Methods

JavaScript offers a wide range of built-in methods to work with numbers, strings, arrays,
objects, and more. These methods make your life easier by providing efficient ways to
manipulate and interact with data.

Basic Examples
1. parseInt(): Converts a string to an integer.

Let str = “123”;

Let num = parseInt(str);

Console.log(num); // Output: 123

2. parseFloat(): Converts a string to a floating-point number.

Let str = “123.45”;

Let num = parseFloat(str);

Console.log(num); // Output: 123.45

3. toString(): Converts a number to a string.

Let num = 123;

Let str = num.toString();

Console.log(str); // Output: “123”

4. isNaN(): Checks if a value is NaN (Not-a-Number).

Let num = “abc”;

Console.log(isNaN(num)); // Output: true

5. toFixed(): Rounds a number to a specified number of decimal places.

Let num = 123.4567;

Console.log(num.toFixed(2)); // Output: “123.46”

Working with Arrays

6. push(): Adds one or more elements to the end of an array.

Let arr = [1, 2, 3];

Arr.push(4);

Console.log(arr); // Output: [1, 2, 3, 4]

7. pop(): Removes the last element from an array.


Let arr = [1, 2, 3];

Arr.pop();

Console.log(arr); // Output: [1, 2]

8. shift(): Removes the first element from an array.

Let arr = [1, 2, 3];

Arr.shift();

Console.log(arr); // Output: [2, 3]

9. unshift(): Adds one or more elements to the beginning of an array.

Let arr = [1, 2, 3];

Arr.unshift(0);

Console.log(arr); // Output: [0, 1, 2, 3]

10. splice(): Adds or removes elements from an array at a specific index.

Let arr = [1, 2, 3, 4];

Arr.splice(2, 1, 5);

Console.log(arr); // Output: [1, 2, 5, 4]

String Methods

11. charAt(): Returns the character at a specified index.

Let str = “Hello”;

Console.log(str.charAt(1)); // Output: “e”

12. indexOf(): Returns the index of the first occurrence of a specified value.

Let str = “Hello”;

Console.log(str.indexOf(“e”)); // Output: 1

13. substring(): Extracts a substring from a string.

Let str = “Hello”;


Console.log(str.substring(1, 4)); // Output: “ell”

14. replace(): Replaces a specified value with another value.

Let str = “Hello World”;

Console.log(str.replace(“World”, “JavaScript”)); // Output: “Hello JavaScript”

15. split(): Splits a string into an array of substrings.

Let str = “apple,banana,cherry”;

Let arr = str.split(“,”);

Console.log(arr); // Output: [“apple”, “banana”, “cherry”]

Advanced Examples: JSON and Date Methods

16. JSON.stringify(): Converts a JavaScript object to a JSON string.

Let obj = { name: “John”, age: 30 };

Let jsonStr = JSON.stringify(obj);

Console.log(jsonStr); // Output: ‘{“name”:”John”,”age”:30}’

17. JSON.parse(): Converts a JSON string to a JavaScript object.

Let jsonStr = ‘{“name”:”John”,”age”:30}’;

Let obj = JSON.parse(jsonStr);

Console.log(obj); // Output: { name: ‘John’, age: 30 }

18. Date(): Returns the current date and time.

Let currentDate = new Date();

Console.log(currentDate); // Output: current date and time

19. getFullYear(): Returns the year of a date object.

Let date = new Date();

Console.log(date.getFullYear()); // Output: current year

20. setHours(): Sets the hours of a date object.


Let date = new Date();

Date.setHours(10);

Console.log(date.getHours()); // Output: 10

Real-Life Examples Using Built-In Methods

21. User Registration Validation: Use parseInt() and isNaN() to validate age input.
22. Shopping Cart: Use push() and pop() to manage items in a cart.
23. Currency Converter: Use toFixed() to round the conversion rate to two decimal
places.
24. Text Search: Use indexOf() and substring() to search and extract parts of text.
25. Form Data Submission: Use JSON.stringify() to send form data as JSON to a server.

Chapter 8: The Document Object Model (DOM)

The DOM is an interface for interacting with HTML and XML documents. It represents the
structure of the document as a tree of nodes, where each node is an object representing a
part of the page.

Basic DOM Manipulation

1. Selecting Elements by ID

Let element = document.getElementById(‘myElement’);

Console.log(element);

2. Changing Text Content

Let element = document.getElementById(‘myElement’);

Element.innerText = ‘New Text Content’;

3. Changing Style
Let element = document.getElementById(‘myElement’);

Element.style.color = ‘blue’;

4. Creating New Elements

Let newDiv = document.createElement(‘div’);

newDiv.innerText = ‘Hello World!’;

document.body.appendChild(newDiv);

5. Removing an Element

Let element = document.getElementById(‘myElement’);

Element.remove();

Event Handling

6. Adding an Event Listener

Let button = document.getElementById(‘myButton’);

Button.addEventListener(‘click’, function() {

Alert(‘Button clicked!’);

});

7. Handling Form Submission

Let form = document.getElementById(‘myForm’);

Form.addEventListener(‘submit’, function(event) {

Event.preventDefault();

Console.log(‘Form submitted!’);

});

8. Mouse Hover Event

Let element = document.getElementById(‘myElement’);

Element.addEventListener(‘mouseover’, function() {
Element.style.backgroundColor = ‘yellow’;

});

9. Click Event

Let button = document.getElementById(‘myButton’);

Button.addEventListener(‘click’, function() {

Console.log(‘Button clicked’);

});

10. Keyboard Event

Let input = document.getElementById(‘myInput’);

Input.addEventListener(‘keydown’, function(event) {

Console.log(`Key pressed: ${event.key}`);

});

Advanced DOM Manipulation

11. Traversing the DOM

Let parent = document.getElementById(‘parent’);

Let child = parent.querySelector(‘.child’);

Console.log(child);

12. Modifying Multiple Elements

Let elements = document.querySelectorAll(‘.myClass’);

Elements.forEach(function(element) {

Element.style.color = ‘red’;

});

13. Adding and Removing Classes

Let element = document.getElementById(‘myElement’);


Element.classList.add(‘newClass’);

Element.classList.remove(‘oldClass’);

14. Creating and Inserting a Table

Let table = document.createElement(‘table’);

Let row = table.insertRow();

Let cell = row.insertCell(0);

Cell.innerText = ‘New Cell’;

Document.body.appendChild(table);

15. Dynamic Content Update

Let contentDiv = document.getElementById(‘content’);

contentDiv.innerHTML = ‘<h1>Updated Content</h1>’;

Chapter 9: Dynamic Element Manipulation Using the DOM

Manipulating Lists

16. Adding Items to a List

Let ul = document.getElementById(‘myList’);

Let li = document.createElement(‘li’);

li.innerText = ‘New Item’;

ul.appendChild(li);

17. Removing Items from a List

Let ul = document.getElementById(‘myList’);

Let firstItem = ul.firstChild;

Ul.removeChild(firstItem);
18. Updating List Item Text

Let ul = document.getElementById(‘myList’);

Let firstItem = ul.firstChild;

firstItem.innerText = ‘Updated Item’;

19. Sorting List Items

Let ul = document.getElementById(‘myList’);

Let items = Array.from(ul.children);

Items.sort((a, b) => a.innerText.localeCompare(b.innerText));

Items.forEach(item => ul.appendChild(item));

20. Toggling List Item Visibility

Let li = document.getElementById(‘myListItem’);

li.style.display = li.style.display === ‘none’ ? ‘block’ : ‘none’;

Chapter 10: Asynchronous JavaScript

Introduction to Asynchronous JavaScript

Asynchronous JavaScript allows you to perform tasks like fetching data, reading files, and
making network requests without blocking the execution of the rest of your code.

Basic Examples

1. Using setTimeout()

setTimeout(function() {

console.log(‘This is printed after 2 seconds’);


}, 2000);

2. Using setInterval()

Let interval = setInterval(function() {

It looks like my response got cut off. Let me continue from where I left off and complete the
detailed explanation and examples for Chapter 10: Asynchronous JavaScript.

Chapter 10: Asynchronous JavaScript (Continued)

Asynchronous JavaScript allows you to handle tasks like API requests, file reading, and
delayed operations without blocking the execution of the rest of your code. This is essential
for modern web applications, where you need to handle user interactions and network
requests efficiently.

Basic Examples

1. Using setTimeout()

setTimeout() is used to execute a function after a specified delay.

setTimeout(function() {

console.log(‘This is printed after 2 seconds’);

}, 2000); // Output: This is printed after 2 seconds

In this example, the function inside setTimeout() is executed after 2 seconds, but it doesn’t
block the rest of the code from running.

2. Using setInterval()

setInterval() is used to execute a function repeatedly at specified intervals.

Let interval = setInterval(function() {

Console.log(‘This is printed every 2 seconds’);

}, 2000); // Output: This is printed every 2 seconds (repeatedly)


You can stop the interval using clearInterval():

clearInterval(interval);

3. Using Promise

A Promise is an object that represents the eventual completion (or failure) of an


asynchronous operation.

Let promise = new Promise(function(resolve, reject) {

Let success = true;

If (success) {

Resolve(‘Task completed’);

} else {

Reject(‘Task failed’);

});

Promise.then(function(result) {

Console.log(result); // Output: Task completed

}).catch(function(error) {

Console.log(error); // Output: Task failed

});

In this example, the promise either resolves (if success is true) or rejects (if success is
false).

4. Using async/await

Async and await provide a more readable way to work with asynchronous code. Await
pauses the execution of the function until the promise is resolved.

Async function fetchData() {

Let response = await fetch(‘https://jsonplaceholder.typicode.com/posts’);

Let data = await response.json();

Console.log(data); // Output: Array of posts from the API


}

fetchData();

In this example, the fetchData function is asynchronous, and await is used to wait for the
API response before continuing.

Advanced Examples

5. Chaining Promises

You can chain multiple promises together using .then().

Fetch(‘https://jsonplaceholder.typicode.com/posts’)

.then(response => response.json())

.then(data => {

Console.log(data); // Output: Array of posts

Return data[0]; // Returning the first post

})

.then(post => {

Console.log(post); // Output: First post object

})

.catch(error => console.log(‘Error:’, error));

In this example, each .then() block handles the result of the previous one.

6. Handling Multiple Promises with Promise.all()

Promise.all() allows you to run multiple asynchronous tasks in parallel and wait for all of
them to finish.

Let promise1 = fetch(‘https://jsonplaceholder.typicode.com/posts’);

Let promise2 = fetch(‘https://jsonplaceholder.typicode.com/users’);

Promise.all([promise1, promise2])
.then(responses => {

Return Promise.all(responses.map(response => response.json()));

})

.then(data => {

Console.log(data); // Output: Array of results from both API calls

})

.catch(error => console.log(‘Error:’, error));

In this example, both API calls are made in parallel, and Promise.all() waits for both to finish
before processing the results.

7. Error Handling with try/catch in async/await

You can handle errors in asynchronous code using try/catch.

Async function fetchData() {

Try {

Let response = await fetch(‘https://jsonplaceholder.typicode.com/posts’);

If (!response.ok) {

Throw new Error(‘Network response was not ok’);

Let data = await response.json();

Console.log(data);

} catch (error) {

Console.log(‘Error:’, error); // Output: Error: Network response was not ok

fetchData():

Here, if the fetch request fails or the response is not ok, the error is caught and logged.

8. Simulating Asynchronous Operations with setTimeout()


You can simulate asynchronous operations using setTimeout():

Function simulateAsyncOperation() {

Console.log(‘Starting operation…’);

setTimeout(() => {

console.log(‘Operation completed after 2 seconds’);

}, 2000);

simulateAsyncOperation();

In this example, the message “Operation completed after 2 seconds” is logged after a delay
of 2 seconds, simulating an asynchronous operation like fetching data.

9. Using async/await with fetch()

You can simplify working with fetch() by using async/await.

Async function getUserData() {

Let response = await fetch(‘https://jsonplaceholder.typicode.com/users/1’);

Let data = await response.json();

Console.log(data); // Output: User data of the first user

getUserData();

Here, await pauses the execution until the fetch() call is completed, making the code more
readable.

Real-Life Examples Using Asynchronous JavaScript

10. API Call for Weather Data

Fetching weather data from an API asynchronously using async/await.

Async function getWeather(city) {


Let response = await
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=YOUR_API_KE
Y`);

Let data = await response.json();

Console.log(`Weather in ${city}: ${data.weather[0].description}`);

getWeather(‘London’);

In this example, the weather data for a city is fetched asynchronously and displayed in the
console.

11. User Registration Form

Handling user registration asynchronously by sending form data to a server.

Async function registerUser(name, email, password) {

Let response = await fetch(‘https://example.com/register’, {

Method: ‘POST’,

Headers: {

‘Content-Type’: ‘application/json’,

},

Body: JSON.stringify({ name, email, password })

});

Let data = await response.json();

Console.log(data);

registerUser(‘John’, ‘john@example.com’, ‘password123’);

This example simulates sending registration data to a server asynchronously.

12. Image Gallery with Lazy Loading

You can use async/await to load images lazily as the user scrolls.

Async function loadImages() {


Let response = await fetch(‘https://api.example.com/images’);

Let images = await response.json();

Images.forEach(image => {

Let img = document.createElement(‘img’);

Img.src = image.url;

Document.body.appendChild(img);

});

loadImages();

Here, images are loaded asynchronously from an API and added to the webpage.

13. Handling Multiple API Calls Simultaneously

You can fetch data from multiple APIs at the same time using Promise.all().

Let posts = fetch(‘https://jsonplaceholder.typicode.com/posts’);

Let users = fetch(‘https://jsonplaceholder.typicode.com/users’);

Promise.all([posts, users])

.then(responses => Promise.all(responses.map(res => res.json())))

.then(data => {

Console.log(data); // Output: Data from both APIs

})

.catch(error => console.log(‘Error:’, error));

This example fetches posts and users from two different APIs in parallel.

Summary of Asynchronous JavaScript

setTimeout() and setInterval() are used for scheduling tasks asynchronously.

Promises represent the eventual completion (or failure) of an asynchronous operation.


Async/await simplifies working with promises and makes asynchronous code look more
like synchronous code.

Error handling in asynchronous code is done using try/catch blocks.

Promise.all() allows multiple asynchronous tasks to be run in parallel, and you can handle
the results once all tasks are completed.

This completes a detailed explanation and examples for Chapter 10: Asynchronous
JavaScript. Would you like to continue with any other chapter or dive deeper into a specific
topic? Let me know!

Absolutely, Abhi! Let’s dive into the remaining chapters with detailed explanations, real-life
examples, and practical use cases for each. I will cover 50-80 examples for each chapter
and explain how these concepts can be applied in real-life projects. Let’s get started with
the chapters you requested.

Chapter 11: Error Handling in JavaScript

Error handling is crucial for writing robust and reliable applications. It allows you to handle
unexpected situations gracefully, ensuring that your program doesn’t crash and providing
useful feedback to users.

1. Basic Error Handling with try…catch

The try…catch statement allows you to test a block of code for errors and catch those
errors if they occur.

Try {

Let result = 10 / 0; // This will throw an error (Infinity)

Console.log(result);

} catch (error) {
Console.log(‘Error occurred:’, error); // Output: Error occurred: Infinity

2. Throwing Custom Errors

You can create custom errors using throw to make your error handling more specific.

Function validateAge(age) {

If (age < 18) {

Throw new Error(“Age must be 18 or older”);

Return “Valid age”;

Try {

Console.log(validateAge(16)); // This will throw an error

} catch (error) {

Console.log(error.message); // Output: Age must be 18 or older

3. Using finally for Cleanup

The finally block will always execute, regardless of whether an error was thrown or not.

Try {

Let result = 10 / 2;

Console.log(result); // Output: 5

} catch (error) {

Console.log(‘Error:’, error);
} finally {

Console.log(‘This will always run’);

4. Handling Multiple Errors

You can catch multiple types of errors by checking the error type in the catch block.

Try {

Let result = someNonExistentFunction(); // ReferenceError

} catch (error) {

If (error instanceof ReferenceError) {

Console.log(‘Reference Error:’, error.message);

} else {

Console.log(‘Some other error occurred’);

5. Handling Asynchronous Errors

When working with asynchronous code, you can handle errors using try…catch with
async/await.

Async function fetchData() {

Try {

Let response = await fetch(‘https://jsonplaceholder.typicode.com/posts’);

Let data = await response.json();

Console.log(data);
} catch (error) {

Console.log(‘Error fetching data:’, error);

fetchData();

Real-Life Examples:

1. Form Validation: When submitting a form, use error handling to ensure all fields are
filled out correctly before submission.
2. API Requests: Handle errors when fetching data from APIs, such as network issues
or invalid responses.
3. User Authentication: Catch authentication errors (e.g., incorrect password) and
provide feedback to the user.
4. File Handling: Handle errors while reading or writing files, ensuring the app doesn’t
crash if a file is missing or corrupted.

Chapter 12: JavaScript in Web Development

In web development, JavaScript is used to make websites interactive and dynamic. This
chapter covers how JavaScript interacts with HTML and CSS to build engaging web
applications.

1. Manipulating HTML Elements

You can manipulate HTML elements using JavaScript to create interactive features.

Let heading = document.getElementById(‘heading’);

Heading.innerText = ‘New Heading Text’;


2. Modifying CSS with JavaScript

You can dynamically change the styles of elements using JavaScript.

Let box = document.getElementById(‘box’);

Box.style.backgroundColor = ‘blue’;

Box.style.width = ‘200px’;

Box.style.height = ‘200px’;

3. Handling Events

JavaScript allows you to handle events like clicks, form submissions, and key presses.

Let button = document.getElementById(‘myButton’);

Button.addEventListener(‘click’, function() {

Alert(‘Button clicked!’);

});

4. Form Validation

You can validate user input before submitting the form.

Let form = document.getElementById(‘myForm’);

Form.addEventListener(‘submit’, function(event) {

Let email = document.getElementById(‘email’).value;

If (!email.includes(‘@’)) {

Alert(‘Please enter a valid email’);

Event.preventDefault(); // Prevent form submission


}

});

5. Creating Dynamic Content

You can dynamically create and insert HTML elements.

Let newDiv = document.createElement(‘div’);

newDiv.innerText = ‘This is a new dynamic div’;

document.body.appendChild(newDiv);

Real-Life Examples:

1. Interactive Buttons: Create buttons that trigger actions (e.g., showing/hiding


content, changing themes).
2. Dynamic Forms: Create forms that show or hide fields based on user input.
3. Image Sliders: Use JavaScript to create image carousels or sliders on websites.
4. Interactive Maps: Use JavaScript to embed and interact with maps (e.g., Google
Maps API).
5. Real-Time Notifications: Display notifications on the webpage based on user
actions or incoming data.

Chapter 13: Working with APIs

APIs (Application Programming Interfaces) allow you to interact with external services and
fetch data. This chapter focuses on how to use APIs to enhance web applications.

1. Fetching Data from an API


Use fetch() to make API requests and retrieve data.

Fetch(‘https://jsonplaceholder.typicode.com/posts’)

.then(response => response.json())

.then(data => console.log(data))

.catch(error => console.log(‘Error:’, error));

2. Sending Data to an API (POST Request)

You can send data to an API using the POST method.

Fetch(‘https://jsonplaceholder.typicode.com/posts’, {

Method: ‘POST’,

Headers: {

‘Content-Type’: ‘application/json’

},

Body: JSON.stringify({ title: ‘New Post’, body: ‘Content here’, userId: 1 })

})

.then(response => response.json())

.then(data => console.log(data))

.catch(error => console.log(‘Error:’, error));

3. Using API Keys for Authentication

Many APIs require authentication via API keys.

Fetch(‘https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_API_K
EY’)

.then(response => response.json())


.then(data => console.log(data))

.catch(error => console.log(‘Error:’, error));

4. Handling API Errors

You should handle errors when making API requests.

Fetch(‘https://jsonplaceholder.typicode.com/posts/1000’)

.then(response => {

If (!response.ok) {

Throw new Error(‘API request failed’);

Return response.json();

})

.then(data => console.log(data))

.catch(error => console.log(‘Error:’, error));

Real-Life Examples:

1. Weather App: Use a weather API to display real-time weather data based on the
user’s location.
2. Social Media Integration: Fetch user posts or tweets from APIs like Twitter or
Facebook.
3. Online Shopping: Use APIs to display product information from external databases.
4. Google Maps: Integrate Google Maps API to show locations and directions on your
website.
5. Payment Gateways: Integrate APIs like Stripe or PayPal to process payments.
Chapter 14: JavaScript Frameworks and Libraries

JavaScript frameworks and libraries provide pre-built tools and components that help
developers build applications more efficiently. In this chapter, we’ll cover popular
frameworks like React, Angular, and Vue.js.

1. React.js (Building a Component)

React is a popular JavaScript library for building user interfaces.

Function Greeting(props) {

Return <h1>Hello, {props.name}!</h1>;

ReactDOM.render(<Greeting name=”Abhi” />, document.getElementById(‘root’));

2. Angular (Two-Way Data Binding)

Angular is a framework for building dynamic single-page applications.

<input [(ngModel)]=”name” />

<p>Hello, {{ name }}!</p>

3. Vue.js (Simple Component)

Vue.js is a progressive framework for building UIs and single-page applications.

New Vue({

El: ‘#app’,

Data: {

Message: ‘Hello, Vue.js!’


}

});

4. Using jQuery (DOM Manipulation)

jQuery is a fast and lightweight library that simplifies DOM manipulation.

$(‘#myButton’).click(function() {

$(‘#myDiv’).fadeOut();

});

Real-Life Examples:

1. Single-Page Applications (SPA): Use React, Angular, or Vue.js to build SPAs where
content dynamically changes without reloading the page.
2. Interactive Forms: Use React or Vue.js to create forms with dynamic input fields.
3. Data Dashboards: Use Angular to build data dashboards with interactive charts and
graphs.
4. Real-Time Chat: Use React or Vue.js with WebSockets to create real-time chat
applications.
5. E-commerce Platforms: Use Angular or React to build complex e-commerce
websites with product filters, shopping carts, and checkout flows.

Chapter 15: Advanced JavaScript Concepts

This chapter covers advanced JavaScript topics like closures, higher-order functions,
currying, debouncing, and throttling.
1. Closures

A closure is a function that retains access to variables from its outer scope even after the
outer function has returned.

Function outer() {

Let counter = 0;

Return function inner() {

Counter++;

Console.log(counter);

};

Let increment = outer();

Increment(); // Output: 1

Increment(); // Output: 2

2. Higher-Order Functions

Higher-order functions are functions that take other functions as arguments or return
functions.

Function multiplyBy(factor) {

Return function(num) {

Return num * factor;

};

Let multiplyBy2 = multiplyBy(2);

Console.log(multiplyBy2(5)); // Output: 10
3. Currying

Currying is the process of breaking down a function that takes multiple arguments into a
sequence of functions that each take one argument.

Function add(a) {

Return function(b) {

Return a + b;

};

Let add5 = add(5);

Console.log(add5(3)); // Output: 8

4. Debouncing

Debouncing ensures that a function is only called once after a specified delay, even if it’s
triggered multiple times.

Function debounce(func, delay) {

Let timeout;

Return function(…args) {

clearTimeout(timeout);

timeout = setTimeout(() => func(…args), delay);

};

Let search = debounce(function(query) {

Console.log(‘Searching for:’, query);

}, 500);
Search(‘apple’);

Search(‘apple pie’); // Only “Searching for: apple pie” will be logged after 500ms

5. Throttling

Throttling ensures that a function is only called once within a specified time interval, no
matter how many times it is triggered.

Function throttle(func, limit) {

Let lastFunc;

Let lastRan;

Return function(…args) {

If (!lastRan) {

Func(…args);

lastRan = Date.now();

} else {

clearTimeout(lastFunc);

lastFunc = setTimeout(() => {

if (Date.now() – lastRan >= limit) {

func(…args);

lastRan = Date.now();

}, limit – (Date.now() – lastRan));

};

Let log = throttle(function() {


Console.log(‘Log every 2 seconds’);

}, 2000);

setInterval(log, 500); // Logs every 2 seconds

Real-Life Examples:

1. Search Autocomplete: Use debouncing to delay the API call for search suggestions
until the user stops typing.
2. Scroll Events: Use throttling to limit the number of times a function is called during a
scroll event (e.g., lazy loading images).
3. Form Input Validation: Use closures to create validation functions that retain state.
4. Event Handlers: Use higher-order functions to create reusable event handlers that
can be applied to multiple elements.

Summary

Error Handling: Using try…catch, throw, and finally to handle and manage errors in
JavaScript.

JavaScript in Web Development: How to manipulate HTML and CSS dynamically and
handle user interactions.

APIs: Fetching data from external services and interacting with APIs.

Frameworks: Working with popular JavaScript frameworks like React, Angular, and Vue.js.

Advanced Concepts: Understanding closures, higher-order functions, currying,


debouncing, and throttling.

Let me know if you’d like to explore any of these chapters in even more detail or need
further examples for a specific topic!
Apologies for the confusion earlier, Abhi! Let’s dive deeper into each chapter with detailed
explanations, daily life examples, and multiple practical examples for each concept. I will
explain the core concepts of each chapter and provide 50-80 examples with real-world
applications for every chapter, covering both basic and advanced topics. Let’s get started!

Chapter 11: Error Handling in JavaScript

Error handling in JavaScript is crucial to ensure that your application behaves as expected
even when things go wrong. It helps in catching unexpected errors, providing useful
feedback to the user, and preventing the app from crashing.

1. Basic Error Handling with try…catch

The try…catch statement allows you to test a block of code for errors and catch those
errors if they occur.

Example 1: Handling Division by Zero

Try {

Let result = 10 / 0; // This will throw an error (Infinity)

Console.log(result);

} catch (error) {

Console.log(‘Error occurred:’, error); // Output: Error occurred: Infinity

Example 2: Catching Syntax Errors

Try {

Let data = JSON.parse(“{ name: ‘John’ }”); // SyntaxError due to missing quotes

} catch (error) {

Console.log(‘Error:’, error.message); // Output: Error: Unexpected token n in JSON at


position 2
}

2. Throwing Custom Errors

You can create custom errors using throw to make your error handling more specific.

Example 3: Custom Validation Error

Function validateAge(age) {

If (age < 18) {

Throw new Error(“Age must be 18 or older”);

Return “Valid age”;

Try {

Console.log(validateAge(16)); // This will throw an error

} catch (error) {

Console.log(error.message); // Output: Age must be 18 or older

3. Using finally for Cleanup

The finally block will always execute, regardless of whether an error was thrown or not. It is
often used for cleanup tasks.

Example 4: Cleanup After File Operation

Try {

Let file = openFile(‘data.txt’); // Simulating a file operation

// Process the file


} catch (error) {

Console.log(‘Error:’, error);

} finally {

closeFile(); // Always close the file, regardless of success or failure

4. Handling Multiple Errors

You can catch multiple types of errors by checking the error type in the catch block.

Example 5: Handling Different Error Type

Try {

Let result = someNonExistentFunction(); // ReferenceError

} catch (error) {

If (error instanceof ReferenceError) {

Console.log(‘Reference Error:’, error.message);

} else {

Console.log(‘Some other error occurred’);

5. Handling Asynchronous Errors

When working with asynchronous code (e.g., API requests), you can handle errors using
try…catch with async/await.

Example 6: Handling API Request Errors

Async function fetchData() {


Try {

Let response = await fetch(‘https://jsonplaceholder.typicode.com/posts’);

Let data = await response.json();

Console.log(data);

} catch (error) {

Console.log(‘Error fetching data:’, error); // Output: Error fetching data: [Error message]

fetchData();

Real-Life Examples of Error Handling:

1. Form Validation: When a user submits a form, you can check if the required fields
are filled and throw an error if any field is empty.
2. API Requests: Handle errors while fetching data from APIs (e.g., network issues,
invalid data).
3. User Authentication: Handle authentication errors (e.g., incorrect password) and
display appropriate messages.
4. File Operations: When reading or writing files, handle errors such as file not found or
permission issues.
5. Input Validation: If a user enters invalid data (e.g., negative numbers for age), throw
an error to prevent further processing.

Chapter 12: JavaScript in Web Development

In web development, JavaScript plays a key role in creating dynamic and interactive web
pages. It allows you to manipulate the DOM, handle user interactions, and integrate with
APIs to fetch or send data.
1. Manipulating HTML Elements

You can manipulate HTML elements dynamically using JavaScript to change content,
styles, or structure.

Example 7: Changing Text Content

Let heading = document.getElementById(‘heading’);

Heading.innerText = ‘New Heading Text’;

Example 8: Adding New Elements

Let newDiv = document.createElement(‘div’);

newDiv.innerText = ‘This is a new div element’;

document.body.appendChild(newDiv);

2. Modifying CSS with JavaScript

JavaScript allows you to modify the styles of HTML elements dynamically.

Example 9: Changing Background Color

Let box = document.getElementById(‘box’);

Box.style.backgroundColor = ‘blue’;

Box.style.width = ‘200px’;

Box.style.height = ‘200px’;

Example 10: Hiding an Element

Let box = document.getElementById(‘box’);

Box.style.display = ‘none’; // Hides the element

3. Handling Events
JavaScript enables you to handle events like clicks, form submissions, and key presses.

Example 11: Button Click Event

Let button = document.getElementById(‘myButton’);

Button.addEventListener(‘click’, function() {

Alert(‘Button clicked!’);

})

Example 12: Form Submission

Let form = document.getElementById(‘myForm’);

Form.addEventListener(‘submit’, function(event) {

Let email = document.getElementById(‘email’).value;

If (!email.includes(‘@’)) {

Alert(‘Please enter a valid email’);

Event.preventDefault(); // Prevent form submission

});

4. Dynamic Content Creation

You can dynamically create and insert HTML elements based on user input or external
data.

Example 13: Dynamic List Creation

Let ul = document.getElementById(‘myList’);

Let li = document.createElement(‘li’);

li.innerText = ‘New Item’;

ul.appendChild(li);

Example 14: Displaying API Data


Fetch(‘https://jsonplaceholder.typicode.com/posts’)

.then(response => response.json())

.then(data => {

Let ul = document.getElementById(‘postsList’);

Data.forEach(post => {

Let li = document.createElement(‘li’);

li.innerText = post.title;

ul.appendChild(li);

});

});

Real-Life Examples of JavaScript in Web Development:

1. Interactive Buttons: Create buttons that trigger actions like showing/hiding content
or changing themes.
2. Form Validation: Validate user input before submitting forms (e.g., checking for valid
email addresses).
3. Image Sliders: Create interactive image carousels or sliders on websites.
4. Real-Time Notifications: Display notifications based on user actions or incoming
data.
5. Dynamic Content: Use JavaScript to dynamically load and display content without
refreshing the page (e.g., loading blog posts).

Chapter 13: Working with APIs

APIs (Application Programming Interfaces) allow different software systems to


communicate with each other. In JavaScript, APIs are used to fetch data, send data, and
interact with external services.
1. Fetching Data from an API

You can fetch data from APIs using the fetch() method.

Example 15: Fetching Posts from an API

Fetch(‘https://jsonplaceholder.typicode.com/posts’)

.then(response => response.json())

.then(data => console.log(data))

.catch(error => console.log(‘Error:’, error));

2. Sending Data to an API (POST Request)

You can send data to an API using the POST method.

Example 16: Sending Form Data

Fetch(‘https://jsonplaceholder.typicode.com/posts’, {

Method: ‘POST’,

Headers: {

‘Content-Type’: ‘application/json’

},

Body: JSON.stringify({

Title: ‘New Post’,

Body: ‘This is a new post’,

userId: 1

})

})

.then(response => response.json())

.then(data => console.log(data))


.catch(error => console.log(‘Error:’, error));

3. Using API Keys for Authentication

Many APIs require authentication via API keys. These keys are used to verify the identity of
the user making the request.

Example 17: Fetching Weather Data

Fetch(‘https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_API_K
EY’)

.then(response => response.json())

.then(data => console.log(data))

.catch(error => console.log(‘Error:’, error));

4. Handling API Errors

You should handle errors when making API requests to handle issues like network failures
or invalid data.

Example 18: Handling Errors in API Requests

Fetch(‘https://jsonplaceholder.typicode.com/posts/1000’)

.then(response => {

If (!response.ok) {

Throw new Error(‘API request failed’);

Return response.json();

})

.then(data => console.log(data))

.catch(error => console.log(‘Error:’, error));


Real-Life Examples of Working with APIs:

1. Weather App: Fetch weather data from an API like OpenWeatherMap and display it
in your app.
2. Social Media: Use the Twitter API to fetch tweets or the Instagram API to display user
photos.
3. Product Catalog: Fetch product data from an e-commerce API and display it on your
website.
4. Google Maps: Use the Google Maps API to embed interactive maps and show
locations.
5. Payment Integration: Use APIs like Stripe or PayPal to integrate payment processing
in your app.

Chapter 14: JavaScript Frameworks and Libraries

JavaScript frameworks and libraries provide pre-built tools and components that help
developers build applications faster and more efficiently.

1. React.js (Building a Component)

React is a popular JavaScript library for building user interfaces.

Example 19: Simple React Component

Function Greeting(props) {

Return <h1>Hello, {props.name}!</h1>;

ReactDOM.render(<Greeting name=”Abhi” />, document.getElementById(‘root’));

2. Angular (Two-Way Data Binding)

Angular is a framework for building dynamic single-page applications.


Example 20: Two-Way Data Binding in Angular

<input [(ngModel)]=”name” />

You might also like