[Go to site: main page, start]

0% found this document useful (0 votes)
26 views47 pages

JavaScript Notes

The document is a comprehensive guide on JavaScript, covering topics from beginner to advanced levels across 15 chapters. It includes essential concepts such as variables, data types, functions, and the Document Object Model (DOM), along with modern features like ES6 and asynchronous programming. The notes provide definitions, examples, and best practices for effectively using JavaScript in web development.
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)
26 views47 pages

JavaScript Notes

The document is a comprehensive guide on JavaScript, covering topics from beginner to advanced levels across 15 chapters. It includes essential concepts such as variables, data types, functions, and the Document Object Model (DOM), along with modern features like ES6 and asynchronous programming. The notes provide definitions, examples, and best practices for effectively using JavaScript in web development.
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

COLLEGE CODERS

presents

JavaScript
Complete Notes
Beginner to Advanced | With Definitions & Simple Examples

15 Chapters Variables Functions DOM ES6 Async Fetch API

[Link] | Learn. Build. Grow.


Table of Contents

01. Introduction to JavaScript


02. Variables & Declarations
03. Data Types
04. Operators
05. Conditional Statements
06. Loops & Iteration
07. Functions
08. Arrays
09. Objects
10. Document Object Model (DOM)
11. Events
12. ES6+ Modern Features
13. Asynchronous JavaScript
14. Promises
15. Fetch API
01. Introduction to JavaScript
Definition: JavaScript — A lightweight, interpreted programming language that runs in the browser
and on servers. It adds interactivity, logic, and dynamic behaviour to web pages.

What is JavaScript?
JavaScript was created by Brendan Eich in 1995. It was originally built for web browsers, but today it
runs almost everywhere — servers, mobile apps, and even robots.
● It is the language of the Web — every browser understands it.
● It can read and change HTML, react to clicks, send data to servers, and much more.
● It is the only language that runs natively inside the browser.
● On the server side, it runs using [Link].

Where Does JavaScript Run?


● Browser — Chrome, Firefox, Safari, Edge run JS natively.
● [Link] — runs JS on computers and servers (outside the browser).
● React Native — builds mobile apps using JavaScript.
● Electron — builds desktop apps (VS Code is built with JS!).

How to Add JavaScript to HTML


Method 1: Inside a Script Tag
You write JavaScript directly inside an HTML file using the <script> tag.
⯈ Simple Example
1 <!DOCTYPE html>
2 <html>
3 <body>
4 <script>
5 // This shows a message in the browser console
6 [Link]("Hello from JavaScript!");
7 </script>
8 </body>
9 </html>
Output: Hello from JavaScript!

Method 2: External JS File (Best Practice)


You create a separate .js file and link it inside your HTML.
⯈ [Link]
1 <script src="[Link]" defer></script>
⯈ [Link]
1 [Link]("External JS loaded!");
TIP Always use the `defer` attribute so your JS runs AFTER the page is fully loaded.
Your First JavaScript Program
⯈ Hello World — 3 Ways
1 // Way 1: Print to console (developer tool)
2 [Link]("Hello, World!");
3
4 // Way 2: Show a popup alert box
5 alert("Hello, World!");
6
7 // Way 3: Ask user for input
8 let name = prompt("What is your name?");
9 [Link]("Hello, " + name);

JavaScript ECMAScript Versions


JavaScript is officially called ECMAScript (ES). New versions are released each year with new features.
Version Year Key Features Added
ES5 2009 strict mode, JSON support, Array methods
ES6 (most important) 2015 let, const, arrow functions, classes, Promises,
template strings
ES2017 2017 async/await, [Link]
ES2020 2020 Optional chaining ?., Nullish coalescing ??
ES2022+ 2022+ Top-level await, class fields, [Link]()

TIP You do not need to memorise all versions. Focus on ES5 and ES6 — they are the most important.
02. Variables & Declarations
Definition: Variable — A named container that stores a value. Think of it like a labelled box where you
can put a value and refer to it by the label name.

Three Ways to Declare Variables


JavaScript has three keywords to create variables: var, let, and const.
⯈ Basic Variable Declaration
1 // var — old way (function-scoped, avoid in modern JS)
2 var city = 'Mumbai';
3
4 // let — modern way (block-scoped, value can change)
5 let age = 20;
6 age = 21; // allowed — we can update it
7
8 // const — constant (block-scoped, value cannot change)
9 const PI = 3.14159;
10 // PI = 3; // ERROR! Cannot reassign a const

var vs let vs const — Simple Comparison


Feature var let const
Can be updated? Yes Yes No
Can be redeclared? Yes No No
Scope Function Block {} Block {}
Hoisted? Yes Yes (TDZ error) Yes (TDZ error)
(undefined)
When to use? Avoid it When value When value
changes stays fixed

What is Scope?
Definition: Scope — The area of code where a variable can be accessed. Think of it like different
rooms in a house — a variable inside a room cannot be seen from outside.
⯈ Block Scope Example
1 // let and const are block-scoped (inside {} curly braces)
2 if (true) {
3 let message = "I am inside the block";
4 [Link](message); // Works fine
5 }
6
7 // [Link](message); // ERROR! message is not visible here

What is Hoisting?
Definition: Hoisting — JavaScript moves variable and function declarations to the top of their scope
before the code runs. This is called hoisting.
⯈ Hoisting with var
1 [Link](name); // undefined (no error)
2 var name = 'Alice'; // var is hoisted to top
3
4 // JavaScript actually sees it as:
5 // var name;
6 // [Link](name); // undefined
7 // name = 'Alice';
⯈ Hoisting with let — Temporal Dead Zone
1 // [Link](score); // ReferenceError — cannot access before init
2 let score = 100;
WARNING Always declare variables at the top of your code to avoid hoisting confusion.

Naming Rules for Variables


● Must start with a letter, _, or $
● Cannot start with a number — 1name is invalid
● Case-sensitive — myVar and myvar are different variables
● Cannot use reserved words like if, for, class, etc.

Naming Conventions
● camelCase — for variables and functions: firstName, totalScore
● UPPER_SNAKE_CASE — for constants: MAX_LIMIT, API_KEY
● PascalCase — for classes: UserProfile, ShoppingCart

Destructuring Assignment
Definition: Destructuring — A shortcut to unpack values from arrays or objects into separate
variables in one line.
⯈ Array Destructuring
1 // Old way:
2 const arr = [10, 20, 30];
3 const a = arr[0]; // 10
4 const b = arr[1]; // 20
5
6 // New way with destructuring:
7 const [x, y, z] = [10, 20, 30];
8 [Link](x); // 10
9 [Link](y); // 20
Output: 10 20
⯈ Object Destructuring
1 const person = { name: "Alice", age: 25 };
2
3 // Extract properties into variables
4 const { name, age } = person;
5 [Link](name); // Alice
6 [Link](age); // 25
Output: Alice 25
03. Data Types
Definition: Data Type — The kind/category of value a variable holds. JavaScript has 8 built-in data
types, split into Primitive (simple) and Non-primitive (complex) types.

The 7 Primitive Data Types


