[Go to site: main page, start]

0% found this document useful (0 votes)
2 views30 pages

JavaScript Complete Course Notes

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)
2 views30 pages

JavaScript Complete Course Notes

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

JS

JavaScript
Complete Course Notes

Syntax • Definitions • Examples

• Variables & Data Types • Control Flow & Loops • Functions & Scope

• Arrays & Strings • Objects & DOM • Events & ES6+

• Async JS & Promises • OOP & Classes • APIs & Storage

18 Chapters • 30 Pages • Beginner to Intermediate

JavaScript Complete Course Notes Page 1


Table of Contents
1. Introduction to JavaScript
— What is JS?
— Features
— Client vs Server-side
— Execution
2. JavaScript Basics
— Variables
— Data Types
— Operators
3. Input and Output
— alert()
— prompt()
— confirm()
— [Link]()
4. Control Statements
— if / else / else if
— switch
— Nested Conditions
5. Loops
— for, while, do...while
— for...in, for...of
— Break & Continue
6. Functions
— Declaration & Expression
— Arrow Functions
— Callbacks & Recursion
7. Arrays
— Array Methods
— map / filter / reduce / forEach
8. Strings
— String Methods
— Template Literals
— Search & Manipulation
9. Objects
— Properties & Methods
— Destructuring
— Spread
— Object Methods
10. DOM
— Selecting Elements
— Modifying Content & Styles
— Create & Remove
11. Events
— Click, Keyboard, Mouse
— Form Events
— Bubbling & Capturing
12. ES6 Features
— let/const, Arrow Fns
— Destructuring, Spread
— Modules & Classes

JavaScript Complete Course Notes Page 2


13. Asynchronous JavaScript
— Callbacks & Promises
— async/await
— Fetch API
14. Error Handling
— try / catch / finally
— throw
15. OOP in JavaScript
— Classes, Constructors
— Inheritance
— Encapsulation & Polymorphism
16. Browser Storage
— Cookies
— localStorage
— sessionStorage
17. AJAX & APIs
— AJAX
— JSON
— REST API
— Fetch & Integration

JavaScript Complete Course Notes Page 3


Chapter 1 | Introduction to JavaScript

1.1 What is JavaScript?


JavaScript (JS) is a lightweight, interpreted, high-level programming language primarily used to
make web pages interactive. It is one of the three core technologies of the web alongside HTML
and CSS.

JavaScript was created by Brendan Eich in 1995 in just 10 days. It originally ran only in
browsers but now runs on servers ([Link]), mobile apps, and IoT devices.

1.2 Features of JavaScript


• Interpreted: No compilation needed; code runs line by line.
• Dynamically Typed: Variable types are determined at runtime.
• Event-Driven: Responds to user interactions like clicks and keystrokes.
• Prototype-based OOP: Inheritance works through prototypes, not classical classes.
• First-class Functions: Functions can be stored in variables and passed as arguments.
• Single-threaded: Runs on a single thread using an event loop for concurrency.

1.3 Client-side vs Server-side JavaScript


Client-side Server-side

Runs in the browser Runs on [Link] server

Manipulates DOM Handles HTTP requests

No file system access Full file system access

Example: React, Vue Example: [Link]

1.4 JavaScript Execution


Browsers use a JavaScript engine to execute code. Popular engines include V8
(Chrome/[Link]), SpiderMonkey (Firefox), and JavaScriptCore (Safari). JS can be embedded in
HTML using the <script> tag.

Syntax:

<!-- Inline Script -->


<script>
[Link]("Hello, JavaScript!");
</script>

<!-- External Script -->


<script src="[Link]"></script>

JavaScript Complete Course Notes Page 4


Chapter 2 | JavaScript Basics

2.1 Variables
Variables store data values. JavaScript has three ways to declare variables:

Keyword Scope Reassignable Hoisted

var Function Yes Yes (undefined)

let Block Yes No (TDZ)

const Block No No (TDZ)

Example:

var name = "Alice"; // function-scoped


let age = 25; // block-scoped, reassignable
const PI = 3.14159; // block-scoped, constant

age = 26; // OK
// PI = 3; // Error: Assignment to constant

2.2 Data Types


JavaScript has 8 data types — 7 primitive and 1 non-primitive (Object).

Number — Integers and floats


let x = 42; let pi = 3.14;

String — Text data


let s = "Hello"; let t = 'World';

Boolean — true or false


let flag = true;

Undefined — Declared but not assigned


let x; // undefined

Null — Intentional empty value


