Recent Post

Friday, 28 August 2026

Complete JavaScript Notes By Pratap Sanjay Sir

Complete JavaScript Notes - Basic to Advanced | Pratap Sanjay Sir
⚡ Full-Stack JavaScript Mastery

Complete JavaScript Notes

Master Modern JavaScript (ES6+) with Detailed Paragraph Theory, Clean Source Code & Live Interactive Execution for Every Concept.

📖 50 Core Topics ⚡ DOM & Events 🔄 Async / Await & Fetch API 👨‍🏫 Prepared by Pratap Sanjay Sir

⚡ Introduction to JavaScript

JavaScript (JS) is a powerful, lightweight, cross-platform programming language used to add dynamic behavior, interactivity, logical computation, and server communication to web pages.

Core Trio of Web Development:

1. HTML (HyperText Markup Language): Defines the skeleton, structure, and semantic elements of a web page.

2. CSS (Cascading Style Sheets): Controls visual aesthetics, responsive styling, colors, and layout structure.

3. JavaScript: Implements interactive features, manages state, calculates logic, and manipulates the document dynamically.

1. Introduction to JavaScript

<script> tag Language Basics
📝 Theory & Notes:

JavaScript is an interpreted, client-side scripting language originally developed by Brendan Eich in 1995. It runs directly inside all modern web browsers without requiring additional compiler installations.

You can embed JavaScript code inside HTML documents using the <script> tag or by linking external .js files using the src attribute.

💻 JavaScript Code:
function showWelcome() { document.getElementById("welcomeOutput").textContent = "Welcome to the world of JavaScript Programming! 🚀"; }
🌐 Output Preview:
Click the button above to execute JavaScript...

2. JavaScript Output Methods

innerHTML, textContent, console.log I/O Streams
📝 Theory & Notes:

JavaScript provides multiple techniques to produce outputs and display values to users and developers:

1. innerHTML: Renders HTML elements and formatted text into a container element.

2. textContent: Sets plain text content safely without interpreting HTML markup.

3. console.log(): Prints diagnostics and variables into the browser developer console (F12).

💻 JavaScript Code:
function showOutput() { console.log("Hello from JavaScript Developer Console!"); document.getElementById("outputExample").innerHTML = "Success: Output rendered using innerHTML property!"; }
🌐 Output Preview:
Output will be displayed here...

3. JavaScript Variables (let, const, var)

let, const, var Memory Storage
📝 Theory & Notes:

Variables serve as named memory containers for storing data values. Modern JavaScript uses three declaration keywords:

1. let: Block-scoped variable whose value can be reassigned later.

2. const: Block-scoped constant variable whose reference cannot be reassigned.

3. var: Legacy function-scoped variable keyword (avoid in modern ES6+ code).