Primitive types hold a single simple value. They are stored directly in memory.

1. Number
Definition: Number — Used for all numeric values — integers, decimals, negative numbers, Infinity,
and NaN.
⯈ Example
1 let age = 25; // whole number
2 let price = 9.99; // decimal
3 let negative = -100; // negative
4 let big = 1_000_000; // underscore for readability
5 let infinity = Infinity;
6 let notNumber = NaN; // result of invalid math
7
8 [Link](10 / 0); // Infinity
9 [Link]("abc" * 2); // NaN

2. String
Definition: String — A sequence of characters (text) enclosed in single quotes, double quotes, or
backticks.
⯈ Example
1 let name = "Alice"; // double quotes
2 let city = 'Mumbai'; // single quotes
3 let country = `India`; // backticks (template literal)
4
5 // Joining strings (concatenation)
6 let greeting = "Hello " + name; // "Hello Alice"
7 [Link](greeting);
8
9 // Template literal — embed variables using ${}
10 let intro = `My name is ${name} from ${city}.`;
11 [Link](intro);
Output: Hello Alice | My name is Alice from Mumbai.

3. Boolean
Definition: Boolean — Represents only two values: true or false. Used in conditions and comparisons.
⯈ Example
1 let isLoggedIn = true;
2 let hasError = false;
3
4 // Result of comparisons is always boolean
5 [Link](10 > 5); // true
6 [Link](10 === 5); // false
7
8 let age = 18;
9 [Link](age >= 18); // true

4. Undefined
Definition: Undefined — A variable that has been declared but NOT yet given a value has the value
undefined.
⯈ Example
1 let score;
2 [Link](score); // undefined
3
4 // A function that returns nothing gives undefined
5 function doNothing() {}
6 [Link](doNothing()); // undefined

5. Null
Definition: Null — Represents the intentional absence of any value. You manually set a variable to null
to say 'this has no value right now'.
⯈ Example
1 let user = null; // no user logged in
2 [Link](user); // null
3
4 // Later when user logs in:
5 user = { name: "Alice" };
6 [Link](user); // { name: 'Alice' }
TIP null means 'empty on purpose'. undefined means 'not yet set'. They are different!

6. Symbol (ES6)
Definition: Symbol — A unique and immutable value, mainly used as unique object property keys. No
two symbols are ever equal.
⯈ Example
1 const id1 = Symbol("id");
2 const id2 = Symbol("id");
3 [Link](id1 === id2); // false — always unique

7. BigInt (ES2020)
Definition: BigInt — Used for very large integers that exceed the safe integer limit of regular numbers.
⯈ Example
1 const big = 9007199254740991n; // note the 'n' at the end
2 [Link](big + 1n); // 9007199254740992n

Non-Primitive: Object
Definition: Object — A collection of key-value pairs. Arrays, functions, and dates are all objects.
Unlike primitives, objects are stored as references.
⯈ Example
1 // Object — key: value pairs
2 const person = { name: "Bob", age: 30 };
3
4 // Array — ordered list (also an object)
5 const colors = ['red', 'green', 'blue'];
6
7 // Function — also an object in JS
8 function greet() { return 'Hello!'; }

Checking Data Type with typeof


Definition: typeof — An operator that tells you the data type of a value.
⯈ Example
1 typeof 42 // "number"
2 typeof "hello" // "string"
3 typeof true // "boolean"
4 typeof undefined // "undefined"
5 typeof null // "object" ← known JS quirk!
6 typeof {} // "object"
7 typeof [] // "object" ← arrays are objects
8 typeof function(){} // "function"
WARNING typeof null returns "object" — this is a historical bug in JavaScript. Always use === null to check
for null.

Type Conversion
Definition: Type Conversion — Converting a value from one data type to another. Can be automatic
(implicit) or manual (explicit).
⯈ Explicit Conversion
1 // To Number
2 Number("42") // 42
3 Number(true) // 1
4 Number(false) // 0
5 Number("hello") // NaN
6
7 // To String
8 String(42) // "42"
9 String(true) // "true"
10
11 // To Boolean
12 Boolean(0) // false ← 0 is falsy
13 Boolean("") // false ← empty string is falsy
14 Boolean(null) // false
15 Boolean(1) // true
16 Boolean("hello") // true
04. Operators
Definition: Operator — A special symbol or keyword that performs an operation on one or more
values (called operands). Example: + adds two numbers.

1. Arithmetic Operators
Used to perform mathematical calculations.
⯈ Example
1 let a = 10, b = 3;
2
3 [Link](a + b); // 13 — Addition
4 [Link](a - b); // 7 — Subtraction
5 [Link](a * b); // 30 — Multiplication
6 [Link](a / b); // 3.33.. — Division
7 [Link](a % b); // 1 — Remainder (Modulo)
8 [Link](a ** b); // 1000 — Exponentiation (10 to power 3)
9
10 // Increment and Decrement
11 let x = 5;
12 x++; // x becomes 6 (add 1)
13 x--; // x becomes 5 (subtract 1)
14 [Link](x); // 5

2. Assignment Operators
Definition: Assignment Operator — Assigns a value to a variable. The basic one is = but there are
shortcuts for common operations.
⯈ Example
1 let x = 10; // basic assignment
2
3 x += 5; // same as x = x + 5 → x is now 15
4 x -= 3; // same as x = x - 3 → x is now 12
5 x *= 2; // same as x = x * 2 → x is now 24
6 x /= 4; // same as x = x / 4 → x is now 6
7 x %= 4; // same as x = x % 4 → x is now 2
8 x **= 3; // same as x = x ** 3 → x is now 8

3. Comparison Operators
Definition: Comparison Operator — Compares two values and returns true or false (a Boolean
result).
⯈ == vs ===
1 // == loose equality — converts types before comparing
2 [Link](5 == "5"); // true (number vs string, converted)
3 [Link](0 == false); // true
4
5 // === strict equality — NO type conversion (recommended)
6 [Link](5 === "5"); // false (different types)
7 [Link](5 === 5); // true
8
9 // Other comparison operators
10 [Link](10 > 5); // true
11 [Link](10 >= 10); // true
12 [Link](3 < 5); // true
13 [Link](3 <= 2); // false
14 [Link](5 !== "5"); // true (strict NOT equal)
WARNING Always use === instead of ==. Using == can lead to unexpected bugs due to automatic type
conversion.

4. Logical Operators
Definition: Logical Operator — Combines multiple conditions. Returns true or false based on the
logic.
⯈ Example
1 // && (AND) — true ONLY if BOTH sides are true
2 [Link](true && true); // true
3 [Link](true && false); // false
4 [Link](5 > 3 && 10 > 7);// true
5
6 // || (OR) — true if AT LEAST ONE side is true
7 [Link](false || true); // true
8 [Link](false || false); // false
9
10 // ! (NOT) — flips true to false, false to true
11 [Link](!true); // false
12 [Link](!false); // true
13 [Link](!0); // true (0 is falsy, so !0 is true)