let val = null;

BigInt — Very large integers


let big = 9007199254740991n;

Symbol — Unique identifiers


let sym = Symbol("id");

JavaScript Complete Course Notes Page 5


Object — Key-value pairs, Arrays, Functions
let obj = { a: 1 };

2.3 Operators
Arithmetic Operators: + (add) | - (subtract) | * (multiply) | / (divide)
Comparison Operators: == (loose equal) | === (strict equal) | != (not equal) | !== (strict not
equal)
Logical Operators: && (AND) | || (OR) | ! (NOT)
Assignment Operators: = (assign) | += -= *= /= | ++ (increment) | -- (decrement)
Example:

let a = 10, b = 3;
[Link](a + b); // 13
[Link](a % b); // 1
[Link](a === 10); // true
[Link](a > b && b > 0); // true
a += 5; [Link](a); // 15

JavaScript Complete Course Notes Page 6


Chapter 3 | Input and Output

3.1 alert()
Displays a message box to the user. Used for simple notifications.

alert("Welcome to JavaScript!");

3.2 prompt()
Displays a dialog box asking the user for input. Returns the input as a string (or null if
cancelled).

let name = prompt("Enter your name:");


alert("Hello, " + name + "!");

3.3 confirm()
Shows a dialog with OK and Cancel buttons. Returns true (OK) or false (Cancel).

let result = confirm("Do you want to proceed?");


if (result) {
[Link]("User clicked OK");
} else {
[Link]("User cancelled");
}

3.4 [Link]()
Prints output to the browser's developer console. Essential for debugging.

[Link]("Simple text");
[Link](42, true, [1, 2, 3]);
[Link]("This is an error");
[Link]("This is a warning");
[Link]([{name:"Alice", age:25}, {name:"Bob", age:30}]);

JavaScript Complete Course Notes Page 7


Chapter 4 | Control Statements

4.1 if Statement
Executes a block of code if the specified condition is true.

let score = 75;


if (score >= 50) {
[Link]("Pass");
}

4.2 if...else Statement


let age = 17;
if (age >= 18) {
[Link]("Adult");
} else {
[Link]("Minor");
}

4.3 else if (Multiple Conditions)


let marks = 82;
if (marks >= 90) {
[Link]("Grade: A");
} else if (marks >= 75) {
[Link]("Grade: B");
} else if (marks >= 60) {
[Link]("Grade: C");
} else {
[Link]("Grade: F");
}

4.4 switch Statement


Tests a variable against multiple values using case labels. More readable than multiple else-if
chains.

let day = "Monday";


switch (day) {
case "Monday":
[Link]("Start of work week");
break;
case "Friday":
[Link]("End of work week");
break;
case "Saturday":
case "Sunday":
[Link]("Weekend!");
break;
default:
[Link]("Midweek day");
}

JavaScript Complete Course Notes Page 8


4.5 Nested Conditions
let num = 15;
if (num > 0) {
if (num % 2 === 0) {
[Link]("Positive even");
} else {
[Link]("Positive odd"); // Output: Positive odd
}
} else {
[Link]("Non-positive");
}

JavaScript Complete Course Notes Page 9


Chapter 5 | Loops

5.1 for Loop


Repeats a block of code a fixed number of times. Syntax: for(init; condition; update)

for (let i = 1; i <= 5; i++) {


[Link]("Count: " + i);
}
// Output: Count: 1, Count: 2, ... Count: 5

5.2 while Loop


Runs as long as the condition is true. Check happens before each iteration.

let n = 1;
while (n <= 5) {
[Link](n);
n++;
}

5.3 do...while Loop


Executes the block at least once before checking the condition.

let i = 0;
do {
[Link]("Value: " + i);
i++;
} while (i < 3);
// Runs even if i starts at 100

5.4 for...in Loop


Iterates over the enumerable properties (keys) of an object.

const person = { name: "Alice", age: 25, city: "Chennai" };


for (let key in person) {
[Link](key + ": " + person[key]);
}
// name: Alice / age: 25 / city: Chennai

5.5 for...of Loop


Iterates over iterable values (arrays, strings, sets, maps).

const fruits = ["apple", "banana", "cherry"];


for (let fruit of fruits) {
[Link](fruit);
}

5.6 Break and Continue

JavaScript Complete Course Notes Page 10


// break - exits the loop entirely
for (let i = 0; i < 10; i++) {
if (i === 5) break;
[Link](i); // 0 1 2 3 4
}

// continue - skips current iteration