💻 JavaScript Code:
function variableExample() { let studentName = "Rahul Sharma"; const studentAge = 15; studentName = "Rahul S. (Updated)"; // let can be reassigned document.getElementById("variableOutput").innerHTML = "Student Name (let): " + studentName + "
Age (const): " + studentAge; }
🌐 Output Preview:
Variable results appear here...

4. JavaScript Data Types

typeof operator Type System
📝 Theory & Notes:

JavaScript is a dynamically typed language with 8 core data types: String, Number, Boolean, Undefined, Null, BigInt, Symbol, and Object.

The typeof unary operator inspects and returns the primitive data type of any variable.

💻 JavaScript Code:
function dataTypeExample() { let name = "Amit"; // String let age = 16; // Number let isEnrolled = true; // Boolean let marks; // Undefined let address = null; // Null (returns object) document.getElementById("dataTypeOutput").innerHTML = "name ('" + name + "'): " + typeof name + "
" + "age (" + age + "): " + typeof age + "
" + "isEnrolled (" + isEnrolled + "): " + typeof isEnrolled + "
" + "marks: " + typeof marks; }
🌐 Output Preview:
Data type analysis will appear here...

5. JavaScript Operators

+, -, *, /, ===, &&, || Computation
📝 Theory & Notes:

Operators perform calculations and logical decisions on operands:

Arithmetic: + (Add), - (Subtract), * (Multiply), / (Divide), % (Modulus), ** (Exponentiation).

Comparison: === (Strict equal with type check), !==, >, <, >=, <=.

Logical: && (AND), || (OR), ! (NOT).

💻 JavaScript Code:
function operatorExample() { let a = 12, b = 5; document.getElementById("operatorOutput").innerHTML = "Addition (12 + 5): " + (a + b) + "
" + "Multiplication (12 * 5): " + (a * b) + "
" + "Modulus Remainder (12 % 5): " + (a % b) + "
" + "Strict Equality (12 === '12'): " + (a === "12"); }
🌐 Output Preview:
Calculated answers will display here...

6. Conditional Statements (if...else if...else)

if, else if, else Control Flow
📝 Theory & Notes:

Conditional statements branch program execution based on whether a boolean expression evaluates to true or false.

Use if for the first test, else if for subsequent conditions, and else as the fallback clause when all prior tests evaluate to false.

💻 JavaScript Code:
function checkAge() { let age = Number(document.getElementById("ageInput").value); let result = ""; if (age >= 18) { result = "✅ You are an eligible adult voter (Age: " + age + ")."; } else if (age > 0) { result = "👶 You are a minor under 18 (Age: " + age + ")."; } else { result = "⚠️ Please enter a valid positive age."; } document.getElementById("ageOutput").textContent = result; }
🌐 Output Preview:
Input an age and click verify...

7. Switch Statement

switch, case, break, default Control Flow
📝 Theory & Notes:

The switch statement evaluates an expression against multiple matching case clauses.

The break keyword terminates execution within the switch block, preventing unwanted fall-through into next cases. The default clause runs if no match is found.

💻 JavaScript Code:
function checkDay() { let dayVal = document.getElementById("dayInput").value; let text = ""; switch (dayVal) { case "1": text = "📅 Monday: Fresh Start of the week!"; break; case "2": text = "📅 Tuesday: Coding and learning!"; break; case "3": text = "📅 Wednesday: Midweek productivity!"; break; case "4": text = "📅 Thursday: Project development!"; break; case "5": text = "🎉 Friday: Weekend is loading!"; break; default: text = "🌟 Weekend / Holiday!"; } document.getElementById("dayOutput").textContent = text; }
🌐 Output Preview:
Select a day from dropdown...

8. For Loop

for (init; cond; step) Iteration
📝 Theory & Notes:

A for loop repeats a block of code a predetermined number of times.

It consists of three expressions separated by semicolons: initialization (e.g. let i = 1), test condition (e.g. i <= 5), and increment/decrement step (e.g. i++).

💻 JavaScript Code:
function forLoopExample() { let result = ""; for (let i = 1; i <= 5; i++) { result += "Iteration " + i + ": Square = " + (i * i) + "
"; } document.getElementById("forOutput").innerHTML = result; }
🌐 Output Preview:
Loop results will be generated here...

9. While Loop

while (condition) Iteration
📝 Theory & Notes:

The while loop repeatedly executes instructions as long as its specified condition remains true.

Because the condition is tested before entering the loop body, if the condition is initially false, the loop will never run.

💻 JavaScript Code:
function whileLoopExample() { let count = 10; let text = ""; while (count <= 50) { text += count + " "; count += 10; } document.getElementById("whileOutput").textContent = "Multiples of 10: " + text; }
🌐 Output Preview:
While loop output will display here...

10. Do...While Loop

do { ... } while () Iteration
📝 Theory & Notes:

The do...while loop is an exit-controlled loop that executes its code block at least once unconditionally before evaluating the condition at the end.

💻 JavaScript Code:
function doWhileExample() { let i = 1; let output = ""; do { output += "Step " + i + " executed | "; i++; } while (i <= 3); document.getElementById("doWhileOutput").textContent = output; }
🌐 Output Preview:
Do while loop output...

11. Functions (Declaration & Invocation)

function greet() Modular Code
📝 Theory & Notes:

A function is a named, reusable block of JavaScript code designed to perform a specific task. Functions avoid duplicate code (DRY principle).

Functions are defined using the function keyword and executed (invoked) by adding parentheses greetUser().

💻 JavaScript Code:
function greetUser() { const time = new Date().toLocaleTimeString(); document.getElementById("functionOutput").textContent = "Hello! Function executed successfully at " + time; }
🌐 Output Preview:
Click the button to invoke function...

12. Function Parameters & Arguments

function(name, role) Modular Code
📝 Theory & Notes:

Parameters are placeholder variable names listed inside the function definition parentheses.

Arguments are the real concrete values passed into the function when calling it.

💻 JavaScript Code:
function makeGreeting(userName) { return "Welcome, " + userName + "! Happy coding in JavaScript."; } function parameterExample() { let val = document.getElementById("nameInput").value.trim() || "Student"; document.getElementById("parameterOutput").textContent = makeGreeting(val); }
🌐 Output Preview:
Personalized greeting will appear here...

13. Function Return Values

return expression; Modular Code
📝 Theory & Notes:

The return keyword stops function execution immediately and hands back a computed value to the caller code location.

💻 JavaScript Code:
function multiply(x, y) { return x * y; } function returnExample() { let n1 = Number(document.getElementById("num1").value); let n2 = Number(document.getElementById("num2").value); let product = multiply(n1, n2); document.getElementById("returnOutput").textContent = "Calculated Product (" + n1 + " × " + n2 + ") = " + product; }
🌐 Output Preview:
Product result will display here...

14. ES6 Arrow Functions

const fn = (x) => x * x Modern ES6
📝 Theory & Notes:

Arrow functions introduced in ES6 provide a concise, clean syntax for writing function expressions using the fat arrow (=>) operator.

Unlike regular functions, arrow functions do not bind their own this context, making them ideal for callbacks.

💻 JavaScript Code:
// Concise ES6 Arrow Function const calculateCube = n => n * n * n; function arrowFunctionExample() { let num = 4; let cube = calculateCube(num); document.getElementById("arrowOutput").textContent = `Cube of ${num} evaluated via Arrow Function = ${cube}`; }
🌐 Output Preview:
Arrow function evaluation output...

15. JavaScript Arrays

[elem1, elem2, elem3] Data Structures
📝 Theory & Notes:

An Array is an ordered, zero-indexed collection capable of storing multiple values under a single variable name.

Array elements are accessed using bracket notation arr[0] and their count is measured with arr.length.

💻 JavaScript Code:
function arrayExample() { let subjects = ["HTML5", "CSS3", "JavaScript", "ReactJS", "NodeJS"]; document.getElementById("arrayOutput").innerHTML = "Full Array: [" + subjects.join(", ") + "]
" + "Total Items: " + subjects.length + "
" + "First Element [0]: " + subjects[0]; }
🌐 Output Preview:
Array elements output...

16. Array Methods (push, pop, shift, unshift)

push(), pop(), shift(), unshift() Array Manipulation
📝 Theory & Notes:

Common mutating methods to add or remove array elements:

push(): Appends new element to the end of the array.

pop(): Removes and returns the last element.

shift(): Removes the first element from the beginning.

unshift(): Adds a new element to the start of the array.

💻 JavaScript Code:
function arrayMethodsExample() { let fruits = ["Apple", "Banana"]; fruits.push("Mango"); // ["Apple", "Banana", "Mango"] fruits.unshift("Orange"); // ["Orange", "Apple", "Banana", "Mango"] fruits.pop(); // removes Mango document.getElementById("arrayMethodsOutput").textContent = "Modified Array: " + JSON.stringify(fruits); }
🌐 Output Preview:
Array mutations will display here...

17. Looping through Arrays (for...of)

for (const item of array) Iteration
📝 Theory & Notes:

The for...of loop iterates seamlessly over iterable data structures such as Arrays and Strings, assigning each consecutive value to a variable without manual index tracking.

💻 JavaScript Code:
function arrayLoopExample() { const students = ["Rahul", "Aman", "Priya", "Neha", "Rohit"]; let html = "
    "; for (const student of students) { html += "
  • Student: " + student + "
  • "; } html += "
"; document.getElementById("arrayLoopOutput").innerHTML = html; }
🌐 Output Preview:
Student list rendered via for...of...

18. Array.prototype.map()

arr.map(x => x * 2) Functional JS
📝 Theory & Notes:

The map() method creates a brand new array populated with the results of calling a provided callback function on every single element in the calling array without modifying the original array.

💻 JavaScript Code:
function mapExample() { const numbers = [2, 4, 6, 8, 10]; const doubled = numbers.map(num => num * 2); document.getElementById("mapOutput").innerHTML = "Original Numbers: [" + numbers.join(", ") + "]
" + "Doubled via map(): [" + doubled.join(", ") + "]"; }
🌐 Output Preview:
Mapped array output...

19. Array.prototype.filter()

arr.filter(x => condition) Functional JS
📝 Theory & Notes:

The filter() method creates a shallow copy of a portion of a given array, filtered down to just the elements that pass the test implemented by the callback predicate function.

💻 JavaScript Code:
function filterExample() { const marks = [45, 82, 33, 91, 58, 76, 29]; const passingMarks = marks.filter(score => score >= 50); document.getElementById("filterOutput").innerHTML = "All Scores: [" + marks.join(", ") + "]
" + "Passing Scores (≥ 50): [" + passingMarks.join(", ") + "]"; }
🌐 Output Preview:
Filtered elements will display here...

20. Array.prototype.reduce()

arr.reduce((acc, cur) => ...) Functional JS
📝 Theory & Notes:

The reduce() method executes a user-supplied reducer callback function on each element of the array, returning a single accumulated result value (e.g. calculating total sum or product).

💻 JavaScript Code:
function reduceExample() { const cartPrices = [120, 250, 499, 80]; const total = cartPrices.reduce((accumulator, currentPrice) => { return accumulator + currentPrice; }, 0); document.getElementById("reduceOutput").textContent = "Items: [" + cartPrices.join(", ") + "] ➔ Total Cart Price = ₹" + total; }
🌐 Output Preview:
Reduced accumulation output...

21. JavaScript Objects

{ key: value } Key-Value Pairs
📝 Theory & Notes:

Objects are unordered collections of related data stored in key: value pairs. Keys are properties that point to primitive values, arrays, or other nested objects.

Properties can be accessed using dot notation (obj.name) or bracket notation (obj["name"]).

💻 JavaScript Code:
function objectExample() { const student = { name: "Rahul Sharma", rollNumber: 101, grade: "8th Standard", isEnrolled: true }; document.getElementById("objectOutput").innerHTML = "Name: " + student.name + "
" + "Roll No: " + student.rollNumber + "
" + "Grade: " + student.grade; }
🌐 Output Preview:
Object properties will display here...

22. Object Methods & `this` Keyword

this.property OOP Basics
📝 Theory & Notes:

A method is a function stored as an object property. Inside an object method, the special keyword this references the owner object executing the current function.

💻 JavaScript Code:
const userAccount = { firstName: "Aman", lastName: "Verma", getFullName: function() { return this.firstName + " " + this.lastName; } }; function objectMethodExample() { document.getElementById("objectMethodOutput").textContent = "Full Name from Method: " + userAccount.getFullName(); }
🌐 Output Preview:
Method result...

23. JavaScript String Methods

toUpperCase(), slice(), replace() String Manipulation
📝 Theory & Notes:

Strings in JavaScript are immutable sequences of characters with helpful built-in manipulation methods such as toUpperCase(), toLowerCase(), includes(), slice(), and trim().

💻 JavaScript Code:
function stringExample() { let str = "Learn JavaScript Today"; document.getElementById("stringOutput").innerHTML = "Original String: '" + str + "'
" + "Length: " + str.length + "
" + "Uppercase: " + str.toUpperCase() + "
" + "Sliced (0, 5): " + str.slice(0, 5) + "
" + "Replaced: " + str.replace("Today", "Everyday!"); }
🌐 Output Preview:
String outputs will appear here...

24. Number Methods (toFixed, parseInt)

toFixed(), parseInt(), parseFloat() Math Utilities
📝 Theory & Notes:

toFixed(n) formats a number to a specified number of decimal digits as a string.

parseInt() parses a string argument and returns an integer, while Number() converts values to numeric types.

💻 JavaScript Code:
function numberExample() { let pi = 3.14159265; let strNum = "42px"; document.getElementById("numberOutput").innerHTML = "pi.toFixed(2): " + pi.toFixed(2) + "
" + "parseInt('42px'): " + parseInt(strNum) + "
" + "isNaN('Hello'): " + isNaN("Hello"); }
🌐 Output Preview:
Number outputs will display here...

25. Document Object Model (DOM)

document.getElementById() DOM API
📝 Theory & Notes:

The DOM (Document Object Model) is a hierarchical tree representation of HTML documents created by the browser. JavaScript accesses and modifies DOM nodes in real time to update text, styles, and attributes.

💻 JavaScript Code:
function changeDOM() { const el = document.getElementById("domDemoText"); el.textContent = "⚡ Text changed dynamically via JavaScript DOM API!"; el.style.color = "#2563eb"; el.style.fontWeight = "bold"; }
🌐 Output Preview:

Original static HTML paragraph text.

26. document.getElementById()

getElementById("id") DOM Selection
📝 Theory & Notes:

document.getElementById() is the fastest method to select a unique element by its specific HTML id attribute.

💻 JavaScript Code:
function changeTargetText() { const target = document.getElementById("specificTarget"); target.textContent = "ID Element located and modified successfully! 🎉"; target.style.background = "#dcfce7"; }
🌐 Output Preview:
I am an element with id="specificTarget"

27. querySelector & querySelectorAll

querySelector(".class / #id") DOM Selection
📝 Theory & Notes:

querySelector() returns the first element that matches a specified CSS selector string (classes like .item, IDs like #nav, or complex tags like div > p).

💻 JavaScript Code:
function queryExample() { const item = document.querySelector(".query-highlight-box"); item.style.backgroundColor = "#fed7aa"; item.style.border = "2px solid #ea580c"; item.textContent = "Styled via querySelector('.query-highlight-box')"; }
🌐 Output Preview:
Target element with class="query-highlight-box"

28. Creating & Appending DOM Elements

createElement(), appendChild() Dynamic DOM
📝 Theory & Notes:

document.createElement('tagName') creates a brand new element in memory, and parent.appendChild(newChild) inserts it into the visible webpage DOM.

💻 JavaScript Code:
function createElementExample() { const container = document.getElementById("newElementArea"); const newBadge = document.createElement("span"); newBadge.textContent = "🏷️ New Item (" + (container.children.length + 1) + ") "; newBadge.style.cssText = "display:inline-block; background:#e0e7ff; color:#3730a3; padding:4px 10px; border-radius:4px; margin:4px; font-weight:600;"; container.appendChild(newBadge); }
🌐 Output Preview:

29. JavaScript Event Handlers

onclick, onmouseover User Interaction
📝 Theory & Notes:

Events represent actions or occurrences that happen in the system (such as user button clicks, mouse hovers, keystrokes, or page loading).

💻 JavaScript Code:
function handleButtonClick() { document.getElementById("eventOutput").textContent = "Event Triggered: onclick handler responded to user click!"; }
🌐 Output Preview:
Waiting for user event...

30. Modern Event Listeners (addEventListener)

addEventListener('click', fn) Standard Events
📝 Theory & Notes:

addEventListener() attaches event handler functions to elements cleanly without overwriting existing event handlers or polluting HTML markup with inline event attributes.

💻 JavaScript Code:
const btn = document.getElementById("listenerDemoBtn"); btn.addEventListener("click", function() { document.getElementById("listenerOutput").textContent = "✅ addEventListener('click') fired successfully!"; });
🌐 Output Preview:
Listener is active and waiting...

31. Interactive Form Validation

form.onsubmit, trim() Form Security
📝 Theory & Notes:

Client-side form validation prevents invalid or empty form data submissions before data is transmitted over the network to a backend server.

💻 JavaScript Code:
function validateUserForm() { let name = document.getElementById("userNameInput").value.trim(); let msg = document.getElementById("validationOutput"); if (name === "") { msg.innerHTML = "<span class='msg-error'>❌ Error: Name field cannot be empty!</span>"; } else { msg.innerHTML = "<span class='msg-success'>✅ Success: Welcome, " + name + "! Form is valid.</span>"; } }
🌐 Output Preview:
Form status message will appear here...

32. The Math Object

Math.sqrt, Math.random, Math.round Built-in Object
📝 Theory & Notes:

The Math namespace object provides mathematical constants and methods such as Math.sqrt(), Math.pow(), Math.random(), Math.floor(), and Math.round().

💻 JavaScript Code:
function mathExample() { let rand = Math.floor(Math.random() * 100) + 1; document.getElementById("mathOutput").innerHTML = "Square root of 64: " + Math.sqrt(64) + "
" + "2 to the power 4: " + Math.pow(2, 4) + "
" + "Random Integer (1-100): " + rand + ""; }
🌐 Output Preview:
Math outputs will display here...

33. The Date Object

new Date() Time Management
📝 Theory & Notes:

The Date object represents a single moment in time. It provides getter methods like getFullYear(), getMonth(), getDate(), and toLocaleDateString().

💻 JavaScript Code:
function showLiveDate() { let d = new Date(); document.getElementById("dateOutput").innerHTML = "Full String: " + d.toString() + "
" + "Formatted Date: " + d.toLocaleDateString() + "
" + "Formatted Time: " + d.toLocaleTimeString(); }
🌐 Output Preview:
Click to get current timestamp...

34. Timers: setTimeout()

setTimeout(fn, delayMs) Async Timers
📝 Theory & Notes:

setTimeout() schedules a single execution of a callback function after a specified delay in milliseconds (1000ms = 1s).

💻 JavaScript Code:
function timeoutExample() { const box = document.getElementById("timeoutOutput"); box.textContent = "⏳ Timer started... waiting 2 seconds..."; setTimeout(() => { box.textContent = "🎉 2 seconds elapsed! Timer callback executed."; }, 2000); }
🌐 Output Preview:
Click button to test setTimeout()...

35. Timers: setInterval() & clearInterval()

setInterval(), clearInterval() Async Timers
📝 Theory & Notes:

setInterval() repeatedly invokes a callback function at a fixed time delay interval. Pass the returned timer ID to clearInterval() to halt the timer.

💻 JavaScript Code:
let count = 0; let timerId = null; function startCounter() { if (timerId !== null) return; timerId = setInterval(() => { count++; document.getElementById("counterOutput").textContent = "Seconds: " + count; }, 1000); } function stopCounter() { clearInterval(timerId); timerId = null; }
🌐 Output Preview:
Seconds: 0

36. JSON (JavaScript Object Notation)

JSON.stringify(), JSON.parse() Data Exchange
📝 Theory & Notes:

JSON is a universal text format for serializing and exchanging structured data.

JSON.stringify() converts a JavaScript object into a JSON string; JSON.parse() converts a JSON string back into a JavaScript object.

💻 JavaScript Code:
function jsonExample() { const student = { name: "Priya", age: 14, subjects: ["Math", "Science"] }; const jsonStr = JSON.stringify(student); const parsedObj = JSON.parse(jsonStr); document.getElementById("jsonOutput").innerHTML = "JSON String: " + jsonStr + "
" + "Parsed Name: " + parsedObj.name; }
🌐 Output Preview:
JSON data will appear here...

37. ES6 Destructuring Assignment

const { title, year } = book Modern ES6
📝 Theory & Notes:

Destructuring syntax enables unpacking values from arrays or properties from objects into distinct variables cleanly and concisely.

💻 JavaScript Code:
function destructuringExample() { const user = { username: "rajesh99", role: "Instructor", country: "India" }; const { username, role, country } = user; // Object Destructuring const colors = ["Red", "Green", "Blue"]; const [firstColor, secondColor] = colors; // Array Destructuring document.getElementById("destructuringOutput").innerHTML = `User: ${username} | Role: ${role} | Country: ${country}
` + `First Color: ${firstColor}, Second Color: ${secondColor}`; }
🌐 Output Preview:
Unpacked variables will display here...

38. Spread Operator (...)

[...arr1, ...arr2] Modern ES6
📝 Theory & Notes:

The spread operator (...) expands an iterable (like an array or object) into individual elements. It is commonly used for merging arrays and copying objects.

💻 JavaScript Code:
function spreadExample() { const frontEnd = ["HTML", "CSS", "JS"]; const backEnd = ["NodeJS", "Express", "MongoDB"]; const fullStack = [...frontEnd, ...backEnd, "Git"]; document.getElementById("spreadOutput").textContent = "Merged Stack: [" + fullStack.join(", ") + "]"; }
🌐 Output Preview:
Merged array output...

39. Rest Parameters (...)

function sum(...numbers) Modern ES6
📝 Theory & Notes:

The rest parameter syntax allows a function to accept an indefinite number of arguments bundled into a standard array.

💻 JavaScript Code:
function sumAll(...numbers) { return numbers.reduce((acc, n) => acc + n, 0); } function restExample() { let ans1 = sumAll(10, 20, 30); let ans2 = sumAll(5, 10, 15, 20, 25, 30); document.getElementById("restOutput").innerHTML = "sumAll(10, 20, 30) = " + ans1 + "
" + "sumAll(5, 10, 15, 20, 25, 30) = " + ans2; }
🌐 Output Preview:
Rest parameter output...

40. Template Literals & String Interpolation

`Hello ${name}!` Modern ES6
📝 Theory & Notes:

Template literals use backticks (` `) instead of regular quotes, allowing multi-line strings and embedded expressions using ${expression}.

💻 JavaScript Code:
function templateExample() { const item = "Laptop"; const price = 45000; const tax = 0.18; const total = price * (1 + tax); const message = `Product: ${item} | Net Total: ₹${total.toLocaleString('en-IN')}`; document.getElementById("templateOutput").textContent = message; }
🌐 Output Preview:
Interpolated string will display here...

41. Error Handling (try...catch...finally)

try { ... } catch (err) Error Handling
📝 Theory & Notes:

The try...catch statement handles runtime errors gracefully, preventing unhandled exceptions from crashing your entire application.

💻 JavaScript Code:
function errorExample() { try { // Calling an intentionally undefined function to test catch block nonExistentFunctionCall(); } catch (error) { document.getElementById("errorOutput").innerHTML = "<span class='msg-error'>Caught Error: " + error.name + " - " + error.message + "</span>"; } }
🌐 Output Preview:
Click to trigger error handling...

42. ES6 Classes

class Person {} OOP Architecture
📝 Theory & Notes:

Introduced in ES6, class provides a clean, syntax sugar over JavaScript's existing prototype-based inheritance to instantiate structured objects.

💻 JavaScript Code:
class Student { constructor(name, subject) { this.name = name; this.subject = subject; } describe() { return `${this.name} is studying ${this.subject}.`; } } function classExample() { const s1 = new Student("Anjali", "Computer Science"); document.getElementById("classOutput").textContent = s1.describe(); }
🌐 Output Preview:
Class instance output...

43. Class Constructors & Properties

constructor(a, b) OOP Architecture
📝 Theory & Notes:

The constructor method is a special function invoked automatically when creating new objects with the new keyword to initialize instance properties.

💻 JavaScript Code:
class Vehicle { constructor(brand, model, year) { this.brand = brand; this.model = model; this.year = year; } } function constructorExample() { const car = new Vehicle("Tata", "Nexon EV", 2024); document.getElementById("constructorOutput").innerHTML = `Brand: ${car.brand} | Model: ${car.model} | Year: ${car.year}`; }
🌐 Output Preview:
Constructor instance output...

44. Class Inheritance (extends & super)

class Sub extends Parent OOP Architecture
📝 Theory & Notes:

Class inheritance allows a child class to inherit methods and properties from a parent class using the extends keyword. super() invokes the parent constructor.

💻 JavaScript Code:
class Animal { constructor(name) { this.name = name; } makeSound() { return `${this.name} makes a sound.`; } } class Dog extends Animal { bark() { return `${this.name} barks: Woof Woof! 🐶`; } } function inheritanceExample() { const myDog = new Dog("Buddy"); document.getElementById("inheritanceOutput").innerHTML = myDog.makeSound() + "<br>" + myDog.bark(); }
🌐 Output Preview:
Inheritance output...

45. JavaScript Promises

new Promise((resolve, reject)) Asynchronous JS
📝 Theory & Notes:

A Promise is an object representing the eventual completion or failure of an asynchronous operation (States: Pending, Fulfilled, Rejected).

💻 JavaScript Code:
function promiseExample() { const box = document.getElementById("promiseOutput"); box.textContent = "Promise pending..."; const mockPromise = new Promise((resolve) => { setTimeout(() => resolve("✅ Promise fulfilled successfully after 1.5s!"), 1500); }); mockPromise.then(result => { box.textContent = result; }); }
🌐 Output Preview:
Promise status...

46. Async / Await Syntax

async function() { await ... } Asynchronous JS
📝 Theory & Notes:

async/await provides syntactic sugar on top of Promises, allowing developers to write asynchronous code that reads sequentially like synchronous code.

💻 JavaScript Code:
async function asyncExample() { const box = document.getElementById("asyncOutput"); box.textContent = "⏳ Step 1: Processing async task..."; await new Promise(r => setTimeout(r, 1200)); box.textContent = "⚡ Step 2: Await finished! Task completed cleanly."; }
🌐 Output Preview:
Async output will display here...

47. Fetch API (HTTP Network Requests)

fetch(url).then(res => res.json()) Network API
📝 Theory & Notes:

The fetch() API provides an interface for fetching remote HTTP resources across the network, returning a Promise that resolves with a Response object.

💻 JavaScript Code:
async function fetchExample() { const box = document.getElementById("fetchOutput"); box.textContent = "Fetching user data from API..."; try { const res = await fetch("https://jsonplaceholder.typicode.com/users/1"); const user = await res.json(); box.innerHTML = "<strong>Name:</strong> " + user.name + "<br>" + "<strong>Email:</strong> " + user.email + "<br>" + "<strong>City:</strong> " + user.address.city; } catch (err) { box.textContent = "Error fetching data: " + err.message; } }
🌐 Output Preview:
Live API data will load here...

48. LocalStorage (Persistent Browser Storage)

localStorage.setItem(), getItem() Web Storage
📝 Theory & Notes:

localStorage allows storing key-value pairs persistently in the user's browser with no expiration date, surviving page reloads and browser restarts.

💻 JavaScript Code:
function saveLocalData() { let val = document.getElementById("storageInput").value; localStorage.setItem("myStudyNote", val); document.getElementById("storageOutput").textContent = "💾 Data saved to localStorage!"; } function getLocalData() { let saved = localStorage.getItem("myStudyNote"); document.getElementById("storageOutput").textContent = saved ? "📂 Retrieved: " + saved : "No item found in localStorage."; } function clearLocalData() { localStorage.removeItem("myStudyNote"); document.getElementById("storageOutput").textContent = "🗑️ Item removed from storage."; }
🌐 Output Preview:

Storage actions will display here...

49. SessionStorage

sessionStorage.setItem() Web Storage
📝 Theory & Notes:

sessionStorage maintains data for the duration of the current page session. The stored data is cleared as soon as the browser tab or window is closed.

💻 JavaScript Code:
function sessionExample() { sessionStorage.setItem("activeSessionUser", "Student_Class8"); let user = sessionStorage.getItem("activeSessionUser"); document.getElementById("sessionOutput").textContent = "Session Active for: " + user + " (Cleared when tab closes)"; }
🌐 Output Preview:
Session data output...

50. Regular Expressions (RegEx)

/pattern/.test(string) Pattern Matching
📝 Theory & Notes:

Regular Expressions are patterns used to match character combinations in strings. The regex.test() method returns true if a string conforms to the pattern.

💻 JavaScript Code:
function regexExample() { let email = document.getElementById("regexEmailInput").value.trim(); let emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; let out = document.getElementById("regexOutput"); if (emailPattern.test(email)) { out.innerHTML = "<span class='msg-success'>✅ Valid Email Pattern!</span>"; } else { out.innerHTML = "<span class='msg-error'>❌ Invalid Email Format (e.g. name@domain.com)</span>"; } }
🌐 Output Preview:
RegEx validation result...

51. JavaScript Summary & Practical Roadmap

🎓 Revision Box
📝 Key Exam & Real-World JS Rules:

Variables: Always prefer const by default, use let when reassignment is necessary, and avoid var.

DOM Interaction: Use document.querySelector and addEventListener for clean separation of concerns.

Async Programming: Use async/await paired with try...catch for robust network communication.

Immutability: Leverage map(), filter(), and spread syntax (...) to maintain pure data structures.

🎉 Message for Students:

Congratulations! 🚀

You have covered the entire JavaScript syllabus from primitive types to modern ES6+ classes, async/await, and DOM manipulation.

Keep building real-world projects and practicing JavaScript daily! 💻⚡

Complete JavaScript Notes • Web Development & Modern ES6+

Prepared by Pratap Sanjay Sir | Learn JavaScript with Theory, Pure Syntax & Live Interactive Previews

No comments:

"कोशिश करो तो सब कुछ हो सकता है, न करो तो कुछ नहीं हो सकता।"