5. Ternary Operator
Definition: Ternary Operator — A one-line shortcut for if/else. Syntax: condition ? valueIfTrue :
valueIfFalse
⯈ Example
1 let age = 20;
2
3 // Long way:
4 // if (age >= 18) { status = 'Adult' } else { status = 'Minor' }
5
6 // Short way using ternary:
7 const status = age >= 18 ? "Adult" : "Minor";
8 [Link](status); // "Adult"
9
10 // Another example:
11 let marks = 75;
12 let result = marks >= 50 ? "Pass" : "Fail";
13 [Link](result); // Pass

6. Nullish Coalescing (??)


Definition: Nullish Coalescing — Returns the right-hand value only if the left-hand value is null or
undefined. Great for setting default values.
⯈ Example
1 let userName = null;
2 let displayName = userName ?? "Guest";
3 [Link](displayName); // "Guest"
4
5 let score = 0;
6 let finalScore = score ?? 100; // 0 is NOT null, so keeps 0
7 [Link](finalScore); // 0
TIP ?? is better than || for defaults because || treats 0 and '' as falsy, but ?? only checks for null/undefined.
05. Conditional Statements
Definition: Conditional Statement — Code that runs only when a specific condition is true. It lets your
program make decisions — just like you decide what to wear based on the weather.

1. if Statement
Definition: if — Runs a block of code only if the condition is true.
⯈ Simple if
1 let temperature = 32;
2
3 if (temperature > 30) {
4 [Link]("It is hot outside!");
5 }
Output: It is hot outside!

2. if...else Statement
Definition: if...else — If the condition is true, run first block. Otherwise, run the else block.
⯈ Example
1 let age = 15;
2
3 if (age >= 18) {
4 [Link]("You can vote.");
5 } else {
6 [Link]("You are too young to vote.");
7 }
Output: You are too young to vote.

3. if...else if...else Chain


Use this when you have multiple different conditions to check.
⯈ Grade Calculator
1 let marks = 75;
2
3 if (marks >= 90) {
4 [Link]("Grade: A");
5 } else if (marks >= 80) {
6 [Link]("Grade: B");
7 } else if (marks >= 70) {
8 [Link]("Grade: C");
9 } else if (marks >= 60) {
10 [Link]("Grade: D");
11 } else {
12 [Link]("Grade: F — Please retry");
13 }
Output: Grade: C

4. switch Statement
Definition: switch — Checks one value against many possible cases. Cleaner than multiple if/else
when comparing the same variable.
⯈ Day Name
1 let day = 3;
2
3 switch (day) {
4 case 1:
5 [Link]("Monday");
6 break;
7 case 2:
8 [Link]("Tuesday");
9 break;
10 case 3:
11 [Link]("Wednesday");
12 break;
13 case 4:
14 [Link]("Thursday");
15 break;
16 case 5:
17 [Link]("Friday");
18 break;
19 default:
20 [Link]("Weekend!");
21 }
Output: Wednesday
WARNING Always write `break` at the end of each case, or execution will 'fall through' to the next case.

5. Truthy and Falsy Values


Definition: Falsy Value — A value that evaluates to false in a boolean context. There are only 6 falsy
values in JavaScript.
⯈ All Falsy Values
1 // These 6 values are FALSY:
2 if (false) { } // false
3 if (0) { } // zero
4 if ("") { } // empty string
5 if (null) { } // null
6 if (undefined) { } // undefined
7 if (NaN) { } // Not a Number
8
9 // Everything else is TRUTHY:
10 if (1) { [Link]("truthy"); }
11 if ("hello") { [Link]("truthy"); }
12 if ([]) { [Link]("truthy"); } // empty array!
13 if ({}) { [Link]("truthy"); } // empty object!

6. Optional Chaining (?.)


Definition: Optional Chaining — Safely access deeply nested properties without getting an error if a
middle property is null or undefined.
⯈ Example
1 const user = {
2 name: 'Alice',
3 address: {
4 city: "New York"
5 }
6 };
7
8 // Without optional chaining (can crash):
9 // [Link]([Link]); // ERROR!
10
11 // With optional chaining (safe):
12 [Link](user?.address?.city); // New York
13 [Link](user?.phone?.number); // undefined (no error!)
06. Loops & Iteration
Definition: Loop — A loop repeats a block of code multiple times until a condition is met. Instead of
writing the same code 100 times, you write it once inside a loop.

1. for Loop
Definition: for Loop — The most common loop. Used when you know exactly how many times you
want to repeat something. Has 3 parts: start, condition, and update.
⯈ Count from 1 to 5
1 // for (start; condition; update)
2 for (let i = 1; i <= 5; i++) {
3 [Link](i);
4 }
5 // Output: 1 2 3 4 5
⯈ Loop through an Array
1 const fruits = ['apple', 'banana', 'mango'];
2
3 for (let i = 0; i < [Link]; i++) {
4 [Link](fruits[i]);
5 }
6 // Output: apple banana mango

2. while Loop
Definition: while Loop — Keeps repeating as long as the condition is true. Use it when you do not
know in advance how many times to loop.
⯈ Example
1 let count = 1;
2
3 while (count <= 5) {
4 [Link]('Count:', count);
5 count++; // IMPORTANT: update the variable or loop runs forever!
6 }
7 // Output: Count: 1 Count: 2 Count: 3 Count: 4 Count: 5
WARNING Always update the loop variable inside a while loop. Forgetting to do so creates an infinite loop
that crashes your browser.

3. do...while Loop
Definition: do...while Loop — Similar to while, but it always runs the code block AT LEAST ONCE,
even if the condition is false from the start.
⯈ Example
1 let num = 10;
2
3 do {
4 [Link]('Ran once with num =', num);
5 num++;
6 } while (num < 5); // condition is false, but code ran once
7
8 // Output: Ran once with num = 10
4. for...of Loop (ES6)
Definition: for...of — The easiest way to loop through arrays, strings, or any iterable. Directly gives
you the VALUE at each step.
⯈ Loop through Array
1 const colors = ['red', 'green', 'blue'];
2
3 for (const color of colors) {
4 [Link](color);
5 }
6 // Output: red green blue
⯈ Loop through String
1 for (const char of "Hello") {
2 [Link](char);
3 }
4 // Output: H e l l o

5. for...in Loop
Definition: for...in — Loops through the KEYS (property names) of an object.
⯈ Example
1 const student = { name: 'Raj', age: 20, city: 'Delhi' };
2
3 for (const key in student) {
4 [Link](key + ': ' + student[key]);
5 }
6 // Output:
7 // name: Raj
8 // age: 20
9 // city: Delhi

6. break and continue