for (let i = 0; i < 6; i++) {
if (i % 2 === 0) continue;
[Link](i); // 1 3 5
}

JavaScript Complete Course Notes Page 11


Chapter 6 | Functions

6.1 Function Declaration


A named function that is hoisted — it can be called before its definition in the code.

function greet(name) {
return "Hello, " + name + "!";
}
[Link](greet("Harini")); // Hello, Harini!

6.2 Function Expression


A function assigned to a variable. Not hoisted — must be defined before use.

const square = function(x) {


return x * x;
};
[Link](square(5)); // 25

6.3 Arrow Functions (ES6)


Shorter syntax for functions. Does not have its own 'this' context.

const add = (a, b) => a + b;


[Link](add(3, 4)); // 7

const double = n => n * 2;


[Link](double(6)); // 12

const sayHi = () => [Link]("Hi!");

6.4 Parameters, Arguments & Return


// Default parameters
function power(base, exp = 2) {
return base ** exp;
}
[Link](power(3)); // 9 (uses default exp=2)
[Link](power(2, 10)); // 1024

6.5 Callback Functions


A function passed as an argument to another function to be executed later.

function doMath(a, b, operation) {


return operation(a, b);
}
const multiply = (x, y) => x * y;
[Link](doMath(4, 5, multiply)); // 20

6.6 Recursion
A function that calls itself to solve smaller sub-problems.

JavaScript Complete Course Notes Page 12


function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
[Link](factorial(5)); // 120

JavaScript Complete Course Notes Page 13


Chapter 7 | Arrays

7.1 Creating Arrays


const nums = [1, 2, 3, 4, 5];
const mixed = [42, "hello", true, null];
const empty = [];
const matrix = [[1,2],[3,4],[5,6]]; // 2D array

7.2 Array Methods — Mutating


let arr = [1, 2, 3];
[Link](4); // [1, 2, 3, 4] — add to end
[Link](); // [1, 2, 3] — remove from end
[Link](0); // [0, 1, 2, 3] — add to start
[Link](); // [1, 2, 3] — remove from start

// splice(start, deleteCount, ...items)


[Link](1, 1, 9); // [1, 9, 3] — replace index 1

// slice(start, end) — non-mutating


let sub = [Link](0, 2); // [1, 9]

let a = [1,2]; let b = [3,4];


let c = [Link](b); // [1, 2, 3, 4]

let words = ["banana","apple","cherry"];


[Link](); // ["apple","banana","cherry"]
[Link](); // ["cherry","banana","apple"]

7.3 Array Iteration Methods


const numbers = [1, 2, 3, 4, 5];

// map() — returns new array with transformed values


const doubled = [Link](n => n * 2);
// [2, 4, 6, 8, 10]

// filter() — returns elements that pass a test


const evens = [Link](n => n % 2 === 0);
// [2, 4]

// reduce() — accumulates to a single value


const sum = [Link]((acc, n) => acc + n, 0);
// 15

// forEach() — iterates, returns nothing


[Link](n => [Link](n));

JavaScript Complete Course Notes Page 14


Chapter 8 | Strings

8.1 String Methods


let str = " Hello, JavaScript! ";

[Link] // 22
[Link]() // " HELLO, JAVASCRIPT! "
[Link]() // " hello, javascript! "
[Link]() // "Hello, JavaScript!"
[Link]() // "Hello, JavaScript! "
[Link]("Java") // true
[Link](" He") // true
[Link]("! ") // true
[Link]("Java") // 9
[Link](2, 7) // "Hello"
[Link]("Hello", "Hi") // " Hi, JavaScript! "
[Link](", ") // [" Hello", "JavaScript! "]
"ha".repeat(3) // "hahaha"
"5".padStart(4, "0") // "0005"

8.2 Template Literals


Use backticks (`) for multi-line strings and embedded expressions with ${expression}.

const name = "Harini";


const score = 95;
const msg = `Student: ${name}, Score: ${score}/100`;
[Link](msg); // Student: Harini, Score: 95/100

// Multi-line string
const poem = `Line 1
Line 2
Line 3`;

8.3 String Search Methods


let text = "The rain in Spain stays in the plain";

[Link]("Spain") // 12
[Link](/in/g) // ["in", "in", "in"]
[Link](/in/g) // iterator of all matches
[Link]("in", "XX") // replaces all occurrences

JavaScript Complete Course Notes Page 15


Chapter 9 | Objects

9.1 Creating Objects


// Object literal
const person = {
name: "Alice",
age: 30,
greet() {
return `Hi, I am ${[Link]}`;
}
};
[Link]([Link]); // Alice
[Link](person["age"]); // 30
[Link]([Link]()); // Hi, I am Alice

9.2 Object Destructuring


const { name, age } = person;
[Link](name); // Alice

// With renaming
const { name: fullName, age: years } = person;

// Default values
const { city = "Unknown" } = person;
[Link](city); // Unknown

9.3 Spread Operator


const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const merged = { ...obj1, ...obj2 };
// { a:1, b:2, c:3, d:4 }

// Clone an object
const clone = { ...obj1 };

9.4 Built-in Object Methods


const car = { brand: "Toyota", year: 2022, color: "red" };

[Link](car) // ["brand", "year", "color"]


[Link](car) // ["Toyota", 2022, "red"]
[Link](car) // [["brand","Toyota"],["year",2022],["color","red"]]

// Freeze prevents modification


const frozen = [Link](car);
[Link] = "Honda"; // silently fails

JavaScript Complete Course Notes Page 16


Chapter 10 | DOM (Document Object Model)

10.1 What is the DOM?


The DOM is a programming interface for HTML documents. It represents the page as a tree of
node objects that JavaScript can modify.

10.2 Selecting Elements


// By ID — returns single element
const el = [Link]("myDiv");

// By CSS selector — first match


const btn = [Link](".submit-btn");

// All matching elements — NodeList


const items = [Link]("li");

// Other selectors
[Link]("card");
[Link]("p");

10.3 Modifying Content


const div = [Link]("output");

// innerHTML parses HTML tags


[Link] = "<b>Hello</b> World";

// textContent is plain text only (safer)


[Link] = "Plain text content";

// Get and set attributes


[Link]("class");
[Link]("class", "highlight");
[Link]("hidden");

10.4 Modifying Styles


const box = [Link](".box");

// Inline styles
[Link] = "red";
[Link] = "#f0f0f0";
[Link] = "18px";

// Class manipulation
[Link]("active");
[Link]("hidden");
[Link]("selected");
[Link]("active"); // true

JavaScript Complete Course Notes Page 17


10.5 Creating and Removing Elements
// Create element
const li = [Link]("li");
[Link] = "New item";

// Add to DOM
[Link]("list").appendChild(li);

// Remove element
[Link]();

// Insert before a reference node


const ref = [Link]("li:first-child");
[Link](li, ref);

JavaScript Complete Course Notes Page 18


Chapter 11 | Events

11.1 Event Listeners


Use addEventListener() to attach event handlers. It allows multiple handlers on the same
element.

const btn = [Link]("#myBtn");

[Link]("click", function(event) {
[Link]("Button clicked!");
[Link]([Link]); // the element that was clicked
});

11.2 Common Events


Category Events

Mouse click, dblclick, mouseover, mouseout, mousemove

Keyboard keydown, keyup, keypress

Form submit, change, input, focus, blur, reset

Window load, resize, scroll, unload

11.3 Keyboard & Mouse Event Example


[Link]("keydown", (e) => {
[Link]("Key pressed:", [Link], "Code:", [Link]);
if ([Link] === "Enter") [Link]("Enter pressed!");
});

[Link]("mousemove", (e) => {


[Link](`Mouse at (${[Link]}, ${[Link]})`);
});

11.4 Event Bubbling and Capturing


Bubbling: Event fires on the target first, then propagates up to parent elements. Capturing
(useCapture=true): Event fires from the top (document) down to the target.

// Bubbling (default) — 3rd argument false or omitted


[Link]("click", handler, false);

// Capturing — 3rd argument true


[Link]("click", handler, true);

// Stop bubbling
[Link]("click", (e) => {
[Link]();
[Link]("Bubble stopped here");
});

JavaScript Complete Course Notes Page 19


Chapter 12 | ES6+ Features
ES6 (ECMAScript 2015) introduced major improvements to JavaScript. Many features are now
standard practice.

12.1 let and const (Block Scope)


{
let x = 10;
const Y = 20;
[Link](x, Y); // 10 20
}
// [Link](x); // ReferenceError: x is not defined

12.2 Destructuring
// Array destructuring
const [a, b, ...rest] = [1, 2, 3, 4, 5];
// a=1, b=2, rest=[3,4,5]

// Object destructuring
const { name, age = 18 } = { name: "Alice" };
// name="Alice", age=18 (default)

// Swap variables
let x = 1, y = 2;
[x, y] = [y, x]; // x=2, y=1

12.3 Spread and Rest Operators


// Spread: expand arrays/objects
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1,2,3,4,5]
[Link](...arr1); // 3

// Rest: collect remaining arguments


function sum(...nums) {
return [Link]((a, b) => a + b, 0);
}
sum(1, 2, 3, 4, 5); // 15

12.4 Modules (import / export)


// [Link] — Named exports
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export default function multiply(a, b) { return a * b; }

// [Link] — Importing
import multiply, { PI, add } from "./[Link]";
[Link](add(2, 3)); // 5
[Link](multiply(4,5)); // 20

JavaScript Complete Course Notes Page 20


12.5 Classes
class Animal {
constructor(name, sound) {
[Link] = name;
[Link] = sound;
}
speak() {
return `${[Link]} says ${[Link]}`;
}
}
const dog = new Animal("Dog", "Woof");
[Link]([Link]()); // Dog says Woof

JavaScript Complete Course Notes Page 21


Chapter 13 | Asynchronous JavaScript

13.1 Sync vs Async


Synchronous code executes line by line, blocking the thread. Asynchronous code allows other
operations to run while waiting for long tasks (I/O, API calls) to complete.

13.2 Callbacks
function fetchData(callback) {
setTimeout(() => {
callback("Data received!");
}, 2000);
}
fetchData((data) => {
[Link](data); // After 2s: "Data received!"
});

13.3 Promises
A Promise represents a value that will be available in the future. It can be pending, fulfilled, or
rejected.

const myPromise = new Promise((resolve, reject) => {


const success = true;
if (success) {
resolve("Operation succeeded!");
} else {
reject("Something went wrong.");
}
});

myPromise
.then(result => [Link](result))
.catch(err => [Link](err))
.finally(() => [Link]("Done"));

13.4 async / await


async/await is syntactic sugar over Promises, making async code look and behave like
synchronous code.

async function getUserData() {


try {
const response = await fetch("[Link]
const data = await [Link]();
[Link](data);
} catch (error) {
[Link]("Error:", error);
}
}
getUserData();

13.5 Fetch API

JavaScript Complete Course Notes Page 22


// GET request
fetch("[Link]
.then(res => [Link]())
.then(data => [Link]([Link]));

// POST request
fetch("[Link] {
method: "POST",
headers: { "Content-Type": "application/json" },
body: [Link]({ name: "Alice", age: 25 })
})
.then(res => [Link]())
.then(data => [Link](data));

JavaScript Complete Course Notes Page 23


Chapter 14 | Error Handling
Errors are runtime problems. JavaScript provides structured error handling to manage them
gracefully.

14.1 try / catch / finally


try {
const result = riskyOperation();
[Link](result);
} catch (error) {
[Link]("Caught error:", [Link]);
} finally {
[Link]("Always runs — cleanup code here");
}

14.2 throw Statement


Use throw to create custom errors. You can throw any value — strings, numbers, or Error
objects.

function divide(a, b) {
if (b === 0) {
throw new Error("Division by zero is not allowed");
}
return a / b;
}

try {
[Link](divide(10, 0));
} catch (e) {
[Link]([Link]); // Division by zero...
}

14.3 Error Types


• SyntaxError: Invalid JavaScript syntax
• ReferenceError: Accessing an undefined variable
• TypeError: Wrong type for an operation
• RangeError: Value out of valid range
• URIError: Malformed URI components

JavaScript Complete Course Notes Page 24


Chapter 15 | OOP in JavaScript

15.1 Classes and Constructors


class Person {
constructor(name, age) {
[Link] = name;
[Link] = age;
}
introduce() {
return `I am ${[Link]}, aged ${[Link]}`;
}
static species() {
return "Homo sapiens";
}
}
const p = new Person("Harini", 22);
[Link]([Link]()); // I am Harini, aged 22
[Link]([Link]()); // Homo sapiens

15.2 Inheritance (extends / super)


class Student extends Person {
constructor(name, age, grade) {
super(name, age); // call parent constructor
[Link] = grade;
}
introduce() {
return [Link]() + `, Grade: ${[Link]}`;
}
}
const s = new Student("Bob", 20, "A");
[Link]([Link]()); // I am Bob, aged 20, Grade: A

15.3 Encapsulation (Private Fields)


class BankAccount {
#balance = 0; // private field (ES2022)

deposit(amount) {
if (amount > 0) this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
const acc = new BankAccount();
[Link](1000);
[Link]([Link]()); // 1000
// [Link](acc.#balance); // SyntaxError

15.4 Polymorphism

JavaScript Complete Course Notes Page 25


class Shape {
area() { return 0; }
}
class Circle extends Shape {
constructor(r) { super(); this.r = r; }
area() { return [Link] * this.r ** 2; }
}
class Rectangle extends Shape {
constructor(w, h) { super(); this.w = w; this.h = h; }
area() { return this.w * this.h; }
}
const shapes = [new Circle(5), new Rectangle(4, 6)];
[Link](s => [Link]([Link]().toFixed(2)));
// 78.54 24.00

JavaScript Complete Course Notes Page 26


Chapter 16 | Browser Storage
Feature Cookies localStorage sessionStorage

Capacity ~4KB ~5MB ~5MB

Expiry Manual Never Tab close

Server access Yes No No

Accessibility All windows All windows Same tab only

16.1 localStorage
// Store data
[Link]("username", "Harini");
[Link]("theme", "dark");

// Retrieve data
const user = [Link]("username"); // "Harini"

// Store objects (must serialize)


const prefs = { lang: "en", font: 16 };
[Link]("prefs", [Link](prefs));
const saved = [Link]([Link]("prefs"));

// Remove
[Link]("theme");
[Link](); // clears all

16.2 sessionStorage
// Same API as localStorage
[Link]("cart", [Link](["item1","item2"]));
const cart = [Link]([Link]("cart"));
[Link]("cart");
// Data cleared when tab is closed

16.3 Cookies
// Set a cookie with expiry
[Link] = "user=Harini; expires=Fri, 31 Dec 2025 23:59:59 GMT; path=/";

// Read cookies (returns all as one string)


[Link]([Link]);

// Delete a cookie (set past expiry)


[Link] = "user=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";

JavaScript Complete Course Notes Page 27


Chapter 17 | AJAX & APIs

17.1 What is AJAX?


AJAX (Asynchronous JavaScript and XML) allows web pages to send and receive data from a
server asynchronously — without reloading the page. Modern AJAX typically uses JSON instead
of XML.

17.2 JSON (JavaScript Object Notation)


JSON is a lightweight data-interchange format. It is text-based and language-independent.

// JSON string
const jsonStr = '{"name":"Alice","age":25,"active":true}';

// Parse JSON string to JS object


const obj = [Link](jsonStr);
[Link]([Link]); // Alice

// Convert JS object to JSON string


const jsObj = { city: "Chennai", zip: "600001" };
const str = [Link](jsObj, null, 2);
// Pretty-printed with 2-space indent

17.3 REST API Concepts


HTTP Method Action Example URL

GET Read data /api/users/1

POST Create new data /api/users

PUT Update entire record /api/users/1

PATCH Partial update /api/users/1

DELETE Delete record /api/users/1

17.4 Full API Integration Example (async/await)

JavaScript Complete Course Notes Page 28


// Complete CRUD example with JSONPlaceholder API

// GET — fetch a post


async function getPost(id) {
const res = await fetch(`[Link]
if (![Link]) throw new Error(`HTTP error: ${[Link]}`);
return await [Link]();
}

// POST — create new data


async function createPost(title, body, userId) {
const res = await fetch("[Link] {
method: "POST",
headers: { "Content-Type": "application/json" },
body: [Link]({ title, body, userId })
});
return await [Link]();
}

// DELETE
async function deletePost(id) {
const res = await fetch(
`[Link]
{ method: "DELETE" }
);
return [Link];
}

// Using [Link]() for parallel requests


async function loadMultiple() {
const [post1, post2] = await [Link]([getPost(1), getPost(2)]);
[Link]([Link], [Link]);
}

JavaScript Complete Course Notes Page 29


JavaScript Quick Reference
Data Types number, string, boolean, null, undefined, bigint, symbol, object

Variable Scope var=function, let/const=block

Truthy/Falsy Falsy: false, 0, '', null, undefined, NaN

== vs === == converts types; === strict no conversion

typeof typeof 42 === 'number' | typeof null === 'object' (quirk)

Array from() [Link]('hello') = ['h','e','l','l','o']

Nullish ?? null ?? 'default' returns 'default'

Optional ?. user?.address?.city — no error if null

[Link] Runs multiple promises in parallel

Async function Always returns a Promise

Closure Function retaining access to its outer scope

Hoisting var declarations & function declarations are hoisted

this keyword Refers to the current execution context

Prototype Objects inherit methods via prototype chain

Event loop Call stack + Web APIs + Callback queue = async handling

JavaScript Complete Course Notes Page 30

You might also like