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.
3. JavaScript: Implements interactive features, manages state, calculates logic, and manipulates the document dynamically.
1. Introduction to JavaScript
<script> tagLanguage 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.logI/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, varMemory 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 operatorType 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:
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, elseControl 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, defaultControl 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 * xModern 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.
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 = "
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.
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.
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).
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"]).
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.
Strings in JavaScript are immutable sequences of characters with helpful built-in manipulation methods such as toUpperCase(), toLowerCase(), includes(), slice(), and trim().
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).
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.
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.roundBuilt-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).
The spread operator (...) expands an iterable (like an array or object) into individual elements. It is commonly used for merging arrays and copying objects.
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 ParentOOP 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).
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! 💻⚡
No comments:
Post a Comment