Definition: break — Exits the loop immediately, even if the condition is still true.
Definition: continue — Skips the current iteration and moves to the next one.
⯈ break Example
1 // Stop when we find 5
2 for (let i = 1; i <= 10; i++) {
3 if (i === 5) break; // exit loop
4 [Link](i);
5 }
6 // Output: 1 2 3 4
⯈ continue Example
1 // Skip even numbers
2 for (let i = 1; i <= 10; i++) {
3 if (i % 2 === 0) continue; // skip even
4 [Link](i);
5 }
6 // Output: 1 3 5 7 9
7. Array Iteration Methods
Modern JavaScript provides built-in methods to loop and transform arrays cleanly.
⯈ forEach — loop without returning anything
1 const nums = [1, 2, 3, 4, 5];
2 [Link](function(n) {
3 [Link](n * 2);
4 });
5 // Output: 2 4 6 8 10
⯈ map — create a new array with transformed values
1 const nums = [1, 2, 3];
2 const doubled = [Link](n => n * 2);
3 [Link](doubled); // [2, 4, 6]
⯈ filter — keep only elements that pass the test
1 const nums = [1, 2, 3, 4, 5, 6];
2 const evens = [Link](n => n % 2 === 0);
3 [Link](evens); // [2, 4, 6]
⯈ reduce — combine all values into one result
1 const nums = [1, 2, 3, 4, 5];
2 const sum = [Link]((total, n) => total + n, 0);
3 [Link](sum); // 15
07. Functions
Definition: Function — A reusable block of code that performs a specific task. Instead of writing the
same code again and again, you define it once in a function and call it whenever needed.

1. Function Declaration
Definition: Function Declaration — The classic way to define a function using the `function` keyword.
It is hoisted, so it can be called even before it is defined.
⯈ Example
1 // Define the function
2 function greet(name) {
3 return "Hello, " + name + "!";
4 }
5
6 // Call the function
7 [Link](greet("Alice")); // Hello, Alice!
8 [Link](greet("Bob")); // Hello, Bob!
Output: Hello, Alice! | Hello, Bob!

2. Function Expression
Definition: Function Expression — A function stored in a variable. It is NOT hoisted, so it must be
defined before calling it.
⯈ Example
1 const square = function(n) {
2 return n * n;
3 };
4
5 [Link](square(4)); // 16
6 [Link](square(7)); // 49

3. Arrow Function (ES6)


Definition: Arrow Function — A shorter, modern way to write functions using the => symbol. Very
popular in modern JavaScript.
⯈ Arrow function syntax
1 // Regular function
2 function add(a, b) { return a + b; }
3
4 // Arrow function (same thing, shorter)
5 const add = (a, b) => a + b;
6
7 [Link](add(3, 4)); // 7
8
9 // Single parameter — no parentheses needed
10 const double = n => n * 2;
11 [Link](double(5)); // 10
12
13 // Multi-line arrow function
14 const multiply = (a, b) => {
15 let result = a * b;
16 return result;
17 };
18 [Link](multiply(3, 4)); // 12

4. Parameters and Arguments


Definition: Parameter — A variable listed in the function definition. It is a placeholder for the value that
will be passed.
Definition: Argument — The actual value you pass to the function when calling it.
⯈ Example
1 // parameter↓ parameter↓
2 function introduce(firstName, lastName) {
3 return `My name is ${firstName} ${lastName}`;
4 }
5
6 // argument↓ argument↓
7 [Link](introduce("John", "Smith"));
8 // My name is John Smith

5. Default Parameters
Definition: Default Parameter — A value used when no argument is provided for that parameter.
⯈ Example
1 function greet(name = "Guest") {
2 return "Hello, " + name;
3 }
4
5 [Link](greet()); // Hello, Guest
6 [Link](greet("Alice")); // Hello, Alice

6. Return Statement
Definition: return — Sends a value back from the function to where it was called. A function stops
running when it hits return.
⯈ Example
1 function isAdult(age) {
2 if (age >= 18) {
3 return true; // stops here if age >= 18
4 }
5 return false; // only reaches here if age < 18
6 }
7
8 [Link](isAdult(20)); // true
9 [Link](isAdult(15)); // false

7. Closures
Definition: Closure — A function that remembers the variables from its outer scope even after the
outer function has finished running.
⯈ Simple Counter using Closure
1 function makeCounter() {
2 let count = 0; // this variable is 'remembered'
3
4 return function() {
5 count++;
6 return count;
7 };
8 }
9
10 const counter = makeCounter();
11 [Link](counter()); // 1
12 [Link](counter()); // 2
13 [Link](counter()); // 3
TIP Closures are used to create private variables and factory functions. This is a very important concept in
JavaScript!

8. Higher-Order Functions
Definition: Higher-Order Function — A function that takes another function as an argument OR
returns a function. This is possible because functions are first-class citizens in JS.
⯈ Example
1 // Takes a function as argument
2 function doTwice(fn, value) {
3 return fn(fn(value));
4 }
5
6 const double = x => x * 2;
7 [Link](doTwice(double, 3)); // 12 (3*2=6, 6*2=12)
08. Arrays
Definition: Array — An ordered list of values stored in a single variable. Each value has a position
number called an index, starting from 0.

1. Creating Arrays
⯈ Example
1 // Array literal — most common way
2 const fruits = ['apple', 'banana', 'mango'];
3 const numbers = [10, 20, 30, 40, 50];
4 const mixed = ['Alice', 25, true, null]; // can mix types
5
6 // Access by index (starts at 0)
7 [Link](fruits[0]); // apple
8 [Link](fruits[1]); // banana
9 [Link](fruits[2]); // mango
10
11 // Length of array
12 [Link]([Link]); // 3

2. Adding & Removing Elements


⯈ Example
1 const arr = [1, 2, 3];
2
3 // Add to END
4 [Link](4);
5 [Link](arr); // [1, 2, 3, 4]
6
7 // Remove from END
8 [Link]();
9 [Link](arr); // [1, 2, 3]
10
11 // Add to BEGINNING
12 [Link](0);
13 [Link](arr); // [0, 1, 2, 3]
14
15 // Remove from BEGINNING
16 [Link]();
17 [Link](arr); // [1, 2, 3]
Method Action Returns
push(item) Add to end New length
pop() Remove from end Removed element
unshift(item) Add to beginning New length
shift() Remove from beginning Removed element
splice(i,n) Remove n elements at index i Removed elements

3. Useful Array Methods


⯈ indexOf — find position of an element
1 const colors = ['red', 'green', 'blue', 'green'];
2 [Link]([Link]('green')); // 1
3 [Link]([Link]('yellow')); // -1 (not found)
⯈ includes — check if element exists
1 const nums = [1, 2, 3, 4, 5];
2 [Link]([Link](3)); // true
3 [Link]([Link](9)); // false
⯈ join — combine array into a string
1 const words = ['Hello', 'World', 'JavaScript'];
2 [Link]([Link](' ')); // Hello World JavaScript
3 [Link]([Link](', ')); // Hello, World, JavaScript
⯈ slice — get a portion of an array (does not change original)
1 const nums = [10, 20, 30, 40, 50];
2 [Link]([Link](1, 4)); // [20, 30, 40]
3 [Link]([Link](2)); // [30, 40, 50]
⯈ sort — sort elements
1 const letters = ['c', 'a', 'b'];
2 [Link]();
3 [Link](letters); // ['a', 'b', 'c']
4
5 // Sort numbers correctly
6 const nums = [40, 10, 30, 20];
7 [Link]((a, b) => a - b); // ascending
8 [Link](nums); // [10, 20, 30, 40]

4. Transform Methods (Very Important!)


⯈ map — create a new array by transforming each element
1 const prices = [100, 200, 300];
2
3 // Apply 10% discount to each price
4 const discounted = [Link](price => price * 0.9);
5 [Link](discounted); // [90, 180, 270]
⯈ filter — create a new array with only matching elements
1 const ages = [15, 22, 17, 30, 13, 25];
2
3 // Keep only adults (18+)
4 const adults = [Link](age => age >= 18);
5 [Link](adults); // [22, 30, 25]
⯈ reduce — calculate a single result from all elements
1 const cart = [500, 200, 150, 300];
2
3 // Calculate total bill
4 const total = [Link]((sum, item) => sum + item, 0);
5 [Link]('Total: Rs.' + total); // Total: Rs.1150
⯈ find — get the first matching element
1 const students = [
2 { name: 'Alice', score: 85 },
3 { name: 'Bob', score: 92 },
4 { name: 'Carol', score: 78 },
5 ];
6
7 const topper = [Link](s => [Link] > 90);
8 [Link](topper); // { name: 'Bob', score: 92 }
09. Objects
Definition: Object — A collection of related data stored as key-value pairs. The key is the property
name and the value is the data. Think of it like a real-world object — a person has a name, age, city,
etc.

1. Creating an Object
⯈ Example
1 // Object literal — most common
2 const person = {
3 name: 'Alice', // key: value
4 age: 25,
5 city: 'Mumbai',
6 isStudent: true,
7 };
8
9 // Access properties
10 [Link]([Link]); // Alice (dot notation)
11 [Link](person['age']); // 25 (bracket notation)

2. Adding, Updating & Deleting Properties


⯈ Example
1 const car = { brand: 'Toyota', model: 'Camry' };
2
3 // Add a new property
4 [Link] = 2023;
5 [Link](car); // { brand: 'Toyota', model: 'Camry', year: 2023 }
6
7 // Update an existing property
8 [Link] = 'Corolla';
9 [Link]([Link]); // Corolla
10
11 // Delete a property
12 delete [Link];
13 [Link]([Link]); // undefined

3. Methods in Objects
Definition: Method — A function stored as a property of an object. It describes what the object can
DO.
⯈ Example
1 const calculator = {
2 // Properties
3 brand: 'Casio',
4
5 // Methods
6 add: function(a, b) {
7 return a + b;
8 },
9 subtract(a, b) { // shorthand method
10 return a - b;
11 }
12 };
13
14 [Link]([Link](5, 3)); // 8
15 [Link]([Link](10, 4)); // 6

4. this Keyword
Definition: this — Inside a method, `this` refers to the object that owns the method. It lets you access
the object's own properties from within its methods.
⯈ Example
1 const student = {
2 name: 'Raj',
3 marks: 85,
4
5 getResult() {
6 // 'this' refers to the student object
7 if ([Link] >= 50) {
8 return [Link] + ' has Passed!';
9 }
10 return [Link] + ' has Failed.';
11 }
12 };
13
14 [Link]([Link]()); // Raj has Passed!

5. Object Methods (Built-in)


⯈ [Link] — get all property names
1 const user = { name: 'Alice', age: 25, city: 'NY' };
2 [Link]([Link](user)); // ['name', 'age', 'city']
⯈ [Link] — get all values
1 [Link]([Link](user)); // ['Alice', 25, 'NY']
⯈ [Link] — get all key-value pairs
1 [Link]([Link](user));
2 // [['name','Alice'], ['age',25], ['city','NY']]
⯈ Spread to copy or merge objects
1 const a = { x: 1, y: 2 };
2 const b = { z: 3 };
3
4 const copy = { ...a }; // copy object a
5 const merged = { ...a, ...b }; // merge a and b
6 [Link](merged); // { x:1, y:2, z:3 }

6. Classes (Blueprint for Objects)


Definition: Class — A template or blueprint for creating objects. Defined using the `class` keyword.
Objects created from a class are called instances.
⯈ Simple Class
1 class Animal {
2 constructor(name, sound) {
3 [Link] = name; // set property
4 [Link] = sound;
5 }
6
7 speak() {
8 return [Link] + ' says ' + [Link];
9 }
10 }
11
12 // Create instances from the class
13 const dog = new Animal('Dog', 'Woof');
14 const cat = new Animal('Cat', 'Meow');
15
16 [Link]([Link]()); // Dog says Woof
17 [Link]([Link]()); // Cat says Meow
⯈ Inheritance — extend a class
1 class Dog extends Animal {
2 constructor(name) {
3 super(name, 'Woof'); // call parent class
4 }
5
6 fetch() {
7 return [Link] + ' fetches the ball!';
8 }
9 }
10
11 const rex = new Dog('Rex');
12 [Link]([Link]()); // Rex says Woof
13 [Link]([Link]()); // Rex fetches the ball!
10. Document Object Model (DOM)
Definition: DOM (Document Object Model) — A programming interface that represents the HTML
page as a tree of nodes/objects. JavaScript can use the DOM to read, change, add, or delete elements
on the page — making web pages interactive.

The DOM Tree


When a browser loads an HTML page, it creates a tree structure like this:
1 // HTML structure:
2 // <html>
3 // <head> <title>Page</title> </head>
4 // <body>
5 // <h1 id='title'>Hello</h1>
6 // <p class='intro'>Welcome</p>
7 // </body>
8 // </html>
9
10 // document is the root — it represents the whole page
11 // [Link] is the <body> element
12 // [Link] is the <head> element

1. Selecting Elements
Definition: Selecting — Finding an HTML element using JavaScript so you can read or change it.
⯈ Common selection methods
1 // Select by ID — returns ONE element
2 const title = [Link]("title");
3
4 // Select by CSS selector — returns FIRST match
5 const para = [Link]("p");
6 const btn = [Link](".btn");
7 const header = [Link]("#header");
8
9 // Select ALL matching elements
10 const allParas = [Link]("p");
11 const allCards = [Link](".card");
12
13 // Loop through all selected elements
14 [Link](para => {
15 [Link]([Link]);
16 });

2. Reading & Changing Content


⯈ Example
1 // HTML: <h1 id="title">Old Text</h1>
2
3 const h1 = [Link]("title");
4
5 // Read text
6 [Link]([Link]); // Old Text
7
8 // Change text (safe — no HTML tags)
9 [Link] = "New Text";
10
11 // Change with HTML tags
12 [Link] = "<em>Italic Text</em>";
WARNING Use textContent when setting plain text. Use innerHTML only when you need to insert HTML
tags, and NEVER put user input into innerHTML — it is a security risk (XSS attack).

3. Changing Styles
⯈ Example
1 const box = [Link](".box");
2
3 // Change CSS style directly
4 [Link] = 'blue';
5 [Link] = '200px';
6 [Link] = '20px';
7
8 // Better way — use CSS classes
9 [Link]('active'); // add a class
10 [Link]('hidden'); // remove a class
11 [Link]('highlight'); // add if missing, remove if present
12 [Link]('active'); // returns true or false

4. Creating & Inserting Elements


⯈ Add a new list item
1 // Step 1: Create the element
2 const li = [Link]('li');
3
4 // Step 2: Set its content
5 [Link] = 'New Item';
6
7 // Step 3: Add it to the page
8 const ul = [Link]("ul");
9 [Link](li); // add at END
10 [Link](li); // add at BEGINNING
11
12 // Quick way using innerHTML
13 [Link]('beforeend', '<li>Quick Item</li>');

5. Removing Elements
⯈ Example
1 const item = [Link](".item");
2
3 // Modern way
4 [Link]();
5
6 // Old way (remove a child from its parent)
7 [Link](item);
6. Working with Attributes
⯈ Example
1 // HTML: <img id='photo' src='[Link]' alt='A photo'>
2
3 const img = [Link]("photo");
4
5 // Read attribute
6 [Link]([Link]('src')); // [Link]
7
8 // Set attribute
9 [Link]('src', '[Link]');
10
11 // Remove attribute
12 [Link]('alt');
13
14 // data-* attributes
15 // HTML: <div data-user-id='42'>
16 const div = [Link]('div');
17 [Link]([Link]); // '42'
11. Events
Definition: Event — An action that happens in the browser — like a user clicking a button, typing in a
field, or moving the mouse. JavaScript can 'listen' for these events and run code when they happen.

1. Adding Event Listeners


Definition: addEventListener — The method to attach an event handler to an element. It takes the
event name and a function to run when the event fires.
⯈ Click Event
1 // HTML: <button id="myBtn">Click Me</button>
2
3 const btn = [Link]("myBtn");
4
5 [Link]('click', function() {
6 [Link]("Button was clicked!");
7 });
8
9 // Using arrow function (shorter)
10 [Link]('click', () => {
11 alert("You clicked the button!");
12 });

2. Common Event Types


Category Events When They Fire
Mouse click, dblclick, mouseover, User clicks or moves mouse over element
mouseout
Keyboard keydown, keyup User presses or releases a key
Form submit, change, input, focus, User interacts with form elements
blur
Window load, DOMContentLoaded, Page loads, resizes, or scrolls
resize, scroll
Touch touchstart, touchend, User touches screen (mobile)
touchmove

3. The Event Object


Definition: Event Object — When an event fires, JavaScript automatically passes an event object
(usually called e or event) to your handler. It contains useful information about the event.
⯈ Example
1 [Link]('click', function(e) {
2 [Link]([Link]); // 'click' — type of event
3 [Link]([Link]); // the element that was clicked
4 [Link]([Link]); // mouse X position on screen
5 [Link]([Link]); // mouse Y position on screen
6 });
7
8 // Keyboard event
9 [Link]('keydown', function(e) {
10 [Link]([Link]); // 'a', 'Enter', 'ArrowUp'...
11 [Link]([Link]); // true if Ctrl was held
12 });

4. preventDefault()
Definition: preventDefault() — Stops the browser's default action for an event. For example, it stops a
form from submitting or a link from navigating.
⯈ Stop form from submitting
1 // HTML: <form id="myForm"> <button type="submit">Submit</button> </form>
2
3 const form = [Link]("myForm");
4
5 [Link]('submit', function(e) {
6 [Link](); // stops the page from reloading
7 [Link]("Form submitted without page reload!");
8 // Now you can validate and send data manually
9 });

5. Event Bubbling
Definition: Event Bubbling — When an event fires on an element, it also fires on all its parent
elements, bubbling up to the top. Like a bubble rising through water.
⯈ Example
1 // HTML: <div id='parent'> <button id='child'>Click</button> </div>
2
3 [Link]("child").addEventListener("click", () => {
4 [Link]("Child clicked");
5 });
6
7 [Link]("parent").addEventListener("click", () => {
8 [Link]("Parent also fires!");
9 });
10
11 // Clicking the button outputs:
12 // Child clicked
13 // Parent also fires! (due to bubbling)
14
15 // Stop bubbling with stopPropagation()
16 [Link]("child").addEventListener("click", (e) => {
17 [Link](); // parent won't fire
18 [Link]("Only child fires");
19 });

6. Event Delegation
Definition: Event Delegation — Instead of adding listeners to every child element, add ONE listener
to the parent. It uses bubbling to catch events from children. Great for dynamic content.
⯈ Example
1 // HTML: <ul id="list"> <li>Item 1</li> <li>Item 2</li> </ul>
2
3 // Add ONE listener to the parent ul
4 const list = [Link]("list");
5
6 [Link]('click', function(e) {
7 // Check if a li was clicked
8 if ([Link] === 'LI') {
9 [Link]('You clicked:', [Link]);
10 [Link] = 'red';
11 }
12 });
13
14 // This even works for li elements added later!
12. ES6+ Modern JavaScript Features
Definition: ES6 (ECMAScript 2015) — A major update to JavaScript released in 2015 that added
many powerful features. It is the most important JavaScript upgrade. Features like let, const, arrow
functions, and Promises all came from ES6.

1. Template Literals
Definition: Template Literal — A better way to write strings using backticks (`). You can embed
expressions inside ${} and write multi-line strings easily.
⯈ Example
1 const name = "Alice";
2 const score = 95;
3
4 // Old way:
5 const msg1 = "Hello " + name + "! Your score is " + score;
6
7 // New way with template literal:
8 const msg2 = `Hello ${name}! Your score is ${score}.`;
9 [Link](msg2); // Hello Alice! Your score is 95.
10
11 // Multi-line string
12 const poem = `Roses are red,
13 Violets are blue,
14 JavaScript is fun,
15 And so are you!`;
16 [Link](poem);

2. Spread Operator (...)


Definition: Spread Operator — Expands an array or object into individual elements. Use it to copy,
merge, or pass elements.
⯈ Spread with Arrays
1 const a = [1, 2, 3];
2 const b = [4, 5, 6];
3
4 // Merge arrays
5 const merged = [...a, ...b];
6 [Link](merged); // [1, 2, 3, 4, 5, 6]
7
8 // Copy an array
9 const copy = [...a];
10 [Link](99);
11 [Link](a); // [1, 2, 3] — original unchanged
12 [Link](copy); // [1, 2, 3, 99]
⯈ Spread with Objects
1 const user = { name: "Alice", age: 25 };
2 const address = { city: "Mumbai", zip: "400001" };
3
4 const profile = { ...user, ...address };
5 [Link](profile);
6 // { name: 'Alice', age: 25, city: 'Mumbai', zip: '400001' }
3. Rest Parameter (...)
Definition: Rest Parameter — Collects multiple arguments into a single array. Always the LAST
parameter in a function.
⯈ Example
1 function sum(...numbers) {
2 return [Link]((total, n) => total + n, 0);
3 }
4
5 [Link](sum(1, 2, 3)); // 6
6 [Link](sum(1, 2, 3, 4, 5)); // 15
7 [Link](sum(10, 20)); // 30
TIP Spread EXPANDS an array. Rest COLLECTS values into an array. Same symbol (...) but opposite jobs!

4. Modules (import / export)


Definition: Module — A JavaScript file that can export values (functions, variables, classes) and
import them in other files. Keeps code organised and reusable.
⯈ [Link] — exporting
1 // Named exports
2 export const PI = 3.14159;
3 export function add(a, b) { return a + b; }
4 export function multiply(a, b) { return a * b; }
⯈ [Link] — importing
1 // Import specific things
2 import { PI, add, multiply } from './[Link]';
3
4 [Link](PI); // 3.14159
5 [Link](add(5, 3)); // 8
6 [Link](multiply(4,5));// 20
7
8 // Import everything
9 import * as math from './[Link]';
10 [Link]([Link](1, 2)); // 3

5. Map and Set


Map
Definition: Map — Like an object, but keys can be of ANY type (not just strings). Maintains insertion
order and has a size property.
⯈ Example
1 const map = new Map();
2
3 [Link]('name', 'Alice'); // string key
4 [Link](1, 'first'); // number key
5 [Link](true, 'yes'); // boolean key
6
7 [Link]([Link]('name')); // Alice
8 [Link]([Link]); // 3
9 [Link]([Link](1)); // true
10
11 // Loop through Map
12 for (const [key, value] of map) {
13 [Link](key, '->', value);
14 }

Set
Definition: Set — A collection of UNIQUE values. Duplicates are automatically removed.
⯈ Example
1 const set = new Set([1, 2, 3, 2, 1, 3]);
2 [Link]([Link]); // 3 (duplicates removed)
3 [Link]([...set]); // [1, 2, 3]
4
5 // Real use case: remove duplicates from array
6 const arr = [5, 3, 5, 1, 3, 2];
7 const unique = [...new Set(arr)];
8 [Link](unique); // [5, 3, 1, 2]
13. Asynchronous JavaScript
Definition: Asynchronous — Code that runs independently without blocking other code. Instead of
waiting for a slow task (like loading data from a server), JavaScript starts it and moves on, then handles
the result when it is ready.

Synchronous vs Asynchronous
⯈ Synchronous (blocking) — one by one
1 [Link]('Step 1');
2 [Link]('Step 2');
3 [Link]('Step 3');
4 // Output: Step 1 Step 2 Step 3 (in order)
⯈ Asynchronous — non-blocking
1 [Link]('Step 1');
2
3 setTimeout(() => {
4 [Link]('Step 2 — after 2 seconds');
5 }, 2000);
6
7 [Link]('Step 3 — runs immediately');
8
9 // Output:
10 // Step 1
11 // Step 3 (does not wait!)
12 // Step 2 (appears 2 seconds later)

The Event Loop (How JS handles async)


JavaScript has one thread but handles async using the Event Loop:
● Call Stack — where your code runs, one function at a time
● Web APIs — browser handles slow tasks (timers, fetch, events)
● Callback Queue — holds callbacks waiting to run
● Event Loop — constantly checks: is stack empty? Move callback from queue to stack!

1. Callbacks
Definition: Callback — A function passed as an argument to another function, to be called later when
a task completes.
⯈ Simple callback
1 function downloadFile(url, onComplete) {
2 [Link]('Downloading...');
3 setTimeout(() => {
4 // After 2 seconds, call the callback with the result
5 onComplete('File downloaded!');
6 }, 2000);
7 }
8
9 downloadFile('[Link]/file', function(result) {
10 [Link](result); // File downloaded!
11 });
12
13 [Link]('This runs while downloading...');
WARNING Nesting many callbacks creates 'Callback Hell' — deeply indented code that is hard to read. Use
Promises or async/await instead.

2. setTimeout & setInterval


⯈ setTimeout — run ONCE after a delay
1 // Run after 3 seconds
2 const id = setTimeout(() => {
3 [Link]("This ran after 3 seconds!");
4 }, 3000);
5
6 // Cancel it (before it fires)
7 clearTimeout(id);
⯈ setInterval — run REPEATEDLY
1 let count = 0;
2
3 // Run every 1 second
4 const id = setInterval(() => {
5 count++;
6 [Link]('Tick:', count);
7
8 if (count === 5) {
9 clearInterval(id); // stop after 5 times
10 }
11 }, 1000);
12 // Output: Tick: 1 Tick: 2 Tick: 3 Tick: 4 Tick: 5

3. async / await (The Modern Way)


Definition: async — Put before a function to make it asynchronous. An async function always returns
a Promise.
Definition: await — Put before a Promise to pause the async function until the Promise resolves.
Makes async code look like synchronous code.
⯈ Simple async/await
1 // This simulates fetching data (takes 2 seconds)
2 function loadData() {
3 return new Promise(resolve => {
4 setTimeout(() => {
5 resolve({ name: 'Alice', age: 25 });
6 }, 2000);
7 });
8 }
9
10 async function main() {
11 [Link]('Loading...');
12
13 const data = await loadData(); // wait until done
14
15 [Link]('Done!', data); // { name: 'Alice', age: 25 }
16 }
17
18 main();
⯈ Error handling with try/catch
1 async function fetchUser() {
2 try {
3 const response = await fetch('/api/user');
4 const user = await [Link]();
5 return user;
6 } catch (error) {
7 [Link]('Error:', [Link]);
8 }
9 }
14. Promises
Definition: Promise — An object representing a future value that is not available yet. Like ordering
food — you get a 'token' (promise) now, and the food (value) arrives later. A Promise has 3 states:
Pending, Fulfilled, and Rejected.

Promise States
State Meaning Next Step
Pending The operation is still in progress Wait...
Fulfilled The operation completed successfully .then() runs
Rejected The operation failed .catch() runs

Creating a Promise
⯈ Example
1 const promise = new Promise((resolve, reject) => {
2 // Do some async work...
3 const success = true;
4
5 if (success) {
6 resolve('Data loaded!'); // fulfilled
7 } else {
8 reject('Error occurred!'); // rejected
9 }
10 });
11
12 // Use the promise
13 promise
14 .then(result => [Link](result)) // Data loaded!
15 .catch(error => [Link](error)) // Error occurred!
16 .finally(() => [Link]('Done')); // always runs

Real-World Promise Example


⯈ Simulate API call
1 function getUser(id) {
2 return new Promise((resolve, reject) => {
3 setTimeout(() => {
4 if (id > 0) {
5 resolve({ id: id, name: 'Alice' });
6 } else {
7 reject(new Error('Invalid ID'));
8 }
9 }, 1000);
10 });
11 }
12
13 getUser(1)
14 .then(user => [Link]('User:', [Link])) // User: Alice
15 .catch(err => [Link]([Link]));
Promise Chaining
Definition: Promise Chaining — Connecting multiple .then() calls to handle a sequence of async
operations, one after another.
⯈ Example
1 getUser(1)
2 .then(user => {
3 [Link]('Got user:', [Link]);
4 return getPosts([Link]); // return ANOTHER promise
5 })
6 .then(posts => {
7 [Link]('Got posts:', [Link]);
8 return getComments(posts[0].id); // another promise
9 })
10 .then(comments => {
11 [Link]('Got comments:', [Link]);
12 })
13 .catch(error => {
14 // ONE catch handles errors from ALL the steps above
15 [Link]('Something failed:', [Link]);
16 });

[Link] — Run Multiple at Once


Definition: [Link] — Runs multiple Promises at the same time (parallel). Waits for ALL of them to
complete. If ONE fails, the whole thing fails.
⯈ Example
1 const getUsers = fetch('/api/users').then(r => [Link]());
2 const getPosts = fetch('/api/posts').then(r => [Link]());
3 const getComments = fetch('/api/comments').then(r => [Link]());
4
5 // Run all three at the same time
6 [Link]([getUsers, getPosts, getComments])
7 .then(([users, posts, comments]) => {
8 [Link]('Users:', [Link]);
9 [Link]('Posts:', [Link]);
10 [Link]('Comments:', [Link]);
11 })
12 .catch(err => [Link]('One request failed:', err));

Other Promise Methods


Method What it does
[Link]([]) Wait for ALL to succeed. Fails if any one fails.
[Link]([]) Wait for ALL, get each result (success or fail). Never rejects.
[Link]([]) Resolves/rejects with the FIRST Promise that settles.
[Link]([]) Resolves with the FIRST Promise that SUCCEEDS. Ignores
rejections.

⯈ [Link] — always see all results


1 [Link]([
2 [Link]('ok'),
3 [Link]('error'),
4 [Link]('also ok'),
5 ]).then(results => {
6 [Link](r => {
7 if ([Link] === 'fulfilled') {
8 [Link]('Success:', [Link]);
9 } else {
10 [Link]('Failed:', [Link]);
11 }
12 });
13 });
15. Fetch API
Definition: Fetch API — A modern, built-in browser API for making HTTP requests (getting or sending
data) to a server. It returns a Promise. It replaced the older XMLHttpRequest.

How HTTP Requests Work


● Your browser sends a REQUEST to a server (like asking a waiter for food)
● The server processes it and sends back a RESPONSE (the waiter brings your food)
● The response has a status code: 200 = OK, 404 = Not Found, 500 = Server Error
● The response body contains the actual data (usually JSON format)

1. GET Request — Fetch Data


Definition: GET Request — Used to retrieve/read data from a server. The most common type of
request.
⯈ Simple GET
1 // fetch() returns a Promise
2 fetch('[Link]
3 .then(response => {
4 [Link]([Link]); // 200
5 [Link]([Link]); // true
6 return [Link](); // parse JSON body
7 })
8 .then(user => {
9 [Link]([Link]); // Leanne Graham
10 })
11 .catch(error => {
12 [Link]('Error:', error);
13 });
⯈ GET with async/await (cleaner)
1 async function getUser(id) {
2 const response = await fetch(
3 `[Link]
4 );
5
6 if (![Link]) {
7 throw new Error('Failed! Status: ' + [Link]);
8 }
9
10 const user = await [Link]();
11 [Link]('Name:', [Link]);
12 [Link]('Email:', [Link]);
13 }
14
15 getUser(1); // Call the function

2. POST Request — Send Data


Definition: POST Request — Used to CREATE/send new data to a server (like submitting a form or
creating a new account).
⯈ Example
1 async function createPost(data) {
2 const response = await fetch(
3 '[Link]
4 {
5 method: 'POST', // HTTP method
6 headers: {
7 'Content-Type': 'application/json', // tell server we send JSON
8 },
9 body: [Link](data), // convert object to JSON string
10 }
11 );
12
13 const newPost = await [Link]();
14 [Link]('Created post with ID:', [Link]);
15 }
16
17 createPost({
18 title: 'My First Post',
19 body: 'This is the content.',
20 userId: 1,
21 });

3. PUT & PATCH — Update Data


⯈ PUT — replace entire resource
1 async function updatePost(id, newData) {
2 const response = await fetch(
3 `[Link]
4 {
5 method: 'PUT',
6 headers: { 'Content-Type': 'application/json' },
7 body: [Link](newData),
8 }
9 );
10 return [Link]();
11 }
⯈ PATCH — update only specific fields
1 async function patchPost(id, fields) {
2 const response = await fetch(
3 `[Link]
4 {
5 method: 'PATCH',
6 headers: { 'Content-Type': 'application/json' },
7 body: [Link](fields), // only the changed fields
8 }
9 );
10 return [Link]();
11 }
12
13 // Only update the title, leave body unchanged
14 patchPost(1, { title: 'Updated Title' });

4. DELETE Request — Remove Data


⯈ Example
1 async function deletePost(id) {
2 const response = await fetch(
3 `[Link]
4 { method: 'DELETE' }
5 );
6
7 if ([Link]) {
8 [Link]('Post deleted successfully!');
9 }
10 }
11
12 deletePost(1);

5. HTTP Methods Summary


Method Purpose Example Use
GET Read data Get user profile, get list of products
POST Create new data Sign up, create a new post
PUT Replace entire record Update entire user profile
PATCH Update part of record Change just the password
DELETE Remove data Delete an account or post

6. Handling Response Types


⯈ Example
1 const res = await fetch('/api/endpoint');
2
3 [Link](); // Parse as JSON object (most common)
4 [Link](); // Parse as plain text
5 [Link](); // Parse as file/image data
6 [Link](); // Parse as raw binary
7
8 // Response info
9 [Link]; // 200, 404, 500...
10 [Link]; // true if status is 200-299
11 [Link]; // response headers

7. Complete Working Example — Todo App API


⯈ Full CRUD for todos
1 const BASE = '[Link]
2
3 // READ all todos
4 async function getAllTodos() {
5 const res = await fetch(`${BASE}/todos`);
6 const todos = await [Link]();
7 [Link]('Total todos:', [Link]);
8 }
9
10 // CREATE a new todo
11 async function addTodo(title) {
12 const res = await fetch(`${BASE}/todos`, {
13 method: 'POST',
14 headers: { 'Content-Type': 'application/json' },
15 body: [Link]({ title, completed: false, userId: 1 })
16 });
17 const todo = await [Link]();
18 [Link]('New todo created, ID:', [Link]);
19 }
20
21 // UPDATE a todo
22 async function completeTodo(id) {
23 const res = await fetch(`${BASE}/todos/${id}`, {
24 method: 'PATCH',
25 headers: { 'Content-Type': 'application/json' },
26 body: [Link]({ completed: true })
27 });
28 const todo = await [Link]();
29 [Link]('Todo updated:', [Link]);
30 }
31
32 // DELETE a todo
33 async function removeTodo(id) {
34 await fetch(`${BASE}/todos/${id}`, { method: 'DELETE' });
35 [Link](`Todo ${id} removed!`);
36 }
37
38 // Run all operations
39 async function demo() {
40 await getAllTodos();
41 await addTodo('Learn JavaScript!');
42 await completeTodo(1);
43 await removeTodo(1);
44 }
45
46 demo();

COLLEGE CODERS | JavaScript Complete Notes


Learn Step by Step. Practice Every Day. Build Something Amazing.
[Link]

You might also like