0% found this document useful (0 votes)
4 views500 pages

IAD Notes_

The document provides an overview of Firebase as a Backend-as-a-Service (BaaS) for building applications, particularly with React, highlighting its features such as authentication, Firestore for data storage, and hosting. It emphasizes the importance of security rules for data protection and suggests a modular architecture where components communicate with Firebase through service files to simplify code management. Additionally, it outlines best practices for handling environment variables and securing sensitive data in both client and server environments.

Uploaded by

ratmouse233
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views500 pages

IAD Notes_

The document provides an overview of Firebase as a Backend-as-a-Service (BaaS) for building applications, particularly with React, highlighting its features such as authentication, Firestore for data storage, and hosting. It emphasizes the importance of security rules for data protection and suggests a modular architecture where components communicate with Firebase through service files to simplify code management. Additionally, it outlines best practices for handling environment variables and securing sensitive data in both client and server environments.

Uploaded by

ratmouse233
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

✅ Slide 1: Firebase Overview

✅ Slide 1: Firebase Overview


🔥 What is Firebase?
Firebase is a Backend-as-a-Service (BaaS) offered by Google. It gives you ready-to-use tools
so you don't have to build backend features from scratch.

🔧 Why Use Firebase with React?


You can build a React blog app using Firebase for:week

● Authentication (sign-in/sign-up users)


● Firestore (storing blog posts)
● Hosting (making your site live)

💡 Key Points:
1. Direct Communication with Firestore:

○ No need to write your own APIs.

○ React talks to Firestore directly using Firebase SDKs.

2. NoSQL Database:

○ Firestore is a NoSQL DB like MongoDB.

○ Data is stored in collections and documents, not tables.

3. Simplified Backend Logic:

○ Firebase handles complex backend stuff for small apps.

○ Example: Login system, storage, real-time updates — all with minimal code.

4. Supports CRUD Operations:

○ CRUD = Create, Read, Update, Delete.

○ You can perform these operations on Firestore easily.

✅ Slide 2: Firebase Products


Firebase has many products. For your blog app, focus on these:
💼 Important Firebase Tools:
Product Purpose

Authentication Let users sign in with email, Google, etc.

Cloud Firestore Stores your blog posts/data

Cloud Serverless backend code (advanced)


Functions
Hosting Deploy your site easily

Cloud Storage Store images/files

📘 Firebase Setup Docs


Firebase can be set up for:

● Web (JavaScript)

● Android / iOS

● Unity / Flutter

You’ll use The Web (JavaScript) setup because you're working with React.

✅ Slide 3: Firebase Security Model


This explains how Firebase protects your data.

Client vs. Server


● Client SDKs: Used in web apps (like React). Data access goes through Security Rules.

● Server SDKs / Admin SDK: Used in backend apps. Uses IAM (Identity and Access
Management).

🔒 Security Rules
If you're accessing the database from a web app (client), you MUST write security rules:

● They control who can read/write what.

● For example, only logged-in users can add blog posts.


✅ Example: Creating a Blog Post in a Firebase +
React App
🎯 Scenario:
You’re building a blog site where users can:

1. Sign up / log in

2. Write blog posts

3. See their post

🔧 Step-by-Step with Firebase:

1. Firebase Authentication (Login)


import { getAuth, signInWithEmailAndPassword } from "firebase/auth";

const auth = getAuth();

signInWithEmailAndPassword(auth, email, password)


.then((userCredential) => {
// User is logged in
[Link]([Link]);
})
.catch((error) => {
[Link]([Link]);
});

🔍 Firebase handles everything — no need to build a login system or store passwords


yourself.

2. Cloud Firestore (Save Blog Post)

import { getFirestore, collection, addDoc } from "firebase/firestore";


const db = getFirestore();
async function addPost() {
try {
await addDoc(collection(db, "posts"), {
title: "My First Blog",
content: "This is a post about Firebase + React!",
author: [Link],
createdAt: new Date()
});
[Link]("Post added!");
} catch (e) {
[Link]("Error adding document: ", e);
}
}

📦 No backend needed! You’re saving data directly to the cloud without creating your own API.

3. Firebase Hosting (Deploy Site)


firebase init
firebase deploy

🌍 Now your entire blog site is live on a public URL — no need for separate web servers.

✅ In Short:
Without Firebase (traditional way) you'd have to:

● Set up backend ([Link], Express)

● Create API endpoints

● Use a database like MongoDB

● Deploy on Heroku or another server

With Firebase:

● You skip all this.

● Firebase handles authentication, database, hosting, and security.


✅ IMAGE 1: Security & DB Controls – Client vs
Server
This table compares React Frontend (Client) and Express Backend (Server) in terms of
security and how we handle sensitive data.

🔐 1. File Name for Environment Variables

● Client (React): .env or .[Link] — special config files that hold sensitive keys (like
Firebase API key).
● Server (Express): Also uses .env.

2. How to Access These Variables

● React (Client): You use [Link].VITE_VAR_NAME

● Node/Express (Server): You use [Link].VAR_NAME

📝 Note: In React, the variable name must start with VITE_ so Vite can recognize and use it.

🧠 3. Variable Naming Rules


● Client: Has to start with VITE_
● Server: No prefix needed — name it whatever you like (MONGO_URI, JWT_SECRET, et

⚠️4. Security Level


● Client: Low. These variables can be seen in browser tools (DevTools), so never store
secrets here.
● Server: High. Environment variables stay hidden from users. They are safe

🧨 5. Sensitive Data
● Client: ❌ Never store sensitive info, only public Firebase keys.

● Server: ✅ Store secrets like DB passwords, JWT tokens, etc.

🔐 6. Database Access Control


● Client: Uses Firebase Security Rules

● Server: Uses custom authentication logic like JWT, OAuth, etc.

🌟 7. Best Practices
Frontend (React)

● Restrict Firebase key in console (so others can’t abuse it)

● Always write proper Firestore security rules

Backend (Express)

● Don’t upload your .env file to GitHub — use .gitignore


● Use authentication middleware (JWT) for secure access

✅ IMAGE 2: Firebase Security Rules & Extra Tips

🔐 Main Idea
If you're building a React app using Firebase, you're talking directly to Firebase from the
browser — so you can’t hide secrets.
👉 That's why Firebase gives you Security Rules to control what users can do.

🧠 What Are Firebase Security Rules?


They’re like conditions or if-statements that you write to protect your data:

// Only allow logged-in users to read/write


match /posts/{postId} {
allow read, write: if [Link] != null;
}

So, you don’t need a backend, but you must write proper rules — otherwise, your entire
database is open to the public 🚨

📌 Extra Safety Tips (Beyond Security Rules)


1. Don’t upload config files to GitHub

○ Even though hiding Firebase config doesn’t protect you fully, it’s still a good
habit.

2. Restrict access by HTTP referrer

○ You can tell Firebase to only allow requests from certain websites (like your
production domain).

3. Use App Check

○ It verifies if the request is coming from a genuine app or website (and not from a
hacker's script).

4. Read Firebase security articles

○ Google has guides like this one to help you avoid common mistakes.

🆚 What’s Being Compared?


The table compares how environment variables are used in:

🔹 1. Client-side React App (specifically using Vite)


🔹 2. Server-side [Link]/Express App
So the focus is:

● Where we store variables

● How we access them

● How secure or exposed they are

● What kind of data is safe to put there

📦 What Are Environment Variables?


Environment variables are config values that your app needs — like :

● API keys

● Database URLs

● Secret tokens

● Project IDs

Instead of writing them directly in your code (which is risky), you put them in a .env file and
access them securely from there.

🔍 Why Do We Use Them?


1. Security – Keeps secrets out of your actual code

2. Reusability – Same code, different configs (e.g., dev vs. production)

3. Clean Code – Centralized control for all key values

🟨 Slide 1: The Big Idea


🔥 Key Message:
“Components never talk to Firebase directly. Only the services do.”

This means:
● Your UI components (like [Link], [Link]) should not directly connect to
Firebase.

● Instead, create a separate file (called a "service") — like [Link] — that


handles all Firebase code.

● This hides Firebase's complexity and makes your code easier to manage and update.

🟨 Slide 2: Why Services are Awesome


🔥 Benefits of Using Services:

● Components (UI parts) just say: login() or logout().


✅ They don’t need to know how login works.

● They don’t care about Firebase setup, providers, or the auth object.

● 🔄 If you ever want to switch from Firebase to another backend (like Supabase or AWS),
you only update the service — not every component.

💡 This is called separation of concerns — a coding best practice.

🟨 Slide 3: Layered, Modular Architecture


Here’s a diagram of the architecture you're building:

📦 Layer 3: Firebase

● Raw Firebase functions like signInWithPopup, signOut, etc.

● This is where you initialize Firebase ([Link]).

📦 Layer 2: Services ([Link])

● You write helper functions here: login(), logout(), useAuthentication().

● This layer uses Firebase internally but hides it from components.

📦 Layer 1: Components ([Link], [Link])


● They use simple calls like login() and logout().

● They don’t touch Firebase directly.

This makes the code more organized, testable, and reusable.

🟨 Slide 4: Creating the Service File


You're instructed to create:

src/services/[Link]

Inside this file:

● You will define easy-to-use functions like login() and logout()

● Also create a custom React Hook called useAuthentication() to detect if a user is


logged in or not.

✅ The goal is to hide all Firebase logic from components.

🟨 Slide 5: Explaining Firebase Functions


What does each function do?

● signInWithPopup(auth, provider)
👉 Shows a popup to sign in with Google.

● GoogleAuthProvider
👉 Represents Google as a login method.

● signOut(auth)
👉 Logs out the user.
● auth
👉 Comes from your Firebase config — it contains all Firebase Auth settings.

✅ These are used inside [Link], not in components.

🟨 Slide 6: [Link] – Full Code


Here's what you do in the file:

export function login() {


return signInWithPopup(auth, new GoogleAuthProvider());
}

export function logout() {


return signOut(auth);
}

export function loggedInUserDisplayName() {


return [Link];
}

export function useAuthentication() {


const [user, setUser] = useState(null);

useEffect(() => {
return [Link]((user) => {
setUser(user ? user : null);
});
}, []);

return user;
}

✅ Now your components can easily call:

● login() → to sign in

● logout() → to sign out

● useAuthentication() → to get the current user

🟨 Slide 7: Using the Service in Components


You're building the UI in [Link]:
import { login, logout, loggedInUserDisplayName } from
"../services/authService";

export function SignIn() {


return <button onClick={login}>Sign In</button>
}

export function SignOut() {


return (
<div>
Hello, {loggedInUserDisplayName()}
<button onClick={logout}>Sign Out</button>
</div>
)
}

Summary:

● SignIn uses the login() function from the service


● SignOut shows the user's name and logs out using the logout() function

✅ Again, your component doesn't know about Firebase — it just uses functions from the
service.

🟨 Slide 1: Step 5 – Update [Link]


We want to change how our app behaves based on whether the user is logged in
or not.

🧠 Simple Logic:
● If someone is logged in:
Show their name, a New Article button, and the Sign Out button.

● If no one is logged in:


Show the Sign In button instead.

This is done inside the src/components/[Link] file.

🟨 Slide 2: [Link] – Import and Setup


🔄 What’s being imported:

● useAuthentication from the service layer (to check if the user is logged in)
● fetchArticles, createArticle from a service that handles article database
operations

🧠 What’s Happening:
const user = useAuthentication():

● This line checks if someone is logged in.

● If someone logs in, it fetches all the blog posts using fetchArticles() and saves
them in articles state.

This keeps track of:

● All articles: articles


● Current selected article: article
● Whether you're writing a new one: writing

🟨 Slide 3: Function addArticle


function addArticle({ title, body }) {
createArticle({ title, body }).then((article) => {
setArticle(article);
setArticles([article, ...articles]);
setWriting(false);
});
}

🔍 What this does:

1. createArticle() → saves the new article to Firebase/DB.


2. setArticle(article) → updates the screen to show the new article.
3. setArticles([article, ...articles]) → adds this new article to the full
list.
4. setWriting(false) → hides the editor after submission.

✅ This updates both the backend (DB) and frontend (React state).
🟨 Slide 4: Render Logic in return()
This part controls what appears on screen:
<header>
Blog
{user && <button onClick={() => setWriting(true)}>New
Article</button>}
{!user ? <SignIn /> : <SignOut />}
</header>

● If user is logged in → shows a button to create a new article + Sign Out


● If not logged in → shows Sign In

Then this part shows navigation and the current article:

{!user ? "" : <Nav articles={articles}


setArticle={setArticle} />}
● If the user is logged in → it shows a navigation bar with a list of articles.

Now the big conditional rendering:


{!user ? (
"" // show nothing if not logged in
) : writing ? (
<ArticleEntry addArticle={addArticle} />
) : (
<Article article={article} />
)}

🧠 Explanation:
● If not logged in → show nothing.

● If logged in and writing === true → show the ArticleEntry form to write a new
article.
● If logged in and writing === false → show the selected article using the
Article component.
🔷 Slide 1: Step 6 – Firestore
🔥 What's going on:
We already learned how to handle authentication (login, logout) using Firebase, but now we
move to Firestore — Firebase’s NoSQL database.

● We’ll use Firestore to store and manage data, like posts in a blog or social feed.
● This slide hints that the same pattern will be used: Components → Services →
Firebase.

🔁 Firebase stays hidden behind services. Components never talk to Firestore directly.

🔷 Slide 2: Social Media Dashboard (Friend Feed App)


We’re now building a friend feed app (like Facebook’s timeline), where:

● Users can view their friends’ posts.


● Later, they’ll be able to interact (like, comment, etc.).

👉 We'll use something called container and presentation pattern for clean code.

🔷 Slide 3: Current Limitations


Right now, the app is static:

● It only fetches and shows posts.

● It doesn’t allow users to add, like, delete, or refresh posts.

✅ This slide introduces the folder structure and file

/components

─ [Link]

[Link]

/utils

└── [Link]
● [Link] → UI display component

● [Link] → Handles logic + state (container)

● [Link] → New helper function for fetching posts

🔷 Slide 4: [Link] File Setup


💡 Why use <main> instead of <div>?

<main> is better for semantic HTML — it tells the browser that this is the main content of the
page, improving accessibility and SEO.

Here:

<main>

<h1>Welcome to Friend Feed</h1>

<FriendFeedContainer />

</main>

This loads the UI with the heading and the feed.

🔷 Slide 5: Styling the Posts


● This slide shows how each post is styled using CSS classes.

● The class .friend-post is styled in [Link] or [Link].

Child Component:

<li className="friend-post">

<p className="post-content">{[Link]}</p>

<p className="post-author"><strong>Posted by:</strong>


{[Link]}</p>
</li>

● [Link] only displays one post using this UI.

● Styling is handled separately for clean design.

🔷 Slide 6: DOM Structure (How HTML is built)


This slide visually shows how the HTML is organized in the browser:

● <html> → <body> → <div> → <ul> → <li> → <p> and so on…

● This visualizes how your React components are converted to HTML (DOM).

✅ Helps you understand how your CSS affects structure.

🔷 Slide 7: Hooks and State Flow


This slide explains the data flow pattern:

● [Link] is a container component — it handles:

○ Fetching data from Firebase

○ Managing state

○ Passing data to the presentational component

● [Link] is the presentational component — it just displays UI.

● [Link] (utility function) → performs network request

● useHook (custom or built-in) handles:

○ async API call

○ storing fetched data

○ and returning it to the component


🔷 Slide 8: Container vs Presenter Code
🔵 [Link] (Container):

const [friendPosts, setFriendPosts] = useState([]);

● This component will fetch data (soon using fetchFriendPosts()), and pass it down
like

<FriendFeed posts={friendPosts} />

🟢 [Link] (Presenter):

const FriendFeed = ({ posts }) => {

return (

<ul>

{[Link](post => (

<li key={[Link]}>

<p>{[Link]}</p>

<p><strong>Posted by:</strong> {[Link]}</p>

</li>

))}

● .map() is used to loop through the posts and display each one as a list item.

🔷 Slide 9: Async/Await instead of .then()


This slide says:

It's better to use async/await than chaining .then() in modern JavaScript.


Right now, the code is:

useEffect(() => {

fetchFriendPosts().then(??); // ← What goes here?

}, []):

🔄 Fix using async/await:

useEffect(() => {

async function fetchData() {

const posts = await fetchFriendPosts();

setFriendPosts(posts); }

fetchData();

}, []);

✅ Cleaner, modern, and easier to debug.

🔷 Slide 1: How the Architecture Works


This slide explains how we're organizing the app using:

✅ Container & Presentational Components

Part Description

FriendFeedContaine Container component: handles logic, data fetching, state


[Link]

[Link] Presenter component: only displays the UI

[Link] Utility file where you write functions like fetchFriendPosts()


to get data from Firebase or an API

useHook Can be a built-in hook like useState, useEffect or a custom


hook that manages data fetching
/api or Firebase Where the actual data comes from (e.g. Firestore, backend
server)

📂 The container fetches data using hooks → passes it down as props → presenter component
shows it.

🔷 Slide 2: Code Breakdown: How It Works


🟩 [Link] (Container)

const FriendFeedContainer = () => {

const [friendPosts, setFriendPosts] = useState([]);

// we will fetch the posts here using fetchFriendPosts()

return <FriendFeed posts={friendPosts} />;

};

● useState keeps the posts in local state.

● Later, we’ll fetch the posts using fetchFriendPosts() inside useEffect.

● Then pass the data to <FriendFeed /> via props.

🟨 [Link] (Presenter)

const FriendFeed = ({ posts }) => {

return (

<ul>

{[Link](post => (

<li key={[Link]}>

<p className="post-content">{[Link]}</p>
<p className="post-author"><strong>Posted by:</strong>
{[Link]}</p>

</li>

))}

</ul>

);

};

● Just shows the posts using .map() — doesn’t handle any logic or fetching.

● It’s called a "dumb" component — it receives data and renders it only.

✅ This separation of concerns makes the app cleaner and easier to manage.

🔷 Slide 3: Async vs .then() + Final Question


❌ Problem with .then()

useEffect(() => {

fetchFriendPosts().then(??); // what goes here?

}, []);

You need to handle the result inside .then() — like this:

fetchFriendPosts().then((posts) => setFriendPosts(posts));

But this approach can get messy, especially with multiple async calls.

✅ Better: Use async/await

useEffect(() => {

async function fetchData() {

const posts = await fetchFriendPosts();


setFriendPosts(posts);

fetchData();

}, []);

🔍 Why is this better?


● Cleaner and easier to read.

● No nested .then() callbacks.

● Easier to add try/catch for error handling.

🟪 Slide 1: Conditional Rendering in [Link]

This diagram breaks down the logic inside [Link] that decides what to show on the screen.

Left Side (Header):

● ✅ If the user is logged in:

○ Show “New Article” button (which sets writing = true when clicked).

○ Also show SignOut button.

● ❌ If no user is logged in:

○ Show SignIn button.

Middle (Navbar):

● If the user is logged in, show the <Nav /> component with props:

○ articles and setArticle.

Right (Main area):

● If no user: show nothing.

● If user is logged in:

○ If writing is true → show <ArticleEntry /> form to create a new post.


○ Else → show the selected article using <Article />.

✅ This is clean conditional UI logic using React if and ternary ? rendering.

🔵 Slide 2: Replacing Mock Data with Real Firestore


🔄 What’s changing:

We're switching from fake article data (in memory) to real database data using Firebase
Firestore.

Structure:

1. [Link]: Main component using article services.

2. [Link]: Contains fetchArticles() and createArticle()


functions.

3. Firebase:

○ We use getFirestore() to connect to Firestore.

○ Use Firestore functions like:

■ collection(), getDocs(), addDoc(), query(), etc.

✅ Services talk to Firebase and hide all complexity from components.

🟩 Slide 3: Code + Flow


This shows the updated app architecture after integrating Firestore.

● [Link] calls fetchArticles() using useEffect() when user logs in.

● The service file talks to Firebase and returns the data.

● When a new article is submitted via addArticle():

1. It is saved to Firebase using createArticle().

2. The new article is added to React state with setArticles.


✅ This allows real-time updates with real backend data.

🔷 Slide 4: Add Data to Firestore


You’re instructed to manually:

1. Go to Firebase Console.

2. Create a new collection called articles.

3. Inside it, add documents with:

○ title → string

○ body → string

○ date → timestamp

Let Firebase auto-generate the document ID.

✅ This gives you real database entries to fetch later in your app.

🟨 Slide 5: Firebase Console View


This slide shows what the Firestore database will look like:

● You have a collection called Articles.

● Inside it are multiple documents, each representing one post.

● Each document has fields like:

○ title

○ body

○ date

✅ This is now your real backend database, replacing the in-memory fake one.

🟧 Slide 6: The Starter Code Reminder


This slide shows the initial project setup:

● Your app already has [Link] with mock data.

● We're now updating this file to connect it to Firebase Firestore instead.

🟩 Slide 7: New Article Service Structure


This slide shows what the updated service will look like.

fetchArticles():

● Combines Firestore document IDs with their data using .map()

return [Link](articles).map(([id, data]) => ({ id, ...data }))

createArticle():

● Accepts title and body.

● Adds the new article to the database.

● Returns a new article object with id, title, body, and date.

✅ These functions keep the database logic separate from your components.

🟩 Slide 8: Previous Fake Data

This slide shows the old version of [Link].

● It had a const articles = {} object in memory.

● No real API call.

● createArticle() just generated random data using [Link]() and new


Date().

🧪 It was good for learning, but not practical for real apps.

🟦 Slide 9: The Difference Between Fake and Real Data


This slide compares both versions:

Fake Blog Real Blog

No server Connected to Firebase

No HTTP/API Uses real HTTP


requests

Instant (no delay) Slower (network delay)

Stored in memory Stored in database

Local memory is fast but not persistent.


Network/database is slower but permanent and sharable across users.

✅ The new version simulates a real-world app with Firestore as your backend.

WEEK 1:
🧠 Main Idea:
This diagram explains how a website (like [Link]) is requested from your
computer and how it reaches the destination server and comes back with a response (like the
Google homepage).

1. Client ([Link])

You (the user) type [Link] in your browser. That makes your computer the client
— the one asking for something.

🌐 2. Browser
Your browser (like Chrome or Firefox) takes what you typed and prepares a request. It wraps
your request in a special format called HTTP.
📤 3. GET Request (HTTP/1.1)
This is the actual request message that goes out.
Example:

GET / HTTP/1.1

Host: [Link]

It means: "Hey Google server, give me the homepage!"

🔁 4. Binary/Radio Waves
This message is converted into binary (0s and 1s). If you're using WiFi, it becomes radio
waves to travel wirelessly.

📡 5. Router/Ethernet
This is your WiFi router or wired internet connection. It knows where you are and sends your
request to the next closest internet router.

🔁 6. Next Nearest Router


This is part of the internet backbone — a chain of routers that passes your request forward
until it reaches the server.

📍 7. Destination Address (IP)


This is the server (Google’s computer) that receives your request. It reads your GET request
and sends back a response (like Google’s homepage HTML).

📥 8. Response Comes Back


The server’s response travels back through the same routers, back to your router, then to
your browser.

📲 9. Client Sees the Website


Finally, your browser displays the webpage using the response from the server.

🌐 1. Front-End Development (What users see)


● It’s everything visible on a website (layout, buttons, forms, text).

● Built using HTML, CSS, and JavaScript.

● Responsive design makes sure the site works on all screen sizes (like mobile and
desktop).

● Client-side scripts run directly in the browser without needing the server every time.

2. Backend Development (What happens behind the


scenes):
● Like the "invisible part of an iceberg."

● Handles data processing, database access, and server logic.

● When a front-end action (like clicking "submit") needs data, it sends a request to the
backend using JavaScript/AJAX.

● The backend runs server-side scripts, fetches or updates data in the database, and
sends a response back to the front-end.

🔁 3. Full-Stack Development (Both front and back)


● A full-stack developer works on both frontend (user interface) and backend (data and
logic).

● They understand the complete process of how a web app works from start to end.
🔷 1. DOM (Document Object Model)
● It’s the HTML structure shown as a tree of elements.

● Each element (like html, body, p, div, etc.) is a node.

● Parent-child relationship means:

○ body is the parent of p, div, img.

○ p is the parent of span.

○ span is the parent of the text web performance.

🧠 Think of it like a family tree — big elements contain smaller elements.

🎨 2. CSSOM (CSS Object Model)


● This is where CSS rules (like font-size, color, etc.) are matched with the HTML
elements.

● Each element gets its style from CSS.

○ For example:
■ p has font-size: 16px, font-weight: bold

■ span has display: none (it will be hidden)

🌲 3. Render Tree
● The browser combines DOM + CSSOM to build a Render Tree.

● This tree shows only the visible elements with their computed styles.

● Elements like the span with display: none are excluded.

📌 Example:

● Only Hello and students appear inside p, because span was hidden.

🔹 HTML Tags vs Elements


✅ Element
An HTML Element is the full structure — from start tag to end tag, including the content
inside.
Example:

html
CopyEdit
<p>Some text</p>

This whole line is called an element.

✅ Tag
Tags are the opening and closing parts of an element.
In the example above:

● <p> is the opening tag

● </p> is the closing tag


So:

● <p> + </p> = tags

● <p>Some text</p> = element

📘 Common Tags in <head> Section


Tag Description

<title> Shows title on browser tab

<meta> Stores metadata (info about the page)

<link> Connects to CSS stylesheet

<script> Adds external JavaScript

<!-- comment Adds comments in code (not visible on the


--> page)

Three Main Layers Highlighted at the Top:


1. UI (User Interface)
○ Refers to the Front End: What the user sees and interacts with (HTML, CSS,
JavaScript).

2. Request Layer
Refers to the Web API: Handles the communication between the front end and the back
end using requests and responses (usually in JSON format).
3. Back End
○ Refers to the Database and Logic: Where the data is stored and processed.

Server-Side (Left Side of Diagram):


● Database
Stores structured data like user information, products, etc.

● Logic
Contains business rules and functions, which interact with the database and other
services.

● Media Cache
Stores frequently accessed media content (like images/videos) to improve performance.

● API (Application Programming Interface)


Serves as a gateway that handles requests from the front end. It receives requests,
executes logic, accesses the database, and returns responses in JSON format.

● Front End (Server-generated code)


Built using HTML, JavaScript, and CSS. It’s delivered to the client’s browser for
rendering the user interface.

🌐 Internet (Middle Cloud Shape)


Acts as the bridge between the Client and the Server. Requests and responses travel through
the internet.

Client-Side (Right Side of Diagram):


● Browser (e.g., Chrome, Firefox, Safari)
This is where users interact with the application. The browser receives front-end code
from the server, renders it, and displays it to the user.
🔄 How It Works (Flow):
1. The client (browser) sends a request via the internet to the server.

2. The API on the server receives the request and communicates with:

○ Logic for processing.

○ Database for data.

○ Media Cache for media content.

3. The API sends back a JSON response.

4. The Front End interprets that data and displays it on the browser.

b) Fill-in-the-blank Activity
This activity asks you to choose correct terms to complete the explanation:

css
Copy code
(HTML, DOM) represents initial page content/state,
and the (HTML, DOM) represents current page content.
When (HTML, JavaScript, DOM) adds, removes, or edits nodes,
the (HTML, DOM, JS) becomes different than the (HTML, DOM, JS).

✅ Correct Filled Version:

HTML represents initial page content/state, and the DOM represents current page
content.
When JavaScript adds, removes, or edits nodes, the DOM becomes different than
the HTML.

✅ Why:

● HTML is static — it's the code written initially.

● DOM is dynamic — it changes as the browser renders and JavaScript manipulates it.

● JavaScript allows real-time manipulation of the DOM.

What is the DOM?


DOM stands for Document Object Model.

● It's a programming interface that represents a web page as a tree of objects.

● Each HTML element (like <h1>, <a>, <body>) becomes a node in this tree.

● This model is built by the web browser when it reads an HTML document.

🔍 Left Side Explanation


● ✅ Model of the web page:
Your browser reads the HTML and creates a model (structure) that includes all
elements (tags, text, etc.).

● ✅ Objects and properties:


All page content becomes objects that can have:

○ Properties (like .innerText)

○ Methods (like .appendChild())

○ Events (like .onclick)

● ✅ Scripting access:
JavaScript or other scripting languages can be used to interact with these objects.

💡 Right Side Explanation


● 🧠 Every item becomes an object:
Each tag (like <h1>, <a>) becomes a manipulatable DOM object.

● 🎨 You can control:

○ Color

○ Transparency

○ Position

○ Sound

○ Behavior (like click actions)

🔗 Every HTML tag is a DOM object


For example:

html
Copy code
<a href="[Link]">Click me</a>
turns into:

js
Copy code
[Link]('a').href // '[Link]'

🌲 Diagram in the Middle


This shows the DOM tree structure:

mathematica
Copy code
Document
└── Root element: <html>
├── <head>
│ └── <title> → Text: "My title"
└── <body>
├── <h1> → Text: "A heading"
└── <a href="..."> → Text: "Link text"

This tree allows scripts to navigate, edit, or add/remove any node.

Website
● Purpose: Informational or presentational.

● Interaction: Mostly read-only content.

● Example: News sites, blogs, portfolios.

● Technologies: HTML, CSS, maybe some JavaScript.

● User Role: Visitor/passive reader.

📌 Think of a website like a digital brochure or magazine.


💻 Web App (Web Application)
● Purpose: Interactive and dynamic.

● Interaction: Users interact, input data, and get personalized responses.

● Example: Gmail, Google Docs, Facebook, online banking portals.

● Technologies: HTML, CSS, JavaScript + backend ([Link], Python, PHP, etc.).

● User Role: Active participants, often with login/accounts.

📌 Think of a web app as software that runs in a browser.

🔄 Web Service
● Purpose: Machine-to-machine communication (not designed for human users).

● Interaction: No UI; provides data or functionality to other software/apps.

● Example: REST APIs, SOAP services (like weather data APIs, payment gateways).

● Technologies: JSON, XML, HTTP, WebSocket, etc.

● User Role: Other applications/programs.

📌 Think of a web service like a waiter — it takes a request and brings the response (data),
behind the scenes.
Week 2:

Main Concept:
"An Internet application does something for end users."

That means: it performs a specific task or service using Internet connectivity — like sending
emails, transferring files, or processing payments.

1. ✅ Email Applications (Link: [Link])


● Purpose: Sending and receiving emails via the Internet.

● Protocols Involved:

○ SMTP (Simple Mail Transfer Protocol) – sends emails.

○ POP3/IMAP – retrieves emails from the mail server.

● Use Case: Apps like Gmail, Outlook, or Mailbird (mentioned link) are examples of email
clients — they act as interfaces between the user and email servers.
2. 🔒 SFTP (Secure File Transfer Protocol)
● Purpose: Safely transfer files between computers over the Internet.

● How it works:

○ Files are encrypted on the sender's end.

○ Transmitted securely via the Internet.

○ Decrypted on the server or recipient’s end.

● Use Case: Transferring confidential documents, like legal or financial files, securely from
one system to another.

3. 💳 Credit Card / Online Payment Systems


● Purpose: Facilitates online financial transactions.

● How it works:

○ User enters card details (like the HBL Platinum Visa card shown).

○ Data is encrypted and sent to the bank/payment processor.

○ Payment is authenticated and processed in real time.

● Use Case: Online shopping, utility bill payment, subscriptions (like Netflix or Spotify).

4. 📩 Email Transmission Diagram (SMTP, POP3, IMAP)


● Detailed Flow:

○ SMTP sends the email from the sender’s client to the recipient’s mail server.

○ Recipient’s mail client fetches the message using POP3 (downloads and deletes)
or IMAP (syncs across devices).

● Use Case: Explains the backend process when you hit “send” in Gmail — it’s not instant
magic, it’s SMTP + server-to-server + POP/IMAP.
5. 🔄 File Transfer Illustration (Laptop-to-Laptop)
● Represents peer-to-peer or server-based file exchange.

● Could use:

○ FTP/SFTP (mentioned earlier)

○ Cloud-based tools (like Google Drive, Dropbox, or WeTransfer)

● Use Case: Sharing project files, assignments, large media files, etc.

🌐 1. HTTP (HyperText Transfer Protocol)


🔎 What is it?
It’s the language browsers and websites use to talk to each other. It helps you request and
receive webpages.

⚙️How it works (Step by Step):


🧠 Scenario: You want to open [Link]

1. You open Google Chrome or Firefox.

[Link]
2.

Your browser sends a HTTP request to the web server of [Link], asking:

pgsql
Copy code
GET /[Link] HTTP/1.1

3.

The server replies with:

css
Copy code
200 OK

(HTML code for the homepage)

4.
5. Your browser renders the HTML and shows you the website.

📦 Example:

http

Copy code

GET /[Link] HTTP/1.1

Host: [Link]

The server replies:

http

Copy code

HTTP/1.1 200 OK

Content-Type: text/html

<html>

<body>Welcome to Example!</body>

</html>

✅ Used for: Browsing web pages, online forms, streaming, e-commerce.

💻 2. Telnet (Teletype Network)


🔎 What is it?
Telnet is used to remotely log in to another computer over a network and execute
commands as if you're sitting in front of it.

⚙️How it works (Step by Step):

🧠 Scenario: You want to access a server at IP [Link]


1. You open a terminal or command prompt.

telnet [Link]
2.
3. If the server allows it, you’ll be connected and see a login prompt.

Copy code
login: yourusername

password: yourpassword

4.
5. Now you can type commands directly on that remote machine.

Example session:

telnet [Link]

Trying [Link]...

Connected to [Link]

Login: admin

Password: *****

Then:

bash

Copy code

dir # To list files

cd folder # To change folder

✅ Used for: Remote management of devices (servers, switches), troubleshooting, network


testing (in older systems).
🆚 Difference Summary (Easy Words)
Feature HTTP Telnet

Purpos View websites Control another computer


e remotely

Interfac Browser (Graphical) Command-line (Text-based)


e

Exampl Requesting a web page Logging into a server and


e typing commands
Action

Securit Not encrypted (use Not secure at all


y HTTPS for secure)

Real- Surfing the web Remote control of network


Life devices
Use

🎯 Real-Life Analogy:
● HTTP is like ordering food from a restaurant using a menu and a waiter.

● Telnet is like walking into the kitchen and cooking your own food there.

🔹 Slide 1: Enabling TELNET on Windows


✅ What is TELNET?
● TELNET is a network protocol.

● It lets you connect to remote computers over a TCP/IP network.

● It's commonly used to log in to remote systems (like servers) and run commands on
them.
💻 What’s being done in the Command Prompt?
You see the command:

bash

Copy code

dism /online /Enable-Feature /FeatureName:TelnetClient

Let me explain each part:

● dism: This stands for Deployment Image Servicing and Management. It’s a tool used
to manage Windows features.

● /online: This means you're making changes to the Windows OS that is currently
running.

● /Enable-Feature: You're enabling a built-in Windows feature.

● /FeatureName:TelnetClient: This tells Windows to enable the Telnet client.

🔚 Outcome:

● It says “The operation completed successfully.”

● This means TELNET is now available for use on your computer.

🔹 Slide 2: Enabling TELNET via Control Panel


This slide shows another way to enable TELNET, using the Graphical User Interface (GUI).

🧭 Step-by-step breakdown:
In the Command Prompt, the user tries:

bash
Copy code
[Link]

1.
○ But that gives an error — it’s a typo.
The correct command is:

bash
Copy code
[Link]

2.
○ This opens "Programs and Features" in the Control Panel, where you can
enable or disable Windows features.

3. On the right side, under "Turn Windows features on or off", a window pops up.

○ You scroll down and tick Telnet Client.

○ Then click OK.

📝 Alternative Features Shown:

● Simple TCP/IP Services: Offers basic network services like echo and daytime.

● SMB 1.0/CIFS File Sharing Support: An old file sharing protocol, mostly for backward
compatibility.

🔹 Slide 3: How to Use TELNET Once It’s Enabled


🪜 Follow these steps:
1. Open Command Prompt

○ Search for "cmd" in your Start Menu and open it.

Type TELNET command

bash
Copy code
telnet <IP address> <Port>

2.
○ Replace <IP address> with the address of the remote computer.

○ Replace <Port> with the port number you want to test.


✅ Example:

bash
Copy code
telnet [Link] 1521

3.
4. What does a blank screen mean?

○ It means the port is open, and TELNET connected successfully.

○ Success!

5. If you see an error like "Connecting..." or "Could not open connection":

○ Something is blocking the connection.

■ Maybe your Windows Firewall.

■ Maybe your antivirus.

■ Maybe a network firewall in a school or office.

6. Test Web Access (e.g., telnet [Link])

○ This is just to show you can try TELNET on known websites.

○ A message like "Press any key to continue" means TELNET tried to connect.
🔹 Slide Title: How to Create an HTTP Request in
Telnet
This tutorial demonstrates how to use the Telnet client to send an HTTP request to a web
server (in this case, Google), and shows why it fails when not done properly.

📌 Part 1: Opening a Connection to Google with


Telnet
Screenshot Description:
sql

Copy code

Welcome to Microsoft Telnet Client

Escape Character is 'CTRL+]'

Microsoft Telnet> open [Link] 80

Connecting To [Link]...

📘 Explanation:
● Microsoft Telnet Client: This is a command-line tool used to connect to remote servers.

● open [Link] 80:

○ [Link]: The domain you're connecting to.

○ 80: The port number. Port 80 is the standard port for HTTP traffic.

💡 At this point, you’ve established a TCP connection with Google's web server on port 80,
which is used for regular (non-encrypted) HTTP.

📌 Part 2: What Happens After Connecting?


The next screenshots show an HTTP response from the server:

vbnet

Copy code

HTTP/1.0 400 Bad Request

Content-Length: 54

Content-Type: text/html; charset=UTF-8

Date: Thu, 09 Jan 2025 ...

<html><title>Error 400 (Bad Request)!!1</title></html>

Connection to host lost.

Press any key to continue...

📘 What went wrong?


● You opened a connection, but you didn’t send a properly formatted HTTP request.

● As a result, Google returns a 400 Bad Request error. This means the server didn’t
understand the request due to invalid syntax.

📌 What is a Proper HTTP Request?


If you were to send a correct request, it would look like this:

vbnet

Copy code

GET / HTTP/1.1

Host: [Link]
● GET / HTTP/1.1:

○ GET is the HTTP method to retrieve data.

○ / refers to the homepage.

○ HTTP/1.1 is the protocol version.

● Host: [Link]: Required in HTTP/1.1 to indicate which website you're requesting


(because many servers host multiple websites).

🔸 You need to press Enter twice at the end to indicate the end of the request headers.

📌 Part 3: Second Screenshot (Detailed Error


Message)
In the second terminal window, the error response is more verbose:

php-template

Copy code

Your client has issued a malformed or illegal request.

<ins>That's all we know.</ins>

● This suggests that some data might have been typed in, but it still wasn’t a valid HTTP
request.
● That’s why Google responds with a detailed HTML error page, but still a 400 Bad
Request.

🧱 Slide 1: Architecture of Static Website


📌 What's a Static Website?
A static website serves fixed content to users. The same HTML file is sent to everyone who
visits the site. There's no server-side logic or processing involved — everything is already
prepared and stored on the server.

✅ Step-by-Step Breakdown (Diagram 1)


🔴 Step 1 – Web browser requests a static page

● This happens when you type a website URL (like [Link]) in your browser and
press Enter.

● The browser sends an HTTP request to the server where that site is hosted.

🔴 Step 2 – Web Server finds the requested page

● The server simply checks its file system (just like opening a folder on your PC) and finds
the requested file (e.g., [Link]).

🔴 Step 3 – Web Server sends the page back


● The server responds with the exact HTML file to the browser.

● The browser then renders (displays) that page on your screen.

📝 Important Note:
"Static does not mean that it will not respond to user actions."

✅ This is a very common misconception!

● A static site can still use CSS for styling and JavaScript for user interaction (like
clicking buttons or animations).

● However, it cannot change content dynamically based on user input or database data,
because there's no server-side processing involved.

⚙️Slide 2: Architecture of Dynamic Website


📌 What's a Dynamic Website?
A dynamic website can generate different content for different users or at different times. It
uses server-side technologies to build pages on the fly, often using databases to store and
retrieve information.

✅ Key Components (Diagram 2)


1. Client / Web Browser

● This is the user’s device, running a web browser (like Chrome, Firefox, etc.).

● It sends requests to the server and displays the response.

● Also known as the “frontend.”

🖧 2. Web Server

● This receives requests from the browser.


● Unlike a static site, it doesn’t just return a pre-made file — it often needs to construct
the page by combining HTML with real-time data.

● May use languages like PHP, Python (Django/Flask), [Link], or others.

3. Database Server

● Stores data like user accounts, product listings, blog posts, etc.

● When the web server needs data, it queries the database and fetches what it needs.

● Popular databases: MySQL, MongoDB, PostgreSQL, etc.

🔁 Interaction Flow (Left to Right in Diagram):


1. The user makes a request (e.g., log in, view blog post).

2. The web server processes the request.

3. If needed, the server queries the database (e.g., “get blog post #5”).

4. The server uses that data to build a custom HTML response.

5. It sends that HTML back to the browser for display.

⚙️DYNAMIC WEBSITE — Real Life Examples


A dynamic website generates content on the fly, often customized for each user. It usually
involves server-side logic, databases, and user interaction.

🔸 Example 1: E-commerce Site (e.g., Amazon, Flipkart)


● Products are pulled from a database.

● You see personalized recommendations.

● Cart updates in real-time.

● Orders, user accounts, and payment processing all happen dynamically.

➡️Built using:
● Backend like [Link], Python, PHP

● Databases like MySQL, MongoDB

🔸 Example 2: Social Media Platforms (e.g., Facebook, Instagram)


● Each user sees their own feed.

● Likes, comments, friend suggestions — all dynamic.

● New content is created and loaded constantly.

➡️Uses:

● Real-time databases

● APIs and user authentication

✅ HTML (HyperText Markup Language)


🔹 What it is:
The standard language for creating web pages.

🔹 Flexible and forgiving:


Browsers are lenient. If you forget to close a tag or make small mistakes, it will still try to
display the page correctly.

🔹 Example:

html

Copy code

<p>This is a paragraph

Even though the </p> is missing, the browser will still show the paragraph.

✅ XHTML (eXtensible HyperText Markup


Language)
🔹 What it is:
XHTML is a stricter, XML-based version of HTML.

🔹 Why stricter?
Because XHTML follows XML rules, which means the code must be perfectly written — no
exceptions.

🔹 Browser behavior:
If there’s even one small mistake, like a missing tag or wrong case, the browser may not
render the page at all.

🔹 Example (must be perfect):

xhtml

Copy code

<p>This is a paragraph</p> <!-- Must be closed properly -->

<br /> <!-- Self-closing tags must end with a slash -->
Week 3

Section 1: Understanding HTML Structure


This part of the image is talking about the structure of a simple webpage that has a counter
button. The question asks:
(i) __??__ : Displays the heading at the top.

● The answer is <h1>.

● Why? In HTML, the <h1> tag is used for the main heading. In the image, "Hello
Counter" is wrapped inside an <h1> element and styled to be at the top using CSS.

✅ So, (i) <h1>

(ii) A __??__ containing __??__ element is used to group and structure the button
independently.

● The first blank refers to <div>.

○ Why? A <div> is a container element in HTML, used to group together HTML


elements for layout and styling purposes. In the image, the button is placed
inside a <div class="container">.

● The second blank is <button>.

○ Why? That’s the interactive element inside the <div> that users can click on to
increment the counter.

✅ So, (ii) A <div> containing <button> element.

🔲 Section 2: CSS Styling Behavior


This section explains what happens when users interact with the button.

● It describes a transition effect:

○ From default background color (#56ccf2)

○ To hover background color (#d0f0fd)

○ Over 0.3 seconds

This improves UX by adding smooth visual feedback when users hover over the button.

🔲 Section 3: CSS Variable Scope


This section talks about CSS custom properties (variables).

The variables defined under the :root selector are __??__ (local/global).

● The answer is global.

● Why? The :root selector refers to the highest-level element in HTML (<html>), and
defining variables here makes them globally available across your entire stylesheet.

✅ So, the answer is: global

--button-text-color would be a __??__ variable, available only within the button


selector and its __??__.

● The first blank is local.

○ Why? If a CSS variable is defined inside a specific selector (like button), it’s
only available within that scope — it’s a local variable.

● The second blank is descendants.

○ Why? Local variables are available within the element they’re defined in and its
child elements.

✅ So, the full sentence becomes:


--button-text-color would be a local variable, available only within the button
selector and its descendants.

Image 1: File Loading Flow – How HTML Opens in a


Browser
This image shows the sequence of steps that occur when a user double-clicks an HTML file on
their computer.

🔢 Flow:

User (1) → OS (2) → Browser (3) → OS (4) → Browser (5) → Browser (6)

Let's match the numbers with what happens:

✅ Steps with explanations:


1. User (1):
➤ Double-clicks [Link].
This action starts the process. It’s the user's intent to open the file.

2. OS (2):
➤ Identifies the file type and associates it with the browser.
The operating system knows .html files should be opened with a web browser (like
Chrome or Firefox).

3. Browser (3):
➤ Receives file path with file:// URL scheme.
The browser gets a path like [Link]

4. OS (4):
➤ Locates and reads the file.
The browser asks the OS to access the contents of the file from disk.

5. Browser (5):
➤ Processes (parses) HTML, CSS, and JS.
The browser reads the file’s contents and starts interpreting the code.

6. Browser (6):
➤ Renders the page and displays the file:// URL.
The final step — the browser draws the page visually on screen.

✅ All steps match what's shown, and the path highlighted ([Link] is the
exact path passed around during this process.

📗 Image 2: Understanding [Link] vs http:// URLs


This one’s about explaining how file URLs work compared to web URLs.

🔲 First Blank:

Just like [Link] the [Link] protocol is also a ?? in the broader URI
structure.

✅ Correct term: scheme

● Why? In a URL, the "scheme" defines how the resource is accessed. Common schemes
include:
○ http, https → for web

○ ftp → for file transfers

○ file → for accessing local files

✅ So the sentence becomes:


"Just like [Link] the [Link] protocol is also a scheme in the broader URI
structure."

🔲 Second Blank:
Just as HTTP URLs point to resources on the ??, file URLs point to resources on
the ??.

✅ First blank: internet


✅ Second blank: local file system

● HTTP URLs access content hosted online.

● File URLs access content stored locally (like from your D: or C: drive).

✅ Final sentence:
"Just as HTTP URLs point to resources on the internet, file URLs point to resources on
the local file system."

Image 1: Domain Name Breakdown ([Link])


This image explains the hierarchical structure of a domain name. Let’s decode each part:

🔤 The domain [Link] is broken down into:

1. mail → Third-level domain (subdomain)

○ It often represents a service or section of a website (e.g., mail, blog, shop).

○ It’s optional and customizable by the domain owner.

2. yahoo → Second-level domain (SLD)


○ This is the unique name chosen by the organization or individual (e.g., google,
bbc, yahoo).

3. com → Top-level domain (TLD)

○ This part denotes the category or region (.com, .org, .pk, .edu, etc.)

○ Managed by ICANN.

4. . (dot) → Root domain (invisible but implied)

○ This dot exists at the end of a fully qualified domain name (FQDN) as the DNS
root, but is usually not typed.

🔁 Hierarchy:
Each part to the left of the dot is a subdomain of what’s on the right.
So:

● mail is a subdomain of [Link]

● yahoo is a subdomain of com (from the DNS perspective)

🌐 Image 2: Parts of a URL


This image shows a complete URL like:

bash
Copy code
[Link]
utm_source=linkedin&utm_medium=organic#definition

Let’s break this into labeled parts and match the blanks!

✅ 1. Protocol:

● https://

● Defines how the resource is requested (HyperText Transfer Protocol Secure).


✅ 2. Host Section:

● [Link]

○ blog → Subdomain

○ raminzamani → Main domain (Second-Level Domain)

○ com → Top-Level Domain (TLD)

Together they form the host (domain name).

✅ 3. Port:

● :443

● Used to define the port number for the request.

○ Port 443 → Default for HTTPS

○ Port 80 → Default for HTTP

✅ 4. Path:

● /6-parts-of-a-url

● Directs the browser to a specific resource or file on the server.

✅ 5. Query String:

● Comes after the ?

● utm_source=linkedin&utm_medium=organic

○ These are parameters passed to the server.


○ Often used for tracking in analytics.

✅ 6. Fragment:

● #definition

● This is not sent to the server.

● It tells the browser to scroll to a specific section (like an anchor or heading) on the page.

Image 1: Technical Limitation of File URL


This slide explains CORS (Cross-Origin Resource Sharing) and the Same-Origin Policy.
These are both key security concepts in web development.

(i) Same-Origin Policy:

“The default security policy enforced by browsers is called the Same-Origin Policy,
which blocks cross-origin requests between different origins.”

● 🔹 Blank = cross-origin

● This means if a website on [Link] tries to fetch data from [Link], the
browser blocks it unless allowed.

(ii) What is CORS?

“CORS stands for Cross-Origin Resource Sharing, a mechanism that allows or


restricts resource sharing between different domains.”

● 🔹 Blank = resource sharing

● CORS lets servers safely share resources (like APIs, images, etc.) with clients hosted on
different domains.

(iii) Error Example:

“Access to fetch at '[Link] from origin '[Link]


has been blocked by CORS policy”.

“This indicates that the backend server does not include the appropriate CORS
headers in its response.”

● 🔹 Blank = CORS headers


● This error tells you that the API server hasn’t set the correct headers to allow your
request from a different origin.

💻 Image 2: Solution / File Protocol Issues Resolution


This slide talks about how to resolve CORS/file protocol issues using lightweight local servers
like Live Server, http-server, or Python HTTP server.

(i) Then Access the app at:

This blank expects the URL where your server is running.

● 🔹 Blank = [Link]

● When you start a local server, your browser accesses it using a localhost address with
the server's port.

(ii) [Link] is a:

“[Link] is a local development server where your app is served (via


a server running on port 8080).”

● 🔹 Blank = local development server

● This means you're running the app locally for testing before deployment.
[Link] vs Vanilla JavaScript
Feature Vanilla JavaScript [Link]

Definition The plain, core JavaScript A JavaScript library developed by


language without any libraries or Facebook for building user interfaces,
frameworks. especially SPAs (Single Page
Applications).

DOM You manipulate the DOM React uses a Virtual DOM, which
Manipulation manually using methods like makes changes more efficient and
getElementById, faster.
querySelector, etc.
Code Procedural or functional code. Component-based architecture —
Structure Managing large UIs can become reusable, isolated pieces of UI
messy. (components).

Reusability Limited; repetitive code is High reusability through components.


common.

State You manage state manually (e.g., Built-in useState, useReducer, and
Management updating values in memory or other hooks make state management
DOM). easier.
UI Updates You have to manually re-render React automatically re-renders
parts of the UI on data changes. components when state or props
change.

Scalability Gets complicated as your app Scales well with features like React
grows. Router, Redux, etc.

Learning Easier to start with. Slightly steeper learning curve due to


Curve JSX, components, hooks, etc.

✅ Why is React Preferred?


Here’s why React is a go-to choice for many developers:

1. 🔁 Reusable Components
You can build UI elements like buttons, cards, forms as reusable pieces — write once, use
anywhere.

2. ⚡ Performance Boost with Virtual DOM


React updates the DOM efficiently using a virtual representation — much faster than updating
the real DOM directly.

3. 🔧 Developer Tools & Ecosystem


Amazing tools like React DevTools and a massive ecosystem (React Router, Redux, etc.) help
in rapid development.

4. 💚 Community Support
Backed by Facebook and loved by millions of devs worldwide — huge support, documentation,
and resources.
5. 🌍 SEO-Friendly
With server-side rendering (e.g., using [Link]), React apps can be optimized for search
engines.

6. 🔄 Unidirectional Data Flow


This makes the data flow predictable, which helps avoid bugs in large applications.

TL;DR:
Vanilla JS is like building a house brick by brick yourself.
React JS is like using a modular kit where each piece (component) snaps together — faster,
neater, and scalable.

Slide 1: What is React?

🔹 React (aka [Link] or ReactJS) is an:

Open-source front-end JavaScript library used for building composable user interfaces,
especially for single-page applications (SPA).

✅ Blank 1 (used for building composable user interfaces, especially for →


single-page applications).

🔹 It is used for handling the view layer in web and mobile apps, based on components in
a:

Declarative manner.

✅ Blank 2 (components in a → declarative manner).

What Does "Declarative" Mean?


Declarative programming is when you describe what you want the UI to look like, not how to
make it happen step-by-step.

🔁 Opposite: Imperative
In imperative programming, you give exact instructions — like a recipe — for how to do
something.
🎯 Think of It Like This:
☕ Making Tea
● Imperative: Boil water → Add tea leaves → Wait → Strain tea → Pour into cup.

● Declarative: “I want a cup of tea.” (Let the system handle the steps!)

Example in Code
🔹 Imperative (Vanilla JavaScript):
const button = [Link]("button");
[Link] = "Click me";
[Link]("click", () => alert("Clicked!"));
[Link](button);

You are telling the browser step-by-step how to create and place a button.

🔹 Declarative (React):

function App() {
return <button onClick={() => alert("Clicked!")}>Click me</button>;
}

Here, you're just describing:


💬 “I want a button that says ‘Click me’ and shows an alert when clicked.”

React handles the how — like creating the element, attaching the event, adding it to the DOM,
etc.

🧠 Why Declarative is Better for UI?


● 🔍 Clearer Code – Easier to read and understand.
● 🔄 Less Error-Prone – You don’t manually update DOM; React does it.

● ⚙️Easier to Maintain – Especially as your app gets complex.

Ahh — that’s such a great question! Let's clear it up with a simple analogy and deeper
explanation.

You're absolutely right — you are still writing a button, so what do we mean when we say
“React is declarative — it's like saying I want a button”?

Let’s break it down step-by-step 👇

🔍 What Declarative Really Means in React


Yes, you’re still writing a button, but you're describing the end result, not how the system
should build it step-by-step.

Compare it to a blueprint:
You say:

jsx
Copy code
<button onClick={handleClick}>Click Me</button>

And React does the rest:

● Creates the element.

● Puts it in the right place in the DOM.

● Updates it when state/props change.

● Handles memory cleanup, event bindings, etc.

You're not telling it how to:

● Call [Link]()

● Attach it with appendChild()

● Bind addEventListener()

● Place it inside a div


● Remove it later

React says:

“Just tell me what UI should look like, and I’ll take care of the how.”

React was created by Jordan Walke, a Facebook software engineer. React was:

● First deployed on a Facebook news feed in 2011.

● Then later used on Instagram in 2012.

✅ Blank 3 (deployed on a → Facebook news feed).


✅ Blank 4 (on a → Instagram).

✅ Slide 2: Major Features Offered by React

Here’s a breakdown of the main features shown in the image and text on the right:

🔹 JSX Syntax

● JSX is a syntax extension for JavaScript.

● It allows you to write HTML-like code inside JavaScript.

● Makes the code more readable and expressive.

🔹 Virtual DOM

● React uses a virtual DOM for better performance.

● Instead of directly updating the real DOM (which is slow), it updates a virtual copy and
then syncs changes.

● This results in efficient rendering.

Server-side Rendering

● React can render components on the server side.


● Good for performance and Search Engine Optimization (SEO).

● Content gets delivered faster, and it's more crawlable by search engines.

What is Server-Side Rendering (SSR)?


In Server-Side Rendering, the HTML of your page is generated on the server and then sent
to the browser, ready to display. This makes the content load faster and be visible to search
engines, improving SEO.

Unidirectional Data Flow

● Data flows in a single direction (from parent to child).

● Makes debugging easier and app behavior more predictable.

🔹 Reusable/Composable Components

● You can break down your UI into reusable pieces.

● Helps you manage and maintain code easily.

● Encourages a component-based architecture.

Quick Intro:
● DOM = Document Object Model — it's the structure of HTML elements in the browser.

● Virtual DOM is a lightweight copy of the Real DOM used in libraries like React to make
UI updates faster.

🔴 VIRTUAL DOM COLUMN


Statement Explanation

It is a virtual copy of the ➤ It's not the real DOM, just a lightweight JS
original DOM version used to compare changes.

It is maintained by JavaScript ➤ React (or similar libs) manages this in memory


libraries using JavaScript.

After manipulation, it only re- ➤ React compares the old and new Virtual DOM
renders changed components (called diffing) and only updates parts that
changed.
Updates are lightweight ➤ Because only the changed parts are updated,
it's fast and efficient.

Performance is high and UX is ➤ Smooth and fast updates improve user


optimized experience.

Highly efficient as it performs ➤ Diffing finds differences between Virtual DOM


diffing algorithm versions and updates the minimal amount of
real DOM nodes.

🟡 REAL DOM COLUMN


Statement Explanation

It is a real representation of HTML ➤ The actual structure your browser


elements renders on the page.

It is maintained by the browser after ➤ Browser builds it as it reads HTML.


parsing HTML elements

After manipulation, it re-renders the ➤ Any change might cause full DOM
entire UI refresh — which is slower.

Updates are heavyweight ➤ Because they involve re-rendering and


recalculating layout, style, etc.

Performance is low and the UX quality ➤ Slower page updates can lead to laggy
is low interactions.

Less efficient due to re-rendering of ➤ Even small changes might trigger full
DOM after each update reflows or repaints.

What Are Class Components?


The slide explains that:

"Class components, also known as stateful components, contain state and


lifecycle methods and are written using JavaScript ES6 classes."

So what does this mean?


🔍 Key Concepts
Term Meaning

Class A component created using a JavaScript class instead of a function.


Component

Stateful It can store and manage state (data that can change over time).

Lifecycle Special methods like componentDidMount, componentDidUpdate,


Methods etc., that run at specific times in a component’s life.

ES6 Class A modern way of writing JavaScript classes (introduced in ES6).

🧱 Structure of the Slide


● The diagram shows:

○ Greeting (a class component)

○ Inherits from [Link]

○ Which provides access to:

■ state

■ render() method (used to return JSX/UI)

🧪 Example of a Class Component


Here's a simple class-based React component that displays a greeting message and a button to
change it:

jsx
Copy code
import React, { Component } from 'react';

class Greeting extends Component {


constructor() {
super(); // Required to use "this"
[Link] = {
message: 'Hello, welcome to React!'
};
}
changeMessage = () => {
[Link]({ message: 'You clicked the button!' });
}

render() {
return (
<div>
<h2>{[Link]}</h2>
<button onClick={[Link]}>Click Me</button>
</div>
);
}
}

export default Greeting;

🧠 What’s Happening Here?

● Greeting is a class component.

● It uses state to store message.

● render() outputs the UI.

● When you click the button, the state updates via [Link](), and React re-
renders the component with the new message.

✅ Why Use Class Components?


Before hooks were introduced in React 16.8, class components were the only way to:

● Use state

● Use lifecycle methods like componentDidMount


Now, function components with hooks (like useState, useEffect) are more common—but
class components are still important to learn and understand.

What does this sentence mean?


"Whenever React calls your component, it gives you a snapshot of the state
for that particular render."

This means:

1. When your component renders (or re-renders), React gives it the current state at that
exact moment in time.

2. That state (and props) will not change during the render, even if you update state
later.

3. Think of it like React is taking a photo (snapshot) of the state and giving it to the
component to work with during that render.

📸 Snapshot Analogy
Imagine you are taking a picture of your desk right now.

● You press the shutter → you capture what your desk looks like at this moment.

● Even if someone adds a cup to your desk right after you take the picture, the picture still
shows the old view — the snapshot doesn't change.

React works like that.

🧪 Code Example to Illustrate It


Let's say you write this:

import React, { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0);

const handleClick = () => {


setCount(count + 1); // uses the current snapshot value
setCount(count + 1); // still uses the same snapshot!
};

return (
<div>
<p>Count: {count}</p>
<button onClick={handleClick}>Increase</button>
</div>
);
}

❗What happens when you click the button?


You might expect the count to increase by 2... but it only increases by 1.

Why? Because:

● On that click, the value of count is 0, let’s say.

● setCount(count + 1) → becomes setCount(1)

● Then again, setCount(count + 1) → still becomes setCount(1) (because


count is still 0 in this render's snapshot)

● React batches them, sees no real change, and only updates to 1.

✅ How to Fix This with Functional Updates


If you want to update state based on the latest value, use the functional form of setState:

setCount(prev => prev + 1);


setCount(prev => prev + 1);

Now it correctly increments twice, because:


● The first call sets it to 1.

● The second call sees the updated value (1) and sets it to 2.

First, What is a "Render"?


When React renders a component:

1. It calls your component function or class render().

2. It reads the current state and props.

3. It creates the UI output (usually virtual DOM).

4. It updates the real DOM after the render is done.

💡 Now, What Does Mid-Render Mean?


“Mid-render” refers to during that exact process — while React is still executing your
component’s code to figure out what to display.

So, mid-render = the time when your component is being executed (e.g., your JSX is being
returned).

🧠 What Happens When You Call setState() Mid-Render?


Let’s look at a quick (invalid) example:

function MyComponent() {

const [count, setCount] = useState(0);

// ❌ Don't do this!

setCount(count + 1);
return <div>{count}</div>;

You’re calling setCount() during render — this means you're trying to change the state while
React is still in the middle of calculating what to show.

🔒 But React Doesn't Allow State to Change Mid-Render

React protects you by not letting the state change instantly. So even if you call setState()
during render, the actual state stays the same until React finishes the render and does a new
one.

Think of it like:
React says — “Hold on! Let me finish drawing everything first. THEN I’ll handle
your state update and do another render.”

✅ What Should You Do Instead?

Only call setState() in:

● Event handlers (like onClick)

● Effects (useEffect)

● Lifecycle methods (like componentDidMount)

Example (✅ correct way):

function MyComponent() {

const [count, setCount] = useState(0);

const handleClick = () => {

setCount(count + 1); // happens outside render, inside event

};
return <button onClick={handleClick}>Click {count}</button>;

PROPS (Properties)
1. Blank 1: immutable

Props are immutable, meaning they cannot be changed by the component that
receives them. They are read-only.

2. Blank 2: argument

Props act like arguments passed to a function, allowing customization of what the
component renders.

3. Blank 3: customize

Props can customize the behavior or appearance of components based on passed-in


values.

4. Blank 4: transfer

Props help transfer data from a parent component to a child component.

5. Blank 5: reusable
When you use props, components become reusable, as the same component can
behave differently depending on the props passed to it.

✅ Final Props Column (after filling):


Props (short for "properties") are passed to a component by its parent component
and are immutable meaning that they cannot be modified by the own component
itself.
Props act as an argument for a function. Also, props can be used to customize
the behavior of a component and to transfer data between components.
The components become reusable with the usage of props.

🟢 STATE
1. Blank 1: modified

State can be modified using the useState() hook or [Link]() in class


components.

2. Blank 2: component

When state changes, React re-renders the component that owns that state, to reflect
the new data.

3. Blank 3: become dynamic

Components become dynamic and interactive with state — for example, a counter that
updates on click.

✅ Final State Column (after filling):


The state entity is managed by the component itself and can be modified using
the setter (setState() for class components) function.
Unlike props, state can be modified by the component and is used to manage the
internal state of the component.
i.e. state acts as a component’s memory.
Moreover, changes in the state trigger a re-render of the component.
The components become dynamic with the usage of state alone.

✅ What is a Side Effect in React?


In React, a side effect is anything that affects something outside the scope of the
component — such as:

● Fetching data from an API

● Subscribing to a stream or socket

● Setting up timers (setInterval, setTimeout)

● Directly modifying the DOM

● Logging to the console

● Adding event listeners

These operations are not pure because they don’t just compute and return JSX — they interact
with the outside world.
🎯 Why Use Side Effects Carefully?
React’s rendering is declarative and predictable, but side effects are not. To keep things
predictable, React separates side effects using a special hook: useEffect().

Here is your original code rewritten to demonstrate all three lifecycle variations (mount,
update, unmount) using useEffect in React.

We’ll show:

1. useEffect() with no dependency array – runs on every render

2. useEffect([]) with empty dependency array – runs only on mount/unmount

3. useEffect([count]) with dependency array – runs on mount and when count


updates

✅ 1. No Dependency Array (runs on every


render)
jsx

CopyEdit

import React, { useEffect, useState } from 'react';

function EffectEveryRender() {

const [count, setCount] = useState(0);

useEffect(() => {

[Link] = `Clicked ${count} times`;

[Link]('✅ Effect: Runs on every render');


return () => {

[Link]('🧹 Cleanup: Before next render or unmount');

};

});

return (

<button onClick={() => setCount(count + 1)}>

Clicked {count} times

</button>

);

✅ 2. Empty Dependency Array [] (runs only once on


mount, cleanup on unmount)
jsx

CopyEdit

import React, { useEffect, useState } from 'react';

function EffectOnMountOnly() {

const [count, setCount] = useState(0);

useEffect(() => {

[Link] = 'Component Mounted';


[Link]('✅ Effect: Runs only on mount');

return () => {

[Link]('🧹 Cleanup: Runs on unmount');

};

}, []);

return (

<button onClick={() => setCount(count + 1)}>

Clicked {count} times

</button>

);

✅ 3. Dependency Array [count] (runs on mount and


when count changes)
jsx

CopyEdit

import React, { useEffect, useState } from 'react';

function EffectOnCountChange() {

const [count, setCount] = useState(0);


useEffect(() => {

[Link] = `Clicked ${count} times`;

[Link](`✅ Effect: Runs on mount and when count changes to ${count}`);

return () => {

[Link]('🧹 Cleanup: Before count changes or on unmount');

};

}, [count]);

return (

<button onClick={() => setCount(count + 1)}>

Clicked {count} times

</button>

);

✅ 1. Run on Every Render (similar to useEffect()


with no dependencies)
In class components, this happens by default in render(), but side effects are usually put in
componentDidUpdate.

jsx

CopyEdit

import React from 'react';

class EveryRenderClass extends [Link] {

state = { count: 0 };
componentDidUpdate() {

[Link] = `Clicked ${[Link]} times`;

[Link]('✅ componentDidUpdate: runs on every render after update');

render() {

return (

<button onClick={() => [Link]({ count: [Link] +


1 })}>

Clicked {[Link]} times

</button>

);

✅ 2. Run Only on Mount and Unmount (similar to


useEffect([]))
This is done using componentDidMount() and componentWillUnmount().

jsx

CopyEdit

import React from 'react';

class MountUnmountClass extends [Link] {


state = { count: 0 };

componentDidMount() {

[Link] = 'Component Mounted';

[Link]('✅ componentDidMount: runs only once when mounted');

componentWillUnmount() {

[Link]('🧹 componentWillUnmount: runs on unmount');

render() {

return (

<button onClick={() => [Link]({ count: [Link] +


1 })}>

Clicked {[Link]} times

</button>

);

✅ 3. Run on Mount and When count Changes


(similar to useEffect([count]))
This requires checking the specific state change inside componentDidUpdate.
jsx

CopyEdit

import React from 'react';

class CountChangeClass extends [Link] {

state = { count: 0 };

componentDidMount() {

[Link] = `Clicked ${[Link]} times`;

[Link]('✅ componentDidMount: runs on mount');

componentDidUpdate(prevProps, prevState) {

if ([Link] !== [Link]) {

[Link] = `Clicked ${[Link]} times`;

[Link](`✅ componentDidUpdate: count changed to ${[Link]}`);

componentWillUnmount() {

[Link]('🧹 componentWillUnmount: runs on unmount');

render() {

return (
<button onClick={() => [Link]({ count: [Link] +
1 })}>

Clicked {[Link]} times

</button>

);

WEEK:04
Slide 1: JS Runtime Environments
✅ Filled Blanks & Key Points:

● V8 is Google’s JavaScript engine (used in Chrome and other browsers).

● SpiderMonkey is Mozilla’s engine and used in Firefox.

● Chakra is Microsoft’s runtime engine. It was originally used in Internet Explorer/Edge.

● In December 2018, Microsoft decided to adopt Chromium (Google’s open-source


browser project).

● JS runtimes are also used in server-side development, mobile apps, IoT.

● Most importantly for us: the [Link] platform is built on top of V8.

💡 Explanation:

JavaScript runtime environments are systems that provide the tools needed to execute
JavaScript code. While browsers like Chrome use V8, [Link] also uses V8 to run JavaScript
outside the browser, allowing server-side development with JS.

Slide 2: JS Engines - Interpret or Compile?


✅ Filled Blanks & Key Points:
● Today’s JavaScript engines both interpret and compile by employing so-called just-in-
time (JIT) compilation.

● JavaScript code that is run repeatedly such as often-called functions is eventually


compiled and no longer interpreted.

💡 Explanation:

Modern JavaScript engines like V8 use JIT (Just-In-Time) compilation. Instead of interpreting all
code line-by-line or compiling everything upfront, JIT compiles frequently used code on the fly
for better performance. This allows JavaScript to be fast while remaining flexible.

Slide 3: What TypeScript Offers


✅ Filled Blanks & Key Points:

● Three of the most well-known languages are TypeScript, CoffeeScript, and Dart.

● JavaScript is a dynamically typed language.

● TypeScript allows you to do that by enabling static (static/dynamic) type checking.

💡 Explanation:

JavaScript is dynamically typed, meaning variables can hold any type and change over time —
which leads to bugs. TypeScript adds static typing to JS, allowing you to define and check
types at compile time. It helps catch errors early, improves code readability, and provides a
better development experience with features like IntelliSense.

🔄 What is Hoisting?
Hoisting is JavaScript’s default behavior of moving declarations to the top of the
current scope (either global or function scope) before the code is executed.

In simple terms:
💡 You can use some things before you declare them.

🎯 Example with var:


js

CopyEdit
[Link](a); // undefined

var a = 5;

✅ What’s happening behind the scenes:

JavaScript "hoists" the var a to the top like this:

var a; // hoisted

[Link](a); // undefined

a = 5;

So the declaration is hoisted, but not the assignment.

❌ Example with let / const:


[Link](b); // ❌ ReferenceError

let b = 10;

● let and const are hoisted too, BUT they are in a temporal dead zone (TDZ).

● You can't access them before the actual line of declaration.

📦 Function Hoisting
✅ Function Declarations are hoisted:
js

CopyEdit

greet(); // "Hello"
function greet() {

[Link]("Hello");

This works because the whole function is hoisted.

❌ Function Expressions are not fully hoisted:


js

CopyEdit

sayHi(); // ❌ TypeError: sayHi is not a function

var sayHi = function () {

[Link]("Hi");

};

Behind the scenes:

js

CopyEdit

var sayHi; // hoisted only the variable

sayHi(); // sayHi is undefined here → error

sayHi = function () { ... };

🔑 Summary Table
Declaration Type Hoisted? Usable before definition? Notes
var ✅ Yes ⚠️Yes (but undefined) Can be confusing

let / const ✅ Yes ❌ No (Temporal Dead Safer, preferred


Zone)

function ✅ Yes ✅ Yes Full hoist

function ⚠️Partially ❌ No Only variable hoisted,


expression not assignment

🔥 Best Practice
● Use let and const instead of var.

● Define functions before using them (even if hoisting works).

● Avoid relying on hoisting — it can lead to bugs.

How to avoid hoisting problems!


There are a few things you can do to avoid hoisting problems: ✓ Always declare
your variables at the top of their scope. This will make your code more readable and
easier to maintain. ✓ Use the let or const keywords to declare your variables
instead of the var keyword. let and const variables are not hoisted, so they can only
be used after they are declared. ✓ Use JavaScript’s strict mode. Strict mode
prevents you from using undeclared variables, which can help to catch hoisting
problems
First, look at the code:

var x = six(); // CASE 1

function six() { return 6; }

var y = seven(); // CASE 2

var seven = function () { return 7; };\

[Link](x + " - " + y);

Step 1: What Happens in CASE 1?


(Function Declaration)
var x = six();

function six() { return 6; }

● function six() {} is a function declaration.

● In JavaScript, function declarations are hoisted completely — both the function


name and its body.

● So the function six is available even before its place in the code.

● ✅ six() runs properly and returns 6.

Result for x:
x = 6

Step 2: What Happens in CASE 2?


(Function Expression)
var y = seven();

var seven = function () { return 7; };

● var seven = function () {} is a function expression.

In hoisting, only the var seven is hoisted, but without a value.


Meaning at the start:

var seven; // undefined

Then, later, seven is assigned the function:


seven = function() { return 7; };

● ❌ But at the moment you call seven(), seven is still undefined.

● Calling undefined() causes a TypeError: seven is not a function.

Step 3: Final Result


● x = 6

● y = Error (TypeError)

Thus, the output will NOT reach [Link](x + " - " + y) because the program
will crash at var y = seven();.

✅ Final Answer:
● Output:

TypeError: seven is not a function


● In our example, the JavaScript runtimehoiststhe declaration
ofsixto the top; it is processed before the remaining code is
executed. Expressions are not hoisted.

✅ var

Scope: Function-scoped.

Hoisting: Yes, hoisted to the top of the function but not initialized.

Redeclaration: Allowed.

Use case: Old way of declaring variables. Avoid using it in modern JavaScript.

function example() {

[Link](x); // undefined (not error)

var x = 10;

[Link](x); // 10

✅ let

Scope: Block-scoped ({ ... }).

Hoisting: Yes, but not initialized — you get a ReferenceError if accessed before declaration.

Redeclaration: Not allowed in the same scope.

Use case: Use when the variable's value will change.

Edit
{

let x = 10;

x = 20; // ✅ allowed

let x = 30; // ❌ Error (in same scope)

✅ const

Scope: Block-scoped (same as let).

Hoisting: Same as let.

Redeclaration: Not allowed.

Reassignment: ❌ Not allowed.

Use case: Use for constants (unchanging values). Note: const objects and arrays can still be
mutated.

Edit

const y = 10;

y = 20; // ❌ Error

const obj = { name: "Ali" };

[Link] = "Ahmed"; // ✅ allowed (mutating object property)

⚡ Summary:

Keyword Scope Reassign? Redeclare? Hoisted?

var Function ✅ Yes ✅ Yes ✅ Yes


let Block ✅ Yes ❌ No ✅ (TDZ)

const Block ❌ No ❌ No ✅ (TDZ)

TDZ = Temporal Dead Zone — the time between entering scope and variable declaration where
access throws an error.

JavaScript Hoisting — it's the idea that variable and function declarations (NOT their
assignments) are moved ("hoisted") to the top of their scope before the code actually runs.

Slide 1 (Top Half) - Functions and


Variables are Hoisted

Left Side Example (global x and y):

function f() {

x = 5;

y = 3;

f();

[Link](x); // 5

[Link](y); // 3

🔵 Explanation:

● Inside the function f(), we assign values to x and y.

● But x and y are NOT declared with var, let, or const.

● So JavaScript treats x and y as global variables automatically.


● When you call f(), x becomes 5, and y becomes 3, globally.

● So [Link](x) prints 5 and [Link](y) prints 3.

📝 Important: When you don't use var, let, or const, variables become global — BAD
PRACTICE!

Right Side Example (local a and b):

function f() {

a = 5;

b = 3;

var a, b; // variable declaration

f();

[Link](a); // ReferenceError

[Link](b);

🔵 Explanation:

● Now we have var a, b; inside the function.

● Because of hoisting, JavaScript moves the var a, b; declaration to the top of the
function f().

● So internally, it looks like:

function f() {

var a, b;

a = 5;

b = 3;
}

● Here, a and b are local to the function f().

● Outside the function (in [Link](a)), they do not exist — that's why you get a
ReferenceError.

📝 Key Point:

● var declarations are hoisted (moved to top) with undefined value.

● Assignments (like a = 5) are NOT hoisted.

✅ Summary of the top half:

● If no var, let, or const, the variable becomes global.

● If var is used, the variable is hoisted to the top of the function but stays inside the
function (local).

Slide 2 (Bottom Half) - Deeper into


Variable Hoisting Example

Example code:

var a = 10;

function print() {

[Link](a);

var a = 20;
[Link](a);

print();

What's happening during hoisting:


JavaScript internally does this:

var a = 10;

function print() {

var a; // Hoisted declaration

[Link](a); // undefined

a = 20;

[Link](a); // 20

🔵 Line-by-line behavior:

1. Global scope: a = 10.

2. Function print is called:

○ Inside print, because of hoisting, var a is moved to the top.

○ So now there’s a new local a inside the function (separate from global a).

3. First [Link](a) — since the local a is declared but not assigned yet, it prints
undefined.

4. Then a = 20; — now local a becomes 20.

5. Second [Link](a) — prints 20.


✅ Important Takeaways from bottom half:

● Only declarations are hoisted (var a;), not initializations (= 20).

● Inside a function, a local variable shadows the global variable if declared with var.

● So [Link](a) inside the function refers to local a, not global a.

SCOPING:

Full sentence filled:

Scoping is the context in which values and expressions are "visible or


accessible".
In contrast to other languages, JavaScript has very few scopes:
A global scope, function scope, and block scope.
A block is used to group a number of statements together with a pair of curly
braces {}.

If you declare a variable inside a function with let, its scope will be local to that function
— it will only exist and be accessible inside that function.

The difference between let and const is that const does not allow the
reassignment or redeclaration of a variable. The originally assigned element though
can change.

✅ So, the first blank = const

Table Fill:

here/how Scope

var declared within a function Function scope

var declared outside of a function Global scope

let (ES6) Block scope

const (ES6) Block scope


variable declaration without var/let/const Global scope (if not in strict
mode)

✅ const with arrays and objects in JavaScript

● const means the variable binding cannot change.

● But the contents of an array or object can still be modified.

📚 const with Arrays

const numbers = [1, 2, 3];

[Link](4); // ✅ allowed

[Link](numbers); // [1, 2, 3, 4]

numbers[0] = 100; // ✅ allowed

[Link](numbers); // [100, 2, 3, 4]

// numbers = [5, 6, 7]; // ❌ Error! Cannot reassign a const variable

📚 const with Objects

const person = { name: "Ali", age: 21 };

[Link] = 22; // ✅ allowed

[Link](person); // { name: "Ali", age: 22 }

[Link] = "Lahore"; // ✅ allowed (adding new property)

[Link](person); // { name: "Ali", age: 22, city: "Lahore" }


// person = { name: "Ahmed" }; // ❌ Error! Cannot reassign a const variable

🧠 Why?

When you use const, the reference (memory address) stays constant, but the data inside
the array or object can still be updated.

🔥 Quick Rule:

Action Allowed
?

Change array elements ✅ Yes

Add/remove object props ✅ Yes

Reassign whole ❌ No
array/object

Summary Table for Your Case:

Line OK / Why? Error (if any)


Not
OK
a = "hello OK let allows None
world"; reassignment

b = "hello ❌ Not const cannot be TypeError:


world"; OK reassigned Assignment to
constant variable

b[0] = -1; OK You can change None


elements inside a
const array

[Link] OK Just printing the None


g(b); modified array

In the code above, var i haS function scope, but we actually need it to be of block
scope,such that every function has its own separate scope, allowing printing the correct value
instead of sharing the same copy of it Waiting for 1 second between printouts one by one.

🌟 What’s happening in the new example?


You have this JavaScript code:

javascript

Copy code

for (var i = 1; i <= 10; i++) {

setTimeout(function() {

[Link](i);

}, 1000);

You are trying to:


● Print numbers 1 to 10.

● Each after a delay (after 1 second).

🌟 Understanding each part:


1. for loop runs very fast, almost instantly.

2. setTimeout says:
“Hey, after 1 second, run this [Link](i)."

3. But var i does not belong to just inside the {} of the loop.
It’s shared across the whole function.

Meaning:

● When the timers (the setTimeouts) actually run (after 1 second),

● The for loop is already finished.

● By that time, i has become 11 (because the loop stops when i > 10).

So all the setTimeouts print 11, not 1 to 10!

🌟 Very simple way to imagine:


Imagine you set 10 alarms right now, but instead of saving "this is alarm 1, alarm 2, alarm 3...",
you only write one note saying "check the clock".

After 1 second, when alarms ring:

● You check the clock.

● The clock shows 11 (because time has moved).

● So, you announce "11" every time!

Suppose you write:


js

CopyEdit

for (var i = 0; i < 5; i++) {

setTimeout(() => {

[Link](i);

}, 1000);

👉 What happens?

● var is function-scoped, not block-scoped.

● By the time the setTimeout actually runs after 1 second, the for loop has already
finished.

● i will be 5 at that point.

So output:

bash

CopyEdit

NOT 0, 1, 2, 3, 4 — because all the setTimeouts are sharing the same i.

✅ How to fix it (properly print 0 1 2 3 4)?


Use let instead of var:

js

CopyEdit

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

setTimeout(() => {

[Link](i);

}, 1000);

● let is block-scoped, so each iteration gets its own copy of i.

● After 1 second, it correctly prints:

bash

CopyEdit

🧠 Why?

● var → single shared i for all closures.

● let → fresh i for each loop iteration.


Would you also like me to show you another way (using var but fixing it with a closure)? It's
super interesting! 🚀

4o

You said:

still did not get it why does it happen

ChatGPT said:

Alright — let me explain it even more simply, like we are sitting side-by-side. 🧠✨

Imagine this code:

js

CopyEdit

for (var i = 0; i < 5; i++) {

setTimeout(() => {

[Link](i);

}, 1000);

What's happening, step-by-step:

1. The for loop runs very fast — almost instantly — before any setTimeout even fires.

2. During each loop, it creates a setTimeout, which says:

"After 1 second, I'll print i."

3. But! setTimeout does NOT run immediately. It waits 1 second.

4. Meanwhile, the for loop finishes. i keeps increasing: 0 → 1 → 2 → 3 → 4 → and


finally 5.

5. Now, after 1 second, the timer goes off...


6. Each setTimeout looks at i and says, "What's the value of i now?"

7. i is already 5 for all of them, because var shares the same i.

Thus, it prints 5 5 5 5 5.

🔥 Important point:

● var is function-scoped → One single i is used by all the setTimeouts.

● let is block-scoped → Each loop gets its own separate i.

That's why if you do:

js

CopyEdit

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

setTimeout(() => {

[Link](i);

}, 1000);

Each setTimeout has its own personal copy of i — first i=0, then i=1, etc. — correctly
printing 0 1 2 3 4.

🎯 One-line summary:

With var, all setTimeouts share the same i, which becomes 5 after the loop
ends.

With let, each setTimeout remembers its own i value.


Would you like me to draw a small diagram to show the memory for var vs let? 🔥
It'll make it crystal clear! 🚀

4o

You said:

dry run

ChatGPT said:

Perfect — you want a dry run!


Let's dry run the var version first step-by-step, like you are the computer. 🧠💻

Code:
js

CopyEdit

for (var i = 0; i < 5; i++) {

setTimeout(() => {

[Link](i);

}, 1000);

Dry Run:
At start:

● i = 0

First loop (i = 0):

● setTimeout(() => [Link](i), 1000) is created.


● It remembers "I'll print i later".

● ➡️Go to next iteration immediately.

Second loop (i = 1):

● setTimeout(() => [Link](i), 1000) is created.

● Again remembers "I'll print i later".

Third loop (i = 2):

● Same, new setTimeout added.

Fourth loop (i = 3):

● Same, new setTimeout added.

Fifth loop (i = 4):

● Same, new setTimeout added.

After 5th loop:

● i becomes 5.

● Loop stops.

Now, after 1 second ⏰:

Each setTimeout wakes up and says:

● "What's the value of i now?"

● i = 5

So it prints:

bash
CopyEdit

💥 Key Point:
All the functions look at the same i, which is now 5.
They don't capture the old i values at the time the setTimeout was made.

✅ If we use let, Dry Run:


js

CopyEdit

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

setTimeout(() => {

[Link](i);

}, 1000);

Now each i is a fresh copy:

Iteration Value of i captured by


setTimeout

1st 0

2nd 1

3rd 2

4th 3

5th 4

So after 1 second:

bash

CopyEdit

✅ Correct output!

In the code above, var i has function scope, but we actually need it to be of block scope
such that every function has its own separate copy of it.

Printing 11 instead of 1 to 10. Waiting for none between print outs one by one.

📢 Slide 1:
Js is a single threaded non-blocking asynchrounous concurrent language

Introduction to V8 and JavaScript Concepts

● It starts by asking "Do you have call back, event loop, call back queue?"
➔ These are features needed to handle asynchronous operations (like timers,
HTTP requests, etc.).

● It also asks, "Do you have DOM, HTTP request, setTimeout?" ➔ DOM, HTTP
requests, setTimeout are NOT part of the JavaScript engine itself — they are
provided by the browser or [Link] environment.

● If you say "No", it means you only have the core JavaScript engine (like V8 for Chrome
and [Link]).

✅ V8 itself only knows how to run JavaScript — it doesn't have a DOM or timers. ✅
Things like setTimeout, DOM manipulation, HTTP requests are outside the V8 engine —
they are provided by the browser APIs or [Link] APIs.

📢 Slide 2:
What is inside the V8 JavaScript Engine?

● The engine has a Parser ➔ It reads your JavaScript file and turns it into an
internal representation called AST (Abstract Syntax Tree).

● Then it compiles that AST into optimized machine code.

● Memory Stack and Heap are important parts:

○ Memory Stack: for managing function calls and static memory (small and fast
access).

○ Heap: for storing larger, dynamic objects like arrays, objects, etc.

✅ In the picture, you can see:

● JS file ➔ Parser ➔ AST ➔ Compiler ➔ Optimized Code ➔ Output on screen.

● Memory Management (Stack and Heap) happens during execution.


📢 Slide 3:
Stack vs Heap — What's the Difference?

Stack Heap

Stack stores static data (known size), like Heap stores dynamic data (objects,
primitive values (numbers, strings, booleans, arrays, functions) that can grow/shrink in
undefined, null). size.

The engine knows exactly how much space is The engine does NOT know the size
needed ahead of time. before — so it uses flexible memory
allocation.

Access is fast because the stack is organized Access is slower because heap is bigger
and small. and less organized.

STACK:
A stack is a data structure that JavaScript uses to store static data.
Static data is data where the engine knows the size at compile time.
In JavaScript, this includes primitive values (strings, numbers, booleans,
undefined, and null) and references, which point to objects and functions.

HEAP:
The heap is a different space for storing data where JavaScript stores objects and functions.

Unlike the stack, the engine doesn't allocate a fixed amount of memory for these objects.
Instead, more space will be allocated as needed.

💬 What does "references, which point to


objects and functions" mean?
When JavaScript deals with objects {} and functions function() {},
it does not store the whole object or function inside the stack.
Instead, it only stores a reference (a pointer) in the stack.

👉 This reference is like a little address — it tells JavaScript,


"Hey, the real object or function is over there in the heap memory."
✅ Example:
javascript

Copy code

let x = 5; // primitive → stored directly in the stack

let obj = { a 1 } :// object → reference stored in stack, real object


stored in heap

function greet() { [Link]("Hi"); } // function → reference in stack,


function body in heap

● x is a primitive → its value 5 is stored directly in the stack.

● obj is an object → the reference (pointer to where { a: 1 } is stored) is kept in the


stack, but the actual { a: 1 } is saved in the heap.

● greet is a function → again, only a reference is stored in the stack, but the actual
function code lives in the heap.

🔥 So simply:
● Stack holds primitive values and references.

● Heap holds the actual objects and functions.

● Reference = a memory address that points to where the object or function really is in the
heap.

📚 Fill in the blanks first:


The slide says:

"All variables first point to the stack. In case it's a non-primitive value, the stack
contains a reference to the object in the heap." The memory of the heap is not
ordered in any particular way, which is why we need to keep a reference to it in the
stack. You can think of references as addresses and the objects in the heap as
houses that these addresses belong to.
✅ So the two answers are:

● stack

● heap

🧩 Key Concepts Explained:


1. Stack and Heap in JavaScript:
● Stack:

○ Stack is used for primitive types (like number, string, boolean, undefined,
null, symbol, and bigint).

○ When you create a primitive, its actual value is stored directly on the stack.

○ Stack is organized: it works like a neat pile — you put things on top and remove
from the top (LIFO - Last In First Out).

● Heap:

○ Heap is used for non-primitive types like objects, arrays, and functions.

○ When you create an object, the stack stores a reference (a pointer) to the
actual object, which is sitting somewhere in the heap.

○ Heap is unorganized memory — things are stored in random places, not neatly
ordered.

🔎 Now, look at the Example Code on the


Left:
const person = {

id: 1,

name: 'John',
age: 25,

};

const dog = {

name: 'puppy',

personId: 1,

};

function getOwner(dog, persons) {

return [Link]((person) => [Link] === [Link]);

const name = 'John';

const newPerson = person;

🛠 What Happens Here Step-by-Step:


Code Line What Happens? Stack Heap

const person A new object is created → stored person → { id: 1,


= {...} in heap, and person (variable) holds (reference) name:
a reference to it. 'John',
age: 25 }

const dog = Another object is created → also dog → { name:


{...} stored in heap, dog holds a (reference) 'puppy',
reference. personId: 1
}

function A function is an object too! It’s stored getOwner → function


getOwner(... in the heap, and getOwner holds a (reference) code
) {} reference to it.

const name = A primitive string is stored directly name →


'John' in the stack (no reference needed). 'John'

const newPerson points to the same newPerson →


newPerson = reference as person. No new object same
person; created. Both person and (person's
newPerson point to the same object reference)
in the heap.

🏡 Memory Diagram (Middle Image):


● Stack (left column):

○ Holds variable names and either primitive values or references (addresses).

● Heap (right column):

○ Holds objects and functions (actual big data).

Red arrows show how variables in the stack point to objects/functions in the heap.

🧠 What These Slides Are Teaching:


They explain how the JavaScript call stack works:

● How function calls are added ("pushed") to the stack.

● How function returns are removed ("popped") from the stack.

● How errors like RangeError: Maximum call stack size exceeded happen.

🔵 Slide 1 (Top Section)


Here's the code shown:

function multiply(a, b) {

return a * b;

function square(n) {

return multiply(n, n);

function printSquare(n) {

var squared = square(n);

[Link](squared);

printSquare(4);

✅ What Happens Step-by-Step:

1. printSquare(4) is called:

○ JavaScript pushes printSquare(4) onto the call stack.

○ (It’s waiting to finish printSquare, but it can’t yet because it needs to do more.)

2. Inside printSquare, it calls square(n):

○ Now square(4) is called, so JavaScript pushes square(4) onto the stack.

3. Inside square(n), it calls multiply(n, n):

○ Now multiply(4, 4) is called, so JavaScript pushes multiply(4, 4)


onto the stack.

📦 So the stack now looks like:

Order Stack Content


3 multiply(4,4)

2 square(4)

1 printSquare(4)

0 main() (the global


script)

Each time you call a function, it’s added to the top of the stack.

🔵 Slide 2 (Middle Section)


🔴 Very Important Concept:

If we return from a function, we pop it from the stack.

Now let's continue from the previous step:

4. multiply(4,4) finishes execution (returns 16):

○ JavaScript removes multiply(4,4) from the top of the stack (pops it).

○ It returns the result 16 to square(4).

5. Now square(4) has what it needs (16), so it finishes too:

○ JavaScript pops square(4) off the stack.

6. Now printSquare(4) can log the result (16):

○ It does [Link](16) and pops printSquare(4) off the stack.

Finally, the stack goes back to just:

● main()

And then when everything is done, even main() is gone — the stack is empty!
🔵 Slide 3 (Bottom Section)
🚨 When Things Go Wrong: Infinite Recursion

The slide shows this code:

function foo() {

return foo();

foo();

Here’s what happens:

● foo() calls itself again and again and again...

● Each call pushes another foo() onto the stack.

● The stack gets bigger and bigger without end.

● Eventually, the browser runs out of memory space for the stack.

💥 Then you get an error:

RangeError: Maximum call stack size exceeded

🔔 This error means: "You have called too many functions without finishing them — the stack is
full!"

Node is all about asynchronous function execution.


All these asynchronous callbacks don’t run immediately

and are going to run sometime later, so can’t be pushed immediately inside the call stack,

unlike synchronous functions like [Link](), mathematical operations.

Concurrency in JS— One Thing at a Time, except not Really, Async Callbacks” No browser will
allow the JavaScript of a single page to run concurrently. However, JavaScript does support
asynchronous functions like the setTimeOut function, and while this allows some sort of
scheduling, fake concurrency, and starting and stopping of threads, it is not true multi threading.

🔹 The Code:
javascript

CopyEdit

function fn(i) {

setTimeout(function () {

[Link](i);

}, 1000 * i);

for (var i = 1; i <= 10; i++) {

fn(i);

🔹 What's Happening:
1. Function Definition

javascript

CopyEdit

function fn(i) {

setTimeout(function () {

[Link](i);

}, 1000 * i);

● fn(i) is a function that takes a number i as input.


● Inside it, we call setTimeout, which delays running the function that logs i to the
console.

● The delay is 1000 * i milliseconds (which is the same as i seconds).

➡️For example: if i = 3, [Link](3) will be called after 3 seconds.

2. Loop

javascript

CopyEdit

for (var i = 1; i <= 10; i++) {

fn(i);

● This loop goes from i = 1 to i = 10, and calls the function fn(i) each time.

● So you are setting 10 timeouts:

○ First one logs 1 after 1 second

○ Second one logs 2 after 2 seconds

○ ...

○ Tenth one logs 10 after 10 seconds


YOUSUF’S PDF:

❓ Why doesn’t DOM update in the


first code?
In the first code, you have long-running while loops immediately after each other — and inside those
loops, you're showing blocking alert() popups.

➡️In JavaScript, everything runs on one thread (single-threaded).


➡️Browser can only update the DOM (like text on page) when JavaScript is not running anything.

But here’s the problem:

● The first while loop runs for 10 seconds — showing alerts and blocking.

● Immediately after that, DOM update lines ([Link] = ...) run.

● But the browser cannot paint (update) while JavaScript is busy.

● And right after DOM updates, another while loop starts — again blocking the browser.

🧠 So the browser never gets a free moment to actually draw the changes on screen.
It queues the updates, but can only show them after ALL the JavaScript and alerts finish.
That’s why you don’t see the DOM updates immediately.

❓ How does setTimeout fix it in the


second code?
In the second code, you wrapped the second part (the results alert loop) inside a setTimeout(...,
0).

➡️setTimeout(function, 0) does not run immediately.


➡️It tells the browser: "Hey, schedule this code later, after the current stuff is done and DOM has a
chance to update."

Order happens like this now:

1. Run first while loop (blocking alerts).

2. Update the DOM (startTimeDisplay, averageDisplay).

3. Wait a tiny moment (because of setTimeout).

4. Browser paints the DOM updates on the screen ✨.

5. Then setTimeout triggers the second batch of alerts.

✅ Because there is a small gap between DOM updates and second blocking code, the browser finally
gets breathing space to update the page.

🔥 In Simple One-Liner:
● First code: No free time → browser can’t update DOM → stuck until all code finishes.

● Second code with setTimeout: Creates a tiny break → browser updates DOM → then
continues.

Would you also like a visual diagram showing this difference (like a timeline)? 📈 It would make it even
easier to understand! 🚀
Should I make it for you? 🎯

AND HOW DOES THE THIRD CODE EVEN MAKES IT BETTER?

ChatGPT said:

Good question bro — let's break it down very clearly:


❓ How does the third code make it
better?
In the third code, after doing the first blocking part (the first while loop and the DOM updates), it uses
this:

await new Promise((resolve) => requestIdleCallback(resolve));

This line is very important!

🚀 What requestIdleCallback does:


● It tells the browser:
👉 "Wait until you are completely free and idle — then continue running the next code."

● So it pauses and lets the browser breathe.

● During this pause, the browser:

○ Updates the DOM (startTimeDisplay, averageDisplay),

○ Repaints the screen,

○ Handles any small background tasks,

○ And only after that, the second batch (results alert loop) runs.

🔹 1. What is a Promise in JavaScript?


A Promise is an object that represents the eventual completion (or failure) of an asynchronous
operation.

It can be in one of three states:

● pending – still in progress

● fulfilled – operation completed successfully

● rejected – operation failed

Example:

javascript
CopyEdit

let promise = new Promise((resolve, reject) => {

setTimeout(() => resolve("Done!"), 1000);

});

🔹 2. What is async/await?

● async turns a function into a Promise and allows use of await inside.

● await pauses execution until a Promise is resolved.

Example:

javascript

CopyEdit

async function example() {

let result = await somePromise; // waits here

[Link](result);

🔹 3. What is requestIdleCallback()?
● It is a built-in browser API.

● It tells the browser: "Run this function when the main thread is free (idle)."

● It’s useful for background or non-urgent work.

Example:

javascript

CopyEdit
requestIdleCallback(() => {

[Link]("Browser is idle. Do background work now.");

});

📌 Not supported in all browsers (like Safari).

🔹 How async/await + Promise is used here


📍 Line:

js

CopyEdit

await new Promise((resolve) => requestIdleCallback(resolve));

● new Promise(...): Creates a promise.

● Inside, requestIdleCallback(resolve) tells the browser: "Call resolve when it is idle".

● await pauses the function until that happens.

This means the function waits for the browser to be idle before continuing to show more alerts.

⚡ So Compared to First and Second


Codes:
Version Browser Opportunity to Notes
Update DOM?

1st Code ❌ No Continuous blocking, no breathing space

2nd 🟡 Little bit setTimeout(0) gives a tiny break


Code

3rd Code ✅ Fully yes requestIdleCallback waits until browser is really


idle, so perfect update timing

GUESS THE OUTPUT:

First, your code:

[Link]('stack [1]');

setTimeout(() => [Link]("macro [2]"), 0);

setTimeout(() => [Link]("macro [3]"), 1);

const p = [Link]();

[Link](() => {

setTimeout(() => {

[Link]('stack [4]');

setTimeout(() => [Link]("macro [5]"), 0);

[Link](() => [Link]('micro [6]'));

}, 0);

[Link]("stack [7]");

});

[Link]("macro [8]");

📚 RULES (important before dry run):


Concept Priority
Stack Synchronous code runs immediately

Microtasks (Promise Run after stack is empty but before any macrotask (timeout,
.then) interval)

Macrotasks (setTimeout) Run later via event loop

Microtasks always have higher priority than macrotasks.

🛠 Step-by-Step Dry Run:


1. Start executing synchronously (stack)

● [Link]('stack [1]') → prints immediately ✅

🖨 Output so far:

cpp

Copy code

stack [1]

● setTimeout(..., 0) for macro [2] → scheduled as a macrotask.

● setTimeout(..., 1) for macro [3] → scheduled as a macrotask (very similar, no


big difference for now).

● const p = [Link]() → resolves immediately, so:


javascript

Copy code

[Link](...)

→ schedules a microtask to run later after the current stack is empty.

Inside the then:

● another setTimeout(...) is set inside (for stack [4] and later).

● also inside this then, there is [Link]("stack [7]").

Important:

● In a .then(), synchronous code inside it (like [Link]('stack [7]')) runs


during the microtask execution.

● Any nested timeouts inside .then() will again be macrotasks scheduled later.

● [Link]('macro [8]') → this is still synchronous, so prints immediately.

🖨 Output now:

css

Copy code

stack [1]

macro [8]

2. Stack is now empty ✅


👉 Time to process microtasks first (Promises)!

● The promise [Link](...) is processed now.


Inside that .then:

● First, setTimeout (for stack [4]) is scheduled → macrotask.

● Then, [Link]('stack [7]') → prints immediately during the microtask.

🖨 Output now:

css

Copy code

stack [1]

macro [8]

stack [7]

3. After microtasks are done ➡️Now event loop starts macrotasks


Macrotask Queue Order Now:

1. macro [2] (timeout 0)

2. macro [3] (timeout 1)

3. stack [4] (timeout 0) (this came from inside the Promise .then)

(Remember, even 0ms or 1ms timers are not guaranteed perfect timing, but their order of
scheduling matters.)

4. First Macrotask → macro [2]

● [Link]('macro [2]') prints.

🖨 Output:

css

Copy code
stack [1]

macro [8]

stack [7]

macro [2]

5. Second Macrotask → macro [3]

● [Link]('macro [3]') prints.

🖨 Output:

css

Copy code

stack [1]

macro [8]

stack [7]

macro [2]

macro [3]

6. Third Macrotask → stack [4]

● [Link]('stack [4]') prints.

● Inside this timeout:

○ Schedules another setTimeout(() => [Link]('macro [5]'), 0)


→ scheduled macrotask.

○ Schedules [Link](() => [Link]('micro [6]')) → schedules


another microtask!
7. Now stack is empty again → Check for microtasks first!
● Run the microtask:

○ [Link]('micro [6]') prints.

🖨 Output:

css

Copy code

stack [1]

macro [8]

stack [7]

macro [2]

macro [3]

stack [4]

micro [6]

8. After microtasks → back to macrotasks

Now, macro [5] (timeout 0) is ready:

● [Link]('macro [5]') prints.

🖨 Final Output:

css

Copy code

stack [1]

macro [8]
stack [7]

macro [2]

macro [3]

stack [4]

micro [6]

macro [5]

WEEK:05
What is [Link]?
[Link] is an open-source, cross-platform JavaScript runtime environment that allows
developers to execute JavaScript code on the server side. It was released in 2009 by Ryan
Dahl and is built on the Chrome V8 JavaScript engine. [Link] enables the development of
scalable and efficient network applications by allowing JavaScript to run outside of a web
browser.

📚 Key Features of [Link] (Explained in


Simple Words):

1. Asynchronous and Event-Driven:


● In [Link], things don't block or wait — it keeps moving without getting stuck on one
request.

● Suppose a user asks for data from a database — [Link] sends the request and
moves on without waiting.

● When the database replies back, an event tells [Link]: "Hey! The data is ready," and
then [Link] responds.

● Result: It can handle many users at the same time without slowing down, making it
perfect for real-time apps like chat apps, live updates, etc.
2. Single-Threaded with Non-Blocking I/O:
● Normally, handling many users would require many threads (heavyweight 💪).

● But [Link] is smart — it uses only ONE thread (like a single line of workers) and still
manages thousands of users.

● Non-blocking I/O means when [Link] does input/output tasks (like reading files,
fetching database results), it doesn’t block the thread. It moves on and deals with
results later.

● Result: High performance 🔥 even with huge traffic and less memory usage.

3. Cross-Platform:
● You don't have to worry about "Will my code work on Windows? Linux? macOS?"

● [Link] can run anywhere easily across all major operating systems.

● Result: One codebase ➔ runs everywhere 💻 without big changes.

4. Rich Ecosystem (NPM):


● NPM (Node Package Manager) is a massive library store where developers share
reusable code (called packages).

● Need to send emails? Build a server? Connect to a database? ➔ There’s


already a package for that.

● It saves time and effort because you don't have to code everything from scratch.

● Result: Faster development, more power, and better apps 🚀

The function inside a class after ES6 allows multiple instances to share the same method,
improving memory efficiency.

🧠 In JavaScript classes (ES6):


● The constructor must be named exactly as constructor.

● You cannot name it anything else (like the class name).


📚 Example:
✅ Correct way:

javascript

Copy code

class Person {

constructor(name) { // Must be named 'constructor'

[Link] = name;

❌ Wrong way (this will give an error):

javascript

Copy code

class Person {

Person(name) { // ❌ Not allowed

[Link] = name;

You wrote this JavaScript class:

javascript

Copy code
class game {

constructor(n) {

[Link] = n;

printName() {

[Link]([Link]);

Then you created two objects:

javascript

Copy code

let g1 = new game("chess");

let g2 = new game("football");

and checked:

javascript
Copy code

[Link]([Link] === [Link]);

You are getting true because in a JavaScript class, methods like printName() are
automatically shared between all instances.

They are not re-created for every object.


Instead, the method printName is stored once on the prototype of the class, and every
object (g1, g2, etc.) just points to the same function.

👉 In short:
[Link] and [Link] refer to the same function in memory.
That's why [Link] === [Link] is true.

Quick visualization:

text

Copy code

[Link] --> one function stored here

[Link] -----------^ (points to it)

[Link] -----------^ (points to it)

If you had instead defined printName inside the constructor, like this:

javascript
Copy code

class game {

constructor(n) {

[Link] = n;

[Link] = function() {

[Link]([Link]);

then each object would have its own copy of printName, and:

javascript

Copy code

[Link]([Link] === [Link]);

would be false.

The function inside a class after ES6 allows multiple instances to share the same method,
improving memory efficiency.
🧠 What’s happening in the code?
You have this class:

javascript

Copy code

class Game {

Game(n) {

[Link]("Game method called!");

[Link] = n;

printName() {

[Link]([Link]);

And you create an object:

javascript

Copy code

let g1 = new Game("Chess");

[Link]();

🚨 But wait — this is wrong usage!


In JavaScript classes, the method that is automatically called when you do new Game()
must be called constructor(), not just any method name.

❌ The problem here:


● You defined a method called Game(n), but in JavaScript it’s NOT the constructor.

● The JavaScript engine expects a method called exactly constructor() inside a


class.

● Since you didn’t define a constructor, JavaScript makes a default empty


constructor by itself.

● The Game(n) method is ignored unless you manually call it yourself (which you didn’t).

🔥 So, what will happen?


When you do

let g1 = new Game("Chess");

● No "Game method called!" will be printed (because Game(n) is NOT called


automatically).

● No value is assigned to [Link] because the method Game(n) was never


executed.

● So [Link] is undefined.

Then:

[Link]():
● [Link]([Link]); will print undefined.

📋 Final Output:
undefined

✅ No "Game method called!" printed.


✅ Only undefined printed when calling printName().

"This proves that Game(n) is just a regular method, your object instances never call it
automatically."

Step-by-Step Explanation:

1. typeof Game

● In JavaScript, classes are just special kinds of functions.


● Internally, a class is syntactic sugar over a function constructor + prototype
methods.
● So:

javascript

Copy code

typeof Game // ➔ "function"

✅ Answer: function

2. [Link]

● printName() is defined inside the class, but it goes on the prototype of the Game
class automatically.
● So [Link] exists and is a function.

Thus:

javascript

Copy code
[Link]([Link]);

prints something like:

javascript

Copy code

function printName() { [Link]([Link]); }

or simply shows it’s a function.

✅ Answer: [Function: printName]


(or just "function" if printed simply).

Fill in the Blanks on the Right:

Sentence Correct Fill

Class is just a _________ function

printName() is a _________ prototype


method method

🧠 What These Slides Are Teaching:


Topic:
👉 Prototypal Inheritance in JavaScript

🟩 First Part (Top Half of the Slide)


● Main idea:
When you create a child object using a constructor (like Array, String, Number, etc.),
the child object automatically gets access to everything inside the constructor’s
prototype.

● What is a prototype?
It’s like a hidden backpack 🎒 that every JavaScript object carries.
This backpack contains useful methods and properties.

● How inheritance happens:

○ Your object doesn’t "copy" methods from the prototype.

○ Instead, it borrows or looks up into the prototype chain when it needs


something.

● Example:

○ Arrays (like [1, 2, 3]) can use .length, .push(), .map(), etc.

○ Strings ("hello") can use .split(), .toUpperCase(), etc.

○ This happens because [Link] and [Link] have these


methods, and your object inherits from them!

🟩 Second Part (Bottom Diagram)


● This is the “Prototypal Inheritance Tree”
Here's what it shows:

○ At the very top, everything starts from [Link].


(Every object in JS is based on Object by default.)

● Then from Object come specialized types:

○ Array → has methods like .map(), .filter(), .length


○ String → has .split(), .toUpperCase(), .length

○ Number → has .toFixed(), .toPrecision()

○ Function → has .call(), .apply(), .bind()

○ Boolean → has .toString(), etc.

● So if your object doesn't find a method on itself,


it climbs up the prototype chain (like a ladder) and looks inside its parent’s
prototype!

📝 Simple Example:
javascript

Copy code

const arr = [1, 2, 3];

[Link](x => x * 2);

// Where is .map() coming from?

// -> It’s from [Link]!

[Link]('length');

// Where is .hasOwnProperty() coming from?

// -> It’s from [Link]! (because arrays ultimately inherit


from Object)

🔥 Quick Summary:
Concept Meaning

Prototype A hidden object where methods are stored

Inheritance Objects can use methods from their prototype

Chain Objects look upward (parent → grandparent) for missing


methods

Object at Everything eventually inherits from [Link]


Top
In JavaScript, Arrays and Functions are objects
and have an internal [[Prototype]] property.
However, String, Number, and Boolean are
primitive types, but JavaScript temporarily
wraps them in their object counterparts (String,
Number, Boolean) when accessing properties or
methods.

string is also an object ?


YES 🔥💯

In JavaScript, a string is a primitive, but when you use it like an object, JavaScript
automatically wraps it into a String object behind the scenes.

Let me explain very simply:

🧠 Normally:
const str = "hello";
● str is a primitive type (not an object).

🧹 BUT — when you do this:


[Link]([Link]());

JavaScript automatically does this for you:

const temp = new String(str);

[Link]([Link]());

● It wraps your primitive "hello" into an object temporarily.

● Calls the method .toUpperCase().

● Then throws away the temporary object.

🎯 So in short:
What you see What happens behind

"hello" new
String("hello")

✅ That's why you can use methods like .toUpperCase(), .slice(), .charAt() on
strings!
📦 Small example to prove it:
const str = "hello";

[Link](typeof str); // "string" (primitive)

const objStr = new String("hello");

[Link](typeof objStr); // "object" (real object)

See the difference?

● "hello" is primitive.

● new String("hello") is a real object.

🛠 Visual:
"hello" (primitive)

↪ temporarily becomes new String("hello")

↪ uses methods like toUpperCase()

↪ discarded

💥 FINAL LINE:
✅ String is primitive, but when you use methods on it, JavaScript treats it like an
object temporarily.

Here’s the filled-in version:


1. Before ES6 (2015), developers had to explicitly use prototypes to share methods.

2. ES6 class introduced a more readable way to define classes, making prototype less visible.

3. But internally, JavaScript still uses prototypes and ES6 class update just hides the prototype.

4. Understanding prototypes helps you debug and optimize JS code better.

5. Prototypes allow method sharing & memory efficiency. Without prototypes, every object would
have its own copy of methods, leading to huge memory waste.
6.

First Slide Explanation:


The first block of code shows:

function Game(n) {

[Link] = n;

[Link] = function() {

[Link]([Link]);

};

Every time you call new Game("something"), a new printName function is created separately for
each object (g1, g2, etc.).

That's why:

✅ Filled Blanks:

● printName is not shared (each object has its own copy)

● Every time new Game(...) is called, a new function is created in memory.

Key Problem:

● Memory is wasted because each object has its own copy of the same function.

Second Slide Explanation:


Now the code is improved:

function Game(n) {

[Link] = n;

[Link] = function() {

[Link]([Link]);

};

Here, printName is added to the [Link], meaning all objects share the same function!

✅ Filled Blanks:

● Instead of creating a new function for every instance,

● we can store it once in the prototype,

● and let all instances access the same function.

Key Benefit:

● Memory efficient: Only one copy of printName exists, shared across all objects.

Third Slide Explanation (Prototype Chain Search):


Now they explain how JavaScript finds the method when you call [Link]():

✅ Order of Lookup:

1. It first checks the object itself (g1).

2. If not found, it checks the prototype ([Link]).

3. If still not found, it checks [Link] (the top-most prototype).

4. If it finds nothing even there, it returns undefined.


This is called the prototype chain.

Key Concept:

● JavaScript walks up the prototype chain to find methods and properties.

● This is why putting shared methods on [Link] is a good idea!

In JavaScript, any function can act as a constructor when you call it with the new keyword.

So even though this looks like a normal function:

function Game(name) {

[Link] = name;

[Link] = function() {

[Link]([Link]);

};

👉 When you call it like this:

let g1 = new Game("Chess");

It becomes a constructor call.

How it works under the hood when you use new Game("Chess"):
1. A new empty object {} is created.

2. this inside the function points to that new object.

3. Properties ([Link], [Link]) are attached to that object.

4. The new object is returned automatically.

So g1 becomes:

name: "Chess",

printName: function() { [Link]([Link]); }

1. Prototypal Inheritance (Left side)


● Explanation:

○ Here, objects inherit directly from other objects.

○ Example in the image:

■ foo1 and foo2 inherit from Foo.

■ bar1 and bar2 inherit from Bar.

■ Bar might itself inherit from Foo.

● Idea:

○ A copy-like relationship:
Child objects copy properties/methods from parent objects when created.

● Static Binding:
(Orange box in the middle)

○ Early binding → Code is linked at compile time.

○ Compile time → Structure is known before running the program.

○ Method overloading → Methods with the same name but different signatures.
2. Behavior Delegation (Right side)
● Explanation:

○ Here, instead of copying behavior, objects delegate behavior at runtime.

○ Example in the image:

■ foo1 and foo2 point to [Link].

■ bar1 and bar2 point to [Link].

■ [Link] may also link to [Link].

● Idea:

○ A link-like relationship:
Child objects look up their parent’s behavior dynamically if they don't have it.

● Dynamic Binding:
(Gray box in the middle)

○ Late binding → Code is linked at runtime.

○ Runtime → Structure can be flexible and determined when the program runs.

○ Method overriding → Methods can be replaced/modified at runtime.

⚡ Key Difference:
Prototypal Inheritance Behavior Delegation

Copies properties/methods Delegates property/method lookup

More static, less flexible More dynamic, highly flexible

Closer to "classical" inheritance True prototype chain lookup

Early binding (compile time) Late binding (runtime)


WEEK 6

🔵 Slide 1: "Need for Back-end? Who


accepts HTTP requests?"
✨ Big Picture:
This slide explains:

● Why do you need a backend?

● Who handles HTTP requests.

● How the backend and frontend communicate.

● Introduction to [Link] for [Link].

📚 Point-by-point Explanation:
1. Why do we need a backend?
● The backend is needed to connect to a database, fetch data, and process it.

● Example:

○ Frontend says: "Give me all the users!"

○ Backend connects to the Database (DB), retrieves users, maybe formats the data, and
sends it back.

✏️Fill-in:

"Back-end will connect to a database, get some results, and do some processing."

2. Backend exposes an API


● The backend must provide an API (Application Programming Interface).

● This API allows the frontend (React, Vue, Android app, etc.) to request or send data.
✏️Fill-in:

"Back-end will expose REST API that the front-end will use to interact with the DB."

3. Who accepts HTTP requests?


● The backend server (using something like [Link]) accepts HTTP requests from the
frontend app.

✏️Fill-in:

"Backend server will accept HTTP requests from frontend app and use CRUD operations
to interact with the DB."

(CRUD = Create, Read, Update, Delete operations on the database)

4. What is [Link]?
● Express is a simple and powerful web framework built for [Link].

● It helps you easily create APIs and full backend services.

✏️Fill-in:

"Express is a minimal and flexible web application framework for [Link]. It is designed for
building web applications and APIs."

🌟 Summary of Slide 1:
● Backend connects to Database.

● Backend exposes REST API.

● Backend Server accepts HTTP Requests from the frontend.

● It uses CRUD operations.

● [Link] is a popular backend framework for [Link].


🟣 Slide 2: "REST API Client/Server
Operation & What is RESTful API?"
✨ Big Picture:
This slide introduces:

● How REST APIs work.

● The client-server interaction process.

● What a RESTful API is.

📚 Point-by-point Explanation:
1. How REST API Works (Diagram on top half):
● REST Client (usually frontend app) makes a REST Call.

○ Example: GET /users

● The REST API Server receives the request and processes it.

○ Example: It fetches all users from the database.

● The Server then replies to the client with the requested data.

2. REST API Client/Server Process (Text):


● Step 1: Client starts a REST Call.

● Step 2: Server receives the call and processes the request.

● Step 3: Server sends back a response (usually in JSON format).

✅ JSON = JavaScript Object Notation, a lightweight format to send data.

3. What is RESTful API? (Bottom gray diagram)


● Client makes a Request (using HTTP methods: GET, POST, PUT, DELETE) to the Server
(API).

● Server (API) interacts with the Data Storage (like a Database).

● Server sends back a Response to the Client (usually in JSON).

Example:

● Client: "GET all the products!"

● Server: "Here is the product list in JSON format."

REST stands for Representational State Transfer.

It is an architectural style for designing networked applications that relies on stateless communication
and standard HTTP methods like GET, POST, PUT, DELETE, PATCH, etc.

RESTful APIs follow a set of principles that make applications scalable, flexible, and easy to use.

An API (Application Programming Interface) is a set of rules and protocols that allows different software
applications to communicate and exchange data. It acts as a bridge between software systems, enabling
them to interact and share functionality.

Examples:

Google Maps API: Allows websites to embed Google Maps on their pages.

Social Media APIs: Enable applications to connect with social media platforms.

Payment APIs: Allow businesses to integrate payment processing into their applications.

Key RESTful API Principles


Statelessness: The server does not store any client state between requests. Each request must contain
all the information the server needs to understand and process it.

Client-Server Architecture: There is a separation between the client (user interface) and server (data and
logic), ensuring that both can evolve independently.

Uniform Interface: RESTful APIs use a consistent, standardized approach to interacting with resources
using HTTP methods and URLs. This includes standardized naming conventions for resources and
actions.

Cacheability: Responses from the server must be explicitly labeled as cacheable or non-cacheable,
promoting high performance in certain cases.

Layered System: The client does not need to know whether it is directly communicating with the server or
an intermediary.
The concept of a RESTful API is an architectural style — it's a set of design principles and constraints
for how web applications/services should be built — while Express is just one of many tools
(frameworks) you can use to implement that design. In other words, RESTful API design is independent
of the technology used to build the server. You can build a RESTful API using Express, Django, Flask, or
any other framework; the key is that you follow REST principles such as statelessness, a uniform
interface, and proper use of HTTP methods and codes. Express doesn’t force you to build a RESTful API
—it merely provides a environment to implement RESTful design if you choose to do so.

RESTful APIs are web services in their purest form, meaning the service exposes an interface (usually
via HTTP and data formats like JSON) for other software to consume.

Web applications can—and often do—use RESTful APIs as the communication layer between the client
and the server.

This separation aligns with the client-server architecture, ensuring clarity and maintainability in your
project’s design.

All web applications have a server side (which behaves like a web service),

but not every web service is a complete web application.

✓ Name few real-world examples where you have a web service that isn’t a full web
application — meaning it exposes functionality via APIs without providing a complete user
interface (UI).

JSON is not an inherent requirement of the web service model.


Payment gateways, weather APIs, geocoding APIs, and cloud storage APIs are considered web
services
because they make HTTP requests to their API endpoints for data exchange without a built-in user
interface (UI).
They often use JSON because it’s popular today, but JSON is not an inherent requirement of the web
service model.

Payment gateways, weather APIs, geocoding APIs, and cloud storage APIs are considered web services
because they make HTTP requests to their API endpoints for data exchange without a built-in UI. They
often use JSON because it’s popular today, but JSON is not an inherent requirement of the web service
model.
🧠 Quick Clarification:
● Web services → Provide functionality over the web (usually through HTTP) without
needing a UI.

● Endpoints → Specific URLs that the client "hits" to send or receive data.

● UI → User Interface; many web services don't have one — just APIs for machines/apps
to communicate.

✅ JSON is just a popular data format today (easy for humans + machines), but web services could also
use XML, YAML, plain text, or even binary formats if needed.

Endpoints are Fundamental: Every web API exposes endpoints (specific URLs) that represent resources
or services.

Clients make requests (using methods like GET, POST, etc.) to these endpoints, and the server
responds with data (commonly in JSON, XML, etc.).

In many cases, an API is a service without a user [Link], the term “API” can also refer to
function libraries or SDKs that expose a set of function calls.

These aren’t necessarily part of a networked client-server architecture but are still considered APIs
because they define how different software components interact.

Now: What is an API outside of Client-Server?


🔹 Sometimes, APIs are just local libraries inside your app —
NO server, NO network involved.

Example:

[Link](3, 5, 7);

● Math is a built-in API in JavaScript.

● It gives you functions (like max, sqrt, floor).

● But you're not talking to a server!

● You're just calling functions from a library inside your own machine/app.

Key Point:
If an API is just a set of functions or classes that your program can call locally (inside your
app), it’s still called an API, but it’s NOT client-server because it doesn’t involve network
communication.

✅ It's just code talking to code inside your system.


❌ It's not a client sending a request to a server.

🎯 In Simple Words:
If Then

API connects over a network (e.g., fetch weather It’s a client-server interaction.
data)

API is just a bunch of code your app uses internally No network, no client-server — just local
(e.g., Math functions) code interaction.

When discussing the server side alone, the focus is on REST principles — defining resources, routes,
HTTP methods, and ensuring stateless interactions.

Later, when you integrate the front-end, you’ll see how the REST API serves as the communication
bridge between the server and the React application.

This separation lets you build and test the backend independently before connecting it with the client side.

Title: Base URL


You see at the top:

🔵 Base URL:

arduino

Copy code

[Link]

This Base URL is super important because every API request your app (frontend) or server (backend)
makes will start with this Base URL.
🔵 First Paragraph (Top Box) Breakdown
The base URL is a key component in our RESTful API design.

✏️Explanation:

● RESTful API is a method of communication between a client (frontend) and server (backend).

● Base URL is like the "home address" of your server.


Think: "Where should my app send its messages (requests)?"

It ensures that both the front-end and back-end consistently ____ and ____ URLs.

✏️Explanation:

● Frontend (like React) and backend (like Express server) must build and access the URLs in the
same way.

● So the missing words are likely "build" and "access".

For instance, our modern front-end (built with frameworks like React or Angular) will use
this base URL to construct ___________, while our Express server uses it to define its
___________ logic.

✏️Explanation:

● Frontend constructs API request URLs (ex: [Link]

● Backend (Express server) uses it to define route logic.


So missing words could be "request URLs" and "routing".

This uniformity is crucial for seamless communication between client and server.

✏️Meaning:

● If both sides follow the same base, they can communicate easily without mismatch or errors.

The base URL is a key component in our RESTful API design. It ensures that both the front-end
and back-end consistently generate and interpret URLs. For instance, our modern front-end
(built with frameworks like React or Angular) will use this base URL to construct API requests,
while our Express server uses it to define its routing logic. This uniformity is crucial for seamless
communication between client and server.
🟣 Second Section: "Still thinking about
Base URL!"
This section continues explaining the same idea but in more "project" terms:

In our project, the base URL (stored in __________ files) is fixed office address for our
__________ (Hint: server/client ?).

✏️Explanation:

● The Base URL is usually stored in an environment file (.env file) — because you don't want to
hardcode it.

● And it's the address for the server, not the client.
So missing words: "environment" and "server".

The RESTful API then provides the “rooms” or ____________ inside that building.

✏️Explanation:

● Think of the base URL as a building address.

● Inside the building, there are many rooms: /users, /products, /orders.

● So "endpoints" fits best here.

The front-end (like a React app) ____________ to retrieve data.

✏️Explanation:

● Front-end makes API calls or sends requests to get data.

● So the missing word: "makes API calls" or simply "requests".

This clear separation ensures that as you build your server-side logic in a RESTful style,
both components—front-end and back-end—know where to send __________ (Hint:
data/request ?) and how to __________ URLs.
✏️Explanation:

● Both should know where to send requests (Hint already says request).

● And how to construct URLs.

In our project, the base URL (stored in configuration/env files) is a fixed office address for our
server. The RESTful API then provides the “rooms” or endpoints inside that building, which the
front-end (like a React app) uses to retrieve data. This clear separation ensures that even as you
build and deploy your server-side logic in a RESTful style, both components—front-end and back-
end—consistently know where to send requests and how to interpret URLs.

🎯 In short:
Concept Easy Understanding

Base URL The "home address" your app/server communicates with

RESTful API A way of structuring your server so that clients can Create, Read, Update,
Delete data easily

Environment File A hidden file (.env) that stores sensitive/configuration values like Base URL

Endpoints "Rooms" inside your base address. Like /users, /products etc.

Request A message sent from front-end to backend asking for data or service

📚 Missing words summary


Fill in the blanks Most likely answers

build and access build and access

request URLs request URLs


routing routing

environment environment

server server

endpoints endpoints

requests requests

construct construct

Quick Real-Life Example


Imagine:

● Base URL = [Link]

● You want to get users → frontend sends a request to:

nginx

Copy code

GET [Link]

Frontend uses the base URL + /users.


Backend (Express server) sets up a route that listens to /users.

✅ They meet successfully because both sides share the base URL!

(with spacing between the lines)


📄 First Diagram: Mapping Architecture to
Webapps Technology
You can see this flow:

pgsql

Copy code

User -> View -> Controller -> Model -> Database

↑ ↓ ↓ ↑

Rendering Request Asking Returning

Content Process Model Data

to Give

Data
Let's break it piece-by-piece:

🟡 1. User
● Who? — A person using your website or application.

● What do they do? — They interact with your application's View (what they can see and
click).

✅ Example:
Imagine you are visiting an Online Book Store.
You (User) want to search for a book.

🟡 2. View
● Who? — This is what the User sees: the UI (User Interface).

● What happens? — The View displays buttons, forms, etc. to the user.

● It captures user actions and sends the request to the Controller.

✅ Example:
You type "Harry Potter" into the search bar and click Search.
The View captures this input and sends it to the Controller.

🟡 3. Controller
● Who? — The brain that handles user actions.

● What happens? — The Controller processes the user's request.

● It decides what to do next — mostly it asks the Model for some data.

✅ Example:
The Controller says:

"User is searching for 'Harry Potter'. Let's find books matching that title."
It tells the Model to fetch the relevant data.

🟡 4. Model
● Who? — This handles the data and business logic.

● What happens? — The Model talks to the Database to get or update information.

✅ Example:
The Model sends a request to the Database:

"Give me all books where title matches 'Harry Potter'."

It fetches this data and returns it.

🟡 5. Database
● Who? — Your storage system (SQL, MongoDB, etc.).

● What happens? — Stores all your application's data.

✅ Example:
Database finds all matching books and sends the data back to the Model.

🟡 6. Returning and Rendering


● What happens after fetching data?

● The Model returns the data to the Controller.

● The Controller tells the View:

"Here is the list of Harry Potter books. Please show them to the user."

The View renders (displays) the data back to the user!


✅ Example:
You now see a beautiful list of Harry Potter books on your screen!

Why is the Controller Needed Between


Model and View?
In short:

The Controller is needed to keep the View and the Model separated and make
each part focused on its own job.

Without the Controller, the system would become messy, tightly connected, and hard to
manage.

🎯 Let's Understand Their Jobs First:


Componen Main Job
t

Model Only manages data (fetch, update, save, delete)

View Only displays data (show it to the user, collect user actions)

Controller Decides what to do when the user interacts and coordinates between Model
and View

📚 Imagine without Controller:


Suppose there is NO Controller.
Then the View would have to:

● Directly interact with the Model,

● Ask for the data,

● Update the user interface itself,


● Also decide what happens when something changes!

👉 Now the View is doing multiple things: UI + Logic + Data!


This is bad because:

● Difficult to maintain.

● Difficult to debug.

● Difficult to upgrade.

● Tightly coupled code — changing one thing can break everything.

Controller protects Model and View from


getting messy
● The Controller handles logic:

○ What action is triggered?

○ Should I fetch data?

○ Should I update data?

○ Should I change the UI?

✅ This way:

● View stays simple (just shows data).

● Model stays clean (just handles data).

● Controller handles decisions (no mess between view and model).

🎨 Think of it like a Real-world Example:


Imagine a restaurant:
Role Who

Model Kitchen (makes food, stores ingredients)

View Menu Card (shows what food is available)

Controller Waiter (takes order from customer and tells kitchen what to
cook)

If there were no waiter:

● Customers would go inside kitchen,

● Ask chef directly for food,

● See raw ingredients,

● Maybe disturb cooking.

Filled Blanks
A model represents the data for the application.
The view is the visual representation of that data.
A controller takes user input on the view and translates that to changes in the
model.
Filled Blanks;-P
In a traditional backend MVC setup, the View (V) is responsible for
rendering UI using templating engines like EJS (Embedded JavaScript) , Pug, or Handlebars.

✓ But when using React for the frontend, React itself handles UI rendering.

✓ The backend now only provides data via APIs (JSON responses) instead of rendering
HTML.

✓ In a React + Express setup, the backend only serves data (Model + Controller),
while React takes over the View layer.

📚 Now, Full Proper Explanation:

1. Traditional Backend MVC Setup (like Express + EJS)


● In classic MVC, the server (backend) is responsible for everything:

○ Fetching data (Model)

○ Deciding what to do (Controller)

○ Rendering the actual web page (View)

● The View here uses templating engines such as:

○ EJS (Embedded JavaScript Templates) — allows you to write HTML mixed


with JavaScript to dynamically generate HTML pages.
○ Pug — a cleaner, indentation-based templating engine.

○ Handlebars — logic-less templates with {{mustache}} syntax.

Example:
When you visit /profile, the backend:

● Fetches user data from the database (Model)

● Prepares it in Controller

● Uses EJS to generate an HTML page (View) with user's name, photo, etc.

2. React Frontend + Express Backend (Modern Approach)


When you introduce React, things change.

● React is a frontend framework (it runs in the user's browser).

● React builds and updates the UI by itself, using components and state.

● It doesn't need backend templates like EJS — it renders everything using JavaScript
on the frontend.

Thus:

● Backend (Express) no longer generates HTML pages.

● Backend (Express) only provides data in the form of JSON APIs.

● Frontend (React) fetches the data from APIs and renders the UI.

📚 Does React itself follow MVC?


✅ Short answer:
No, React itself does not strictly follow MVC — but it has some similar ideas.

✅ Longer, complete answer:


React is mainly focused on the View part of MVC (the "V" in MVC).
It manages the user interface — how things look and how users interact.

However:
● You can organize a React app in an MVC-like way if you want.

● But React itself is not built with full MVC in mind.


Instead, React encourages a different idea called Component-Based Architecture

First Image Explanation


1. Express as Backend (REST API)
You see a block diagram showing how a typical [Link] backend works.

● HTTP:

○ Users (clients) send HTTP requests (like GET, POST, PUT, DELETE).

● Routes/Routers:

○ This part reads the request's URL and HTTP method (GET/POST etc.) and
directs the request to the correct Controller.

● Controllers:

○ They handle incoming data and pass it to Services.

● Services (Business Logic):

○ Perform the core logic — e.g., calculating, validating data, deciding what to
store/retrieve.

● Database Access Models:

○ Services interact with the database using models. Models define the structure of
the data (like what fields a "User" has: name, email, etc.).

● Database (Persistent Storage):

○ Actual storage of data. Could be MongoDB, MySQL, PostgreSQL, etc.

● External APIs:

○ If needed, the backend can talk to other external services/APIs too (e.g.,
payment gateways, third-party services).

➔ This whole thing together is called the "Express REST API".

2. Step 1: Create Project Directory & Initialize [Link]


You are being guided to:

● Open a command line/terminal.

● Go to your project folder (for example, D:\back_end).

Run the command:

csharp
Copy code
npm init -y


● What this does:

○ It creates a [Link] file automatically with default values (-y means


"yes to everything").

[Link] looks like this:

json

Copy code

"name": "back_end",

"version": "1.0.0",

"description": "",

"main": "[Link]",

"scripts": {

"test": "echo \"Error: no test specified\" && exit 1"

},

"author": "",

"license": "ISC"

}
● It basically defines:

○ The project name, version.

○ The main file (starting point): [Link].

○ Scripts you can run (e.g., tests).

CommonJS vs ES Modules — Full Proper


Explanation
In [Link] (and JavaScript in general), we often need to split our code into smaller files
(modules) and reuse them.

● But how we import and export code depends on the module system you choose.

● [Link] supports two module systems:

1. CommonJS (CJS) → older system

2. ES Modules (ESM) → newer, modern system

Now let's compare them carefully:

Feature CommonJS (CJS) ES Modules (ESM)

Import require('module') import something from 'module'


Syntax

Export [Link] = export default something / export


Syntax something { something }

Loading Synchronous (blocking) Asynchronous (non-blocking)

Default In Older [Link] versions Browsers and modern [Link] (type:


"module" in [Link])

File .js usually .js or .mjs


Extension
Performance Good for small apps Better for large-scale apps (optimized for async
loading)

CommonJS (CJS) Details

Behavior:

● Synchronous loading:

○ If you require() a file, Node waits (blocks) until the module is fully loaded.

○ Slower for huge apps but simple for small ones.

ES Modules (ESM) Details

Behavior:

● Asynchronous loading:

○ Modules are fetched without blocking other operations.

○ Very useful for large apps, modern web development.

CommonJS Module System in [Link]


● Modules in CommonJS are synchronously imported.

● This means [Link] will wait (pause) until the module is fully loaded before moving
forward.

2. Example: [Link]

In the file [Link], you define two functions:

javascript

Copy code

function add(a, b) {

return a + b;

}
function subtract(a, b) {

return a - b;

// Exporting functions

[Link] = {

add,

subtract

};

● [Link] is used to make functions available outside the [Link] file.

● You group your functions inside an object.

3. Example: [Link]

In your main file [Link], you use:

javascript

Copy code

const { add, subtract } = require('./math');

[Link](add(5, 3)); // Outputs 8

[Link](subtract(10, 4)); // Outputs 6

● You import (require) the functions from [Link].


● { add, subtract } means you are doing destructuring, picking only the needed
functions.

● You then call them and print the results.

Week 7
Morgan: A middleware for logging HTTP requests in the console for easier debugging and
monitoring.

ESLint: A tool that analyzes your JavaScript code to find and fix problems, enforcing consistent
coding standards

In Context of [Link] and Morgan


When we say Morgan "logs HTTP requests", it means:

● Every time someone sends a request (like opening a webpage, submitting a form),
Morgan prints a line in the console.

● The line includes details like:

○ HTTP Method (GET, POST, etc.)

○ URL

○ Status code (200 OK, 404 Not Found, etc.)

○ Time taken

○ Date and time of request

Example of a Morgan log:

bash

Copy code

GET /users 200 12ms

POST /login 401 8ms


This tells you:

● Which endpoint was hit

● Whether it succeeded or failed

● How long it took

● If there were any issues

🛠 First Part: [Link](PORT, () =>


{...})
javascript

Copy code

// Start the server

[Link](PORT, () => [Link](`Server running at


[Link]

📚 What’s happening here?

● [Link](PORT, callback) is used to start your Express server.

● PORT is usually a number like 3000, 5000, etc.

● Once the server starts, the callback function runs and logs a message to the console.

● ${PORT} inside backticks (`) is called a template string — it allows you to easily insert
variables inside a string.

🔥 Example if PORT = 5000:


Console will show:

arduino

Copy code
Server running at [Link]

✅ This confirms your server is running and ready to handle requests.

🛠 Second Part: Building a Full URL


javascript

Copy code

const apiUrl = "[Link]

const endpoint = "/api/projects";

const fullUrl = `${apiUrl}${endpoint}`;

[Link]("Fetching data from: " + fullUrl);

📚 What’s happening here?


● You are building a full URL by combining:

○ The base API URL (apiUrl) → [Link]

○ The specific endpoint (endpoint) → /api/projects

● ${apiUrl}${endpoint} joins them nicely into a single complete URL.

🔥 Final Result:

fullUrl = "[Link]

Console will print:

bash
Copy code

Fetching data from: [Link]

✅ Now you have a ready-to-use API URL!

🛠 Third Part: [Link]() and the missing


blank
javascript

Copy code

[Link]("/", (req, res) => {

[Link]({ message: "Server is running! Welcome to the Capstone


Project API." });

});

📚 What’s happening here?

● [Link](PATH, callback) defines a GET route.

● "/" is the path for the homepage/root URL (like [Link]

● (req, res) => {...} is the callback function that handles the request.

● [Link]({}) sends back a JSON response to the client (browser/postman/etc.).

Slide 1: "Fix Bugs" (First slide)


The first slide presents an image suggesting that there are bugs in the code, particularly in the
context of JavaScript. The code given shows the use of an API route handler in an Express app:

javascript

CopyEdit

[Link]("/api/projects", (req, res) => {


[Link]("Server is running! Welcome to the Capstone Project API.");

});

Here’s the explanation:

● [Link]("/api/projects", (req, res) => {...});: This is an Express route


definition. The .get() method is used to define a route that handles HTTP GET
requests sent to the /api/projects endpoint.

● The callback function (req, res) has two parameters:

○ req: The request object that contains information about the HTTP request.

○ res: The response object that allows you to send data back to the client.

● [Link]("Server is running! Welcome to the Capstone Project


API.");: This sends a JSON response with a message saying "Server is running!
Welcome to the Capstone Project API."

Fixing the Bugs:

● The code shown here seems fine. However, there could be an issue with how the
message is being sent. A better practice would be to send the message as an object, not
just a string. It’s better to follow the format:

javascript

CopyEdit

[Link]({ message: "Server is running! Welcome to the Capstone


Project API." });

This would improve the structure, ensuring the client receives a properly structured response.

Slide 2: "Foundation for REST API" (Second slide)


This slide talks about the basics of creating a REST API with the Express framework. It explains
the concept of exposing an API endpoint using the GET method.

● Exposes an API Endpoint: Here, the code is defining an API endpoint,


/api/projects, where clients can send a GET request to access data or receive a
response.

● Clients can send a GET request to "/api/projects": This part explains that a GET
request can be made by the client (such as a browser or Postman) to the endpoint
/api/projects, and in return, it will get a JSON response that says, "Server is
running! Welcome to the Capstone Project API."

Again, this slide uses the same code, and with the fix mentioned earlier, it should look like this:

javascript

CopyEdit

[Link]("/api/projects", (req, res) => {

[Link]({ message: "Server is running! Welcome to the Capstone


Project API." });

});

Slide 3: "To be Run single file [Link]" (Third slide)


This slide explains how to run the server.

● npm start or npm run dev: These are the commands you would use in the terminal
to start your Express server. Usually, npm start is used to start the application in
production, while npm run dev is typically used to run it in development mode (e.g.,
with nodemon for auto-restarting the server).

● Single file [Link]: This is referring to the server being contained in a single
JavaScript file ([Link]), where the Express application is set up, routes are
defined, and the server is started.

In Slide 3, besides the "npm start" and "npm run dev" instructions, there’s an icon and a note
that says:

"=>" ES6

This is related to ES6 Arrow Functions in JavaScript.

What does it mean?

● => is the arrow function syntax introduced in ECMAScript 6 (ES6).


● It provides a shorter way to write functions compared to the traditional function
keyword.

● It also automatically binds the this context, making it easier to work with inside
callbacks.

You gave three options:

● A. Arrow function

● B. Callback function

● C. Anonymous function

Now, the correct and best fit for this line:

[Link]("/api/projects", --------------------- )

is B. Callback function ✅

Why?
Because Express needs a function to call when someone sends a GET request to
/api/projects.
That function is called after the request — meaning it's a "callback function".

Why? → Because it is executed only when an HTTP request is received.

✅ First part:

The Arrow Functions in JavaScript helps us to create anonymous functions


or methods i.e. functions without names
As they do not have any names, the arrow makes the syntax concise.

✅ Second part:
1. ()=>{} are a concise way of writing anonymous, lexically scoped
functions in ES6.

✅ Third part:

2. The ()=>{} can contain other ()=>{} or also normal functions.

✅ Fourth part:

3. The ()=>{} accomplishes the same result as a regular function with fewer
lines of code.

✅ Fifth part:

4. The ()=>{} automatically binds this object to the surrounding code’s


context.

✅ Sixth part:

5. The value of this keyword inside the ()=>{} is not dependent on how they
are called or how they are defined.
It depends only on its enclosing context.

✅ Seventh part:

6. If the ()=>{} is used as an inner function,


this refers to the parent scope in which it is defined.

"Argument list () implies logic within {}"

✅ Meaning:
In an arrow function, the parentheses () are used for parameters (inputs),
and the curly braces {} hold the logic (the body of the function).
THIS KEYWORD :

[Link]

🎯 Simple Example to Understand:


Imagine you have an object like this:

javascript

Copy code

const frog = {

name: "Smart Frog",

sayHello: function () {

[Link]("Regular Function:", [Link]);

const arrowFunc = () => {

[Link]("Arrow Function:", [Link]);

};

arrowFunc();

};

[Link]();

🔥 What will happen when you run this?


Output:

mathematica

Copy code

Regular Function: Smart Frog

Arrow Function: Smart Frog

🧠 Why?
● sayHello is a normal function, so this refers to frog.

● Inside sayHello, we define arrowFunc — an arrow function.

● The arrow function automatically uses the this of where it was created (which is
inside sayHello), so it also points to frog.

● It does NOT create its own this — it inherits this from sayHello.

The primary use of arrow functions in the frontend is to attach functionality to UI interactions,
such as click events, form submissions, and hover actions.

Good question! Here's the direct answer:

An arrow function in JavaScript captures the surroundings of its parent function, NOT the
surroundings of its object.

More precisely:

● Arrow functions do not have their own this, arguments, super, or [Link].

● Instead, they inherit this from the surrounding (parent) scope where they are
defined.

● So the "captured surroundings" are the lexical environment of where the arrow
function was created, not the object that eventually calls it.
Quick Example:
javascript

CopyEdit

const obj = {

value: 42,

regularFunction: function() {

const arrowFunc = () => {

[Link]([Link]); // 'this' comes from regularFunction's


'this'

};

arrowFunc();

};

[Link](); // prints 42

● In this example, arrowFunc captures the this from regularFunction, which is


bound to obj at the time regularFunction was called.

● NOT because arrowFunc was created inside obj, but because it was created inside
regularFunction, and regularFunction's this points to obj.

Important point:
If an arrow function is defined globally (i.e., outside any function), it captures the global scope's
this (window in browser or undefined in strict mode).

javascript

CopyEdit
const arrow = () => {

[Link](this); // window in browser (or undefined if 'use


strict')

};

arrow();

Visual:
Think of it like this:

vbnet

CopyEdit

arrow function's `this`

the `this` of

the parent function (where arrow function is defined)

NOT the object where it is later assigned or called from.

Got it — you're asking:

If I define an arrow function directly inside an object, can it capture the object's
variables (its properties)?

Short answer:
No, not automatically.
Because arrow functions don't bind their own this — they capture this from wherever
they were created.

When you define an arrow function inside an object literal, this does NOT automatically refer
to the object.

Here's an example to show it clearly:


javascript

CopyEdit

const obj = {

value: 42,

arrowFunc: () => {

[Link]([Link]); // 'this' is NOT obj here

};

[Link](); // undefined

● Why?
arrowFunc is created in the outer (global) scope where this is window (in browser)
or undefined (in strict mode), NOT obj.

● So [Link] is undefined.

How to correctly access the object's property?

If you want a method that uses this bound to the object, you should use a regular function,
NOT an arrow function:

javascript

CopyEdit

const obj = {

value: 42,

regularFunc() {

[Link]([Link]); // Now 'this' correctly refers to obj

}
};

[Link](); // 42

Or if you really want an arrow function but still access the object's property, you need to pass
the object manually, like this:

javascript

CopyEdit

const obj = {

value: 42,

};

[Link] = () => {

[Link]([Link]); // manually referencing 'obj'

};

[Link](); // 42

But here, you're hardcoding the object name (obj), which is not flexible and usually bad
practice.

Full Meaning of the Line:

Because arrow functions don't bind their own this — they capture this from
wherever they were created.

This means:

1. In JavaScript, normal functions (regular function keyword) have their own this
based on how they are called.
2. Arrow functions, however:

○ Do NOT create their own this.

○ Instead, they inherit (capture) the this value from the scope where the
arrow function was defined (created).

○ In other words, they remember the this of their outer function or outer block
where they were born.

Let's Understand Step-by-Step:

Regular function (normal function) behavior:

javascript

CopyEdit

const obj = {

value: 10,

regularFunc: function() {

[Link]([Link]);

};

[Link](); // 10

● regularFunc is called by obj, so this = obj.

● Regular functions bind their this at the time of calling.

Arrow function behavior:

javascript
CopyEdit

const obj = {

value: 10,

arrowFunc: () => {

[Link]([Link]);

};

[Link](); // undefined

● Even though you call [Link](), the arrow function's this was already
decided when it was created — at that time it captured this from the outer global
scope.

● In the global scope, this is window (or undefined in strict mode), NOT obj.

● That's why [Link] is undefined.

Visualize it like this:


When you use an arrow function, it behaves like:

"Hey, I'm an arrow function. I don't care how or where you call me later.
I already captured this from the place I was born (created)."

Whereas a regular function behaves like:

"Hey, I'm a normal function. I will set this based on who calls me at runtime."

No problem — I'll explain it again from scratch, even more simply and carefully:

You're asking about this code:

javascript
CopyEdit

const outer = {

outerValue: 100,

createArrow: function() {

return () => {

[Link]([Link]);

};

};

const arrow = [Link]();

arrow(); // prints 100

Step-by-Step Explanation

1. You create an object called outer.

javascript

CopyEdit

const outer = {

outerValue: 100,

createArrow: function() { ... }

};

It has:
● a property outerValue = 100

● a method createArrow (a regular function).

2. You call [Link]().

javascript

CopyEdit

const arrow = [Link]();

● createArrow is a regular function (function inside object).

● In regular functions, when you call [Link](), this points to the object.

● So inside createArrow(), this points to outer.

3. Inside createArrow(), you return an arrow function:

javascript

CopyEdit

return () => {

[Link]([Link]);

};

● The arrow function is created inside createArrow().

● Arrow functions do NOT have their own this.

● So they capture the this of the place where they were created, meaning the this
inside createArrow().
● At the time of creation, this was outer (because createArrow was called as
[Link]()).

Thus, the arrow function remembers that this = outer.

4. Now you call arrow().

javascript

CopyEdit

arrow(); // prints 100

● Even though you're calling arrow() from somewhere else (global code), it still
remembers that this = outer.

● So [Link] is [Link], which is 100.

❓ "If arrow is a variable, why do we call it like arrow() with parentheses?"


Shouldn’t it behave like a normal variable instead of acting like a function?

✅ Good catch — and here’s the detailed and clear answer:

1. arrow is a variable, yes, but it holds a function inside it.


Look at this line carefully:

javascript

CopyEdit

const arrow = [Link]();

● createArrow() returns an arrow function.

● So arrow becomes a function — not just a normal value.


● The function is stored inside the variable arrow.

Thus, arrow is a variable that holds a function.

2. Why parentheses ()?


Because in JavaScript:

● If you have a variable that holds a function, you call the function by adding
parentheses after the variable name.

Example:

javascript

CopyEdit

const sayHello = function() {

[Link]("Hello!");

};

sayHello(); // calling the function

● sayHello is a variable, yes.

● But it points to a function.

● So sayHello() calls the function.

Same thing with your arrow()!

3. In your case:
javascript

CopyEdit
const arrow = [Link](); // arrow holds a function

arrow(); // you call the function

● [Link]() returns an arrow function (() =>


{ [Link]([Link]); }).

● arrow becomes a function.

● So when you write arrow(), you call the function inside the variable.

Slide 1: [Link]() ➔ BUG


Explanation and Fix
javascript

Copy code

const wizard = {

magicNumber: 50,

castSpell: () => {

[Link]([Link]);

};

[Link]();

Problem:

● The castSpell function is an arrow function.

● Arrow functions do not have their own this — they inherit this from the parent
scope (likely the global scope, not wizard).
● So [Link] will be undefined, because in the global scope there is no
magicNumber!

Output:

javascript

Copy code

undefined

Why?

● Arrow functions don't bind their own this, causing this inside castSpell to not point
to wizard.

✅ Fix the bug: Use a regular function (not an arrow function).

Corrected code:

javascript

Copy code

const wizard = {

magicNumber: 50,

castSpell: function() { // <--- Regular function

[Link]([Link]);

};

[Link](); // ✅ Output: 50

const hero = {

name: "Thor",
greet: function () {

const inner = function () {

[Link](`Hello, I am ${[Link]}`);

};

inner();

};

[Link]();

When [Link]() is called:

The greet method defines an inner function.

inner calls [Link] with ${[Link]}.

BUT in JavaScript, in a normal function (function () {}), the value of this depends on how the
function is called — not where it is defined.

inner() is called normally, not as a method of hero. So inside inner, this will be either:

undefined (in strict mode)

or the global object (window in browsers) if not in strict mode.

Thus, [Link] will be undefined because the global object doesn't have a name property (or it
will be something weird if you have a global name defined).
Final output:

plaintext

Copy code

Hello, I am undefined

If you wanted it to correctly log "Hello, I am Thor", you could fix it by:

Using an arrow function (because arrow functions capture this from the surrounding context):

javascript

Copy code

greet: function () {

const inner = () => {

[Link](`Hello, I am ${[Link]}`);

};

inner();

Or by saving this into a variable:

greet: function () {

const self = this;

const inner = function () {

[Link](`Hello, I am ${[Link]}`);

};

inner();

const wizard = {

magicNumber: 42,
spell: function(a, b) { // Regular function

[Link](`Magic Boost: ${[Link]}`);

return a + b + [Link];

};

[Link]([Link](10, 5));

Now, step-by-step:

wizard is an object with:

a property magicNumber with value 42

a method spell, which is a regular function.

When you call [Link](10, 5), inside the spell method:

this refers to the object wizard because you are calling it with dot notation ([Link]).

So:

[Link] is [Link], which is 42.

It prints:

yaml
Copy code

Magic Boost: 42

Then it calculates and returns:

Copy code

10 + 5 + 42 = 57

Finally, [Link] will print 57.

Final Output:

yaml

Copy code

Magic Boost: 42

57

This is the ➔ function

(also called a request handler) that gets executed when a request

such as a frontend app making a request to the endpoint /api/projects

hits the API.

When a React frontend makes a request like this:

javascript

Copy code

fetch("/api/projects")

.then(response => [Link]())

.then(data => [Link](data));

✅ Filled blanks:
● fetch(" **/api/projects** ")

● .then( **response => [Link]()** )

● .then( **data => [Link](data)** )

✅ Your full sentence now reads:

Say a React frontend makes a request like this:

fetch("/api/projects")
.then(response => [Link]())
.then(data => [Link](data))

Then, when the request reaches the backend, the callback function (request
handler) in
[Link]("/api/projects", (req, res) => {...}) executes and returns
data.

This is the callback function (also called a request handler) that gets executed when a GET
request, such as a frontend app making a request to [Link] "/api/projects", hits the
API.

The error "Cannot GET /" happens because your server does not define a route for the "/"
path.
WEEK 8:

Main Idea of the Diagram


In React:

● Data flows one way — from parent components down to child components via
props (green arrows downward).

● Events flow upward — child components can trigger events that inform parent
components to possibly update state (orange arrow upward).

● Each component can also manage its own local state (small circular arrows).

Step-by-Step Explanation
1. Top-Level Component:

○ The top Component (at the very top) holds some state (internal data).

○ It passes down pieces of this state as props to its child components.

2. Props:

○ Props (shown with green arrows) are read-only.

○ Props flow downward from parent to child.

○ Example:
If the parent has a userName in its state, it can pass it to a child like:

<ChildComponent name={[Link]} />

3. Child Components:

○ Child components receive props and use them for rendering.

○ They can also have their own state (local state inside each child).

○ Example:

A child could have its own isClicked state for a button:

const [isClicked, setIsClicked] = useState(false);

4. Events Flow Upward:

○ If a child needs to update data (for example, a button click), it calls a function
received through props.

○ The parent function updates the parent state.

○ This updated state is passed down again through props, refreshing the UI.

5. Example:

Parent defines a function:

handleNameChange = (newName) => {


[Link]({ userName: newName });
}

It passes it to child:
<ChildComponent changeName={[Link]} />
Child calls it on button click:

[Link]('NewUserName');

Simple Example Scenario:


Imagine a Dashboard app where:

● Parent component = Dashboard

● Child components = UserProfile, UserPosts

[Link]:

function Dashboard() {
const [userName, setUserName] = useState('John Doe');

return (
<>
<UserProfile name={userName} changeName={setUserName} />
<UserPosts user={userName} />
</>
);
}

[Link]:

function UserProfile({ name, changeName }) {


return (
<div>
<h2>{name}</h2>
<button onClick={() => changeName('Jane Doe')}>Change
Name</button>
</div>
);
}

[Link]:

function UserPosts({ user }) {

return <h3>Posts by {user}</h3>;


}
Relating to the Diagram
Diagram Part Example in Code

Parent holds state userName in Dashboard

Props sent to children Passing name and changeName to UserProfile

Child triggers event upward Clicking the button in UserProfile triggers


changeName
State updates & flows down New userName flows down to UserProfile and
again UserPosts

[Link]
function Dashboard() {
const [userName, setUserName] = useState('John Doe');

return (
<>
<UserProfile name={userName} changeName={setUserName} />
<UserPosts user={userName} />
</>
);
}

🔵 Explanation step-by-step:

● function Dashboard()
➔ This defines a React functional component named Dashboard.

● const [userName, setUserName] = useState('John Doe'); ➔ This uses


React's useState hook to:

○ Create a state variable called userName.

○ Set an initial value of 'John Doe'.

○ setUserName is the function you will call whenever you want to update the
userName.
● return (...) ➔ This tells React what to render in the browser.

● <></> ➔ This is called a Fragment (<Fragment>). It's a shortcut way to return


multiple elements without wrapping them inside an unnecessary <div>.

● <UserProfile name={userName} changeName={setUserName} /> ➔ You


render a UserProfile component.

○ name={userName} ➔ Pass the current userName as a prop called name.

○ changeName={setUserName} ➔ Pass the function setUserName as a prop


called changeName so the child can call it to update the state.

● <UserPosts user={userName} /> ➔ You render a UserPosts component.

○ user={userName} ➔ Pass the current userName as a prop called user.

2. [Link]
function UserProfile({ name, changeName }) {
return (
<div>
<h2>{name}</h2>
<button onClick={() => changeName('Jane Doe')}>Change
Name</button>
</div>
);
}

🔵 Explanation step-by-step:

● function UserProfile({ name, changeName }) ➔ Defines a functional


component UserProfile. ➔ It receives props: name and changeName
(destructured directly inside the function parameters).

● return (...) ➔ Defines what this component shows.

● <h2>{name}</h2> ➔ Display the name prop inside an <h2> heading.


Example: If name = 'John Doe', it will display:
John Doe

● <button onClick={() => changeName('Jane Doe')}>Change


Name</button> ➔ A button that says "Change Name". ➔ When clicked:

○ It calls the changeName function (which is actually setUserName from the


parent) and passes 'Jane Doe'.

○ This updates the Dashboard’s userName to 'Jane Doe', causing re-


rendering.

3. [Link]
function UserPosts({ user }) {
return <h3>Posts by {user}</h3>;
}

🔵 Explanation step-by-step:

● function UserPosts({ user }) ➔ Defines another functional component. ➔


It receives one prop: user.

● return <h3>Posts by {user}</h3>; ➔ Displays a heading like:


Posts by John Doe
(if user = 'John Doe')

🔥 How everything connects:


Step What
happens

Dashboard starts with userName = 'John Doe'

It renders UserProfile and UserPosts and sends userName down as props

UserProfile shows the name and has a button

When the button is clicked ➔ it calls changeName('Jane Doe') ➔


this updates Dashboard's state

React automatically re-renders everything with the new userName 'Jane


Doe'
Now UserProfile shows 'Jane Doe', and UserPosts says Posts by
Jane Doe

🧠 In Short:
● Dashboard controls the state.

● UserProfile shows user name and has a button to change it.

● UserPosts just shows posts related to that user.

● Data flows down (Dashboard ➔ UserProfile, UserPosts).

● Event (button click) flows up to update the parent's state.


Flow Meaning

Props ➔ Component Props are passed to the component from a parent. The
➔ Render Function ➔ component uses these props (and possibly its internal state)
Element inside a render function to produce HTML elements.

State ➔ Component If the component has internal state, the render function uses
➔ Render Function ➔ the current state along with props to decide what HTML
Element elements to generate.

Filling in the blanks (with explanation):

First section: (related to Props)


✅ Blank 1:
"Props are basically data that flows from one to another component as parameters."
👉 Why?
Because props carry data from parent to child — props are like variables filled with data.

✅ Blank 2:
"Props are passed to components via attributes."
👉 Why?
When you use a component inside JSX, you pass props like attributes:

jsx

Copy code

<UserProfile name="John" />

Here, name="John" is an attribute.

Second section: (related to State)


✅ Blank 3:
"React components have a built-in state object which is private to a component."
👉 Why?
State is private because it belongs to the component itself and cannot be changed from
outside unless you send it explicitly.

First Line:
Props:
"props are passed in, and they cannot change (_________/read only)"

🔵 Meaning:
Props are immutable (cannot be changed) inside the component that receives them. Once a
parent passes a prop to a child, the child component cannot modify it. It can only use it.

✅ Blank fill:

(immutable / read only)

State:
"State can be changed (writable/mutable) using events or lifecycle methods within
a component"

🔵 Meaning:
State is mutable — it can change over time, typically when the user interacts with the app (like
clicking a button) or when data updates (API calls).
We use event handlers (like onClick) or React lifecycle methods (useEffect,
componentDidMount) to change it.

✅ No blank to fill here.

🧠 Second Line:
Props:
"props can be passed to component from outside"

🔵 Meaning:
Props come from the parent component and are passed down into the child component.
So props are external data flowing into a component.

✅ No blank to fill here.

State:
"State can be passed to child components from inside a component but as prop"

🔵 Meaning:
The state belongs inside a component. But if you want a child component to know the state
value, you pass it as a prop to the child.

✅ No blank to fill here.

🧠 Third Line:
Props:
"props are _______ (Hint: public/private)"

🔵 Meaning:
Props are public — any parent can pass data to any child through props.

✅ Blank fill:

public

State:
"State is _______. (Hint: public/private)"
🔵 Meaning:
State is private to the component — it cannot be directly accessed by other components.
If you want to "share" it, you must pass it as props.

✅ Blank fill:

private

🧠 Fourth Line:
Props:
"have better performance"

🔵 Meaning:
Since props are immutable and involve no internal management (no updating, no tracking),
they lead to faster rendering and better performance.

✅ No blank to fill here.

State:
"has worse performance"

🔵 Meaning:
When state changes, React must re-render the component (and sometimes its child
components too), causing more computations and reducing performance if not managed
carefully.

✅ No blank to fill here.

Pass data from a parent to a child component using props


● The parent sends data to the child by giving props.

● Props are like arguments passed into components.

2. Modify the data from within a component using state


● Inside a component, if you want to change something (like user clicks),
you use state (via useState) and update it.
3. Pass data up from child to parent by passing a handler function
● The parent sends a function to the child as a prop.

● The child calls that function, sending data back up to the parent.

✨ Simple Example
import { useState } from 'react';

function Parent() {
const [message, setMessage] = useState("Hello from Parent!");

// Handler to receive data from child


const receiveFromChild = (childData) => {
setMessage(childData); // Update parent's state
};

return (
<div>
<h1>Parent says: {message}</h1>
{/* Pass data and function to child */}
<Child parentMessage={message}
sendToParent={receiveFromChild} />
</div>
);
}

function Child({ parentMessage, sendToParent }) {


const [childMessage, setChildMessage] = useState("Hello from
Child!");

return (
<div>
<h2>Child received: {parentMessage}</h2>

{/* Modify child's own data */}


<button onClick={() => setChildMessage("Child updated
message!")}>
Update Child's Message
</button>

{/* Send child's data to parent */}


<button onClick={() => sendToParent(childMessage)}>
Send Message to Parent
</button>
</div>
);
}

export default Parent;


LIFTING STATE UP
Lifting state up in React involves moving the state to a common ancestor component to share it
between multiple child components. This ensures a single source of truth for the state and
makes data flow more predictable. When two or more components need to share and modify
the same data, instead of each managing their own independent copies, the state is "lifted" to
their nearest common parent.
The process involves:
Identifying the components that need to share the state.
Removing the state from the child components.
Defining the state in the common ancestor component.
Passing the state and the function to update it as props to the child components.
Child components can then access and modify the state through props.
This pattern helps avoid inconsistencies and synchronization issues, simplifies state
management, and ensures all components reflect the same data.

Key Concept: Props and State in React


● Parent → Child data flow

○ In React, the parent component owns the state.

○ It passes data (state) and functions (handlers) down to child components via
props.

🧾 Slide Breakdown
Component A (Parent Component)

● [Link].x = 2 — Holds the state.

● [Link] => [Link]({x: [Link].x + 1}) — A


function that updates the state.

This component owns the state and creates the handler function, then passes them to the
children.

Component B (Child of A)

● Receives x and onXClick as props.

● [Link] => (function in A) — This function was passed from


Component A.

● Passes the same props down to Component C.

Component C (Child of B)

● Receives x and onXClick through Component B.

● onClick => [Link] — When something is clicked, the function


from the parent is triggered.

So, even deeply nested components can access parent functions, as long as they’re passed
down correctly.
Component D (Direct child of A)

● Similar to B and C but receives the props directly from A.

✅ Answer to the Slide's Question:


"How to pass a handler function to the child component as a prop?"

Answer:

You can pass a handler function from a parent component to a child component like this:

// Parent (Component A)
class A extends [Link] {
state = { x: 2 };

handleXClick = () => {
[Link]({ x: [Link].x + 1 });
};

render() {
return (
<>
<B x={[Link].x} onXClick={[Link]} />
<D x={[Link].x} onXClick={[Link]} />
</>
);
}
}

// Child (Component B)
function B(props) {
return <C x={props.x} onXClick={[Link]} />;
}

// Grandchild (Component C)
function C(props) {
return <button onClick={[Link]}>Click Me</button>;
}
✅ This is how you lift state up and pass down handlers via props — very common in
controlled React components.

JavaScript’s this is not automatically bound inside class methods.

<br /> – Line Break (Single Line)


● Inserts a line break in the text.

● It's like pressing Enter once in a Word document.

● Best used inside text when you just want to break a line without adding space around it.

🔹 Example:

<p>
Line 1<br />
Line 2
</p>

This will show:

Line 1
Line 2

✅ <p> – Paragraph (Block Element)


● Represents a whole block of text.
● Automatically adds space above and below (like a full paragraph).

● Best for structuring and separating content semantically.

● More accessible and semantic in HTML (screen readers & SEO prefer it).

🔹 Example:
<p>Line 1</p>
<p>Line 2</p>

This will show:

Line 1

Line 2

WEEK : 11 SLIDESS
CORS stands for Cross-Origin Resource Sharing, a security feature built into browsers.
CORS enforces security by blocking the response from being accessible to your front-end,
unless the server explicitly allows it via CORS headers.

For example:

● Your frontend is hosted at [Link].

● Your backend API is hosted at [Link].

The browser treats these as different origins and blocks the responses unless it’s explicitly
allowed.

✅ Scenario:
● Your frontend (HTML + JavaScript) is hosted at:
[Link]

● Your backend API is hosted at:


[Link]

You want to fetch user data from the backend:

javascript
Copy code
// Code on frontend ([Link]
fetch('[Link]
.then(response => [Link]())
.then(data => [Link](data))
.catch(error => [Link]('CORS error:', error));

❌ What happens without proper CORS:

The browser blocks the response from [Link] because it's a different origin
than [Link].
You’ll see an error in the browser console:

pgsql
Copy code
Access to fetch at '[Link] from origin
'[Link] has been blocked by CORS policy: No 'Access-
Control-Allow-Origin' header is present on the requested resource.

✅ How to fix it (on backend):


If you're using [Link] with Express, you can enable CORS like this:

javascript
Copy code
const express = require('express');
const cors = require('cors');
const app = express();

// Allow requests from [Link]


[Link](cors({
origin: '[Link]
}));

[Link]('/user', (req, res) => {


[Link]({ name: 'John Doe', age: 25 });
});

[Link](3000, () => [Link]('API running on port 3000'));


Now the server sends a response header:

arduino
Copy code
Access-Control-Allow-Origin: [Link]

✅ This tells the browser it’s safe to share the response with the frontend.

CORS errors are triggered by the Same-Origin Policy,


which prevents malicious websites from making unauthorized API calls using your credentials.

When the server doesn’t include the right CORS headers, the browser
refuses to share the response and throws this error:

Access to fetch at '[Link] from origin '[Link]


has been blocked by CORS policy: No ‘Access-Control-Allow-Origin' header is
present.

In short, the browser isn’t blocking the request, it’s blocking the response for security reasons.

Same-Origin Policy (SOP)


Feature Description

What it is A browser security rule that blocks web pages from accessing data from a
different origin

🔓 Cross-Origin Resource Sharing (CORS)


Feature Description

What it is A protocol (set of headers) that allows servers to override the Same-Origin
Policy

🟦 Slide 1: "Facts Behind CORS" + "Fixing CORS: Three


Steps"
✅ Key Points About CORS:
1. It’s not a frontend issue

○ CORS errors happen even if your frontend is perfect. The issue lies in how the
backend responds to the browser.

2. It’s not a browser bug

○ The browser is doing the correct thing by blocking the request for security. It’s
following the Same-Origin Policy.

3. It’s a server-side configuration responsibility

○ Your server must explicitly tell the browser: “Yes, I allow this origin (e.g.,
[Link] to access my data.”

How to Fix It — Three Steps


1. Update the Backend
Add CORS headers on the server:

http
Copy code
Access-Control-Allow-Origin: [Link]


● This tells the browser: “[Link] is allowed to access this resource.”

2. Handle Preflight Requests

● For requests with methods like POST, or with custom headers, the browser sends an
OPTIONS request first (called a preflight).

Your server must respond correctly with:

http
Copy code
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type

🔍 What is an OPTIONS request?


An OPTIONS request is a special type of HTTP request that a browser sends before the
actual request (like GET, POST, etc.) to ask the server:

“Hey server, am I allowed to make this request from my origin?”

This is known as a preflight request.

🛫 Why is it called a “Preflight”?


Just like how planes go through a preflight checklist before flying, the browser performs this
preflight OPTIONS request to make sure it’s safe to proceed with the actual request.

🧠 When does the browser send an OPTIONS request?


Only when a request is considered complex, such as:

1. Using methods other than GET or POST (like PUT, DELETE, PATCH)

2. Using custom headers (like Authorization, Content-Type:


application/json, etc.)

3. Sending requests with credentials (cookies, tokens)

🧾 Example: OPTIONS request


If your frontend at [Link] tries to POST data to
[Link] with JSON, the browser will send this:

http
Copy code
OPTIONS /api HTTP/1.1
Origin: [Link]
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type

✅ Server must respond with:


http
Copy code
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: [Link]
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Content-Type

🚫 If the server doesn’t respond correctly?


The browser will block the actual request and throw a CORS error, even before your backend
route runs.

3. Use a Proxy (optional for local development)

● If setting CORS headers is tricky, you can configure your frontend dev server to proxy
API calls, avoiding CORS issues entirely.

✅ Solution: Use a Proxy in Development


Instead of calling [Link] directly from the frontend, you set up
your frontend dev server (like Vite, React Scripts, etc.) to proxy the request.

🚀 Example 1: Create React App (CRA)

1. In [Link] of your React app:


json
Copy code
"proxy": "[Link]

This tells the development server:


“If the frontend makes a request to /api, send it to
[Link]

2. In frontend code:
javascript
Copy code
fetch('/api/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: [Link]({ name: 'John' })
});

✅ Now it doesn’t cause CORS issues, because the browser sees it as a same-origin
request, and the dev server forwards it to the backend.

🚀 Example 2: Vite

In [Link]:

js
Copy code
export default {
server: {
proxy: {
'/api': {
target: '[Link]
changeOrigin: true,
rewrite: path => [Link](/^\/api/, '')
}
}
}
}

Frontend code:
javascript
Copy code
fetch('/api/data'); // Proxied to [Link]

⚙️How It Works Behind the Scenes

The dev server (Webpack Dev Server or Vite) intercepts the request to /api and forwards it to
[Link] making the request itself (not your browser). Since the request
comes from the same machine (not from a different origin), CORS never becomes a problem.

🟨 Slide 2: Understanding the "Origin"


This section helps explain what the browser considers an origin, which is important for
understanding when CORS is triggered.

📌 Origin = scheme + host + port


🔷 Example 1:
arduino
Copy code
[Link]

● Scheme (Protocol): https

● Host (Domain): [Link]

● Port: 443 (default for HTTPS)


✅ Treated as a single origin.

🔶 Example 2:
bash
Copy code
[Link]

● Scheme: https

● Host: [Link]

● Port: 8888 (non-standard port)

● Because the port is different, this has a different origin from the default HTTPS port
(443).

🔺 Why It Matters:
If your frontend and backend have different origin values, the browser sees them as cross-
origin, and CORS rules apply.
Definition:
An FQDN is the complete domain name for a specific computer, host, or service on the
internet. It includes all domain levels, all the way up to the top-level domain (TLD).

🔐 Important Notes:
Requirement Explanation

credentials: 'include' Tells browser to send cookies with cross-origin


request

Access-Control-Allow- Tells browser it’s okay to accept cookies from this


Credentials: true origin

Access-Control-Allow- Must be a specific origin — can’t be '*' if you're


Origin using credentials

❌ You cannot use * as the origin if credentials: true is enabled.

❗What happens if you forget this?


If frontend sends credentials: true, but the backend does not send:
http
Copy code
Access-Control-Allow-Credentials: true
Then the browser will block the response and give a CORS error, even if the request "reaches"
the backend.

🧠 What Are Authentication Tokens and Cookies?


Term Meaning

Authentication A string (usually a JWT token) used to prove the user is logged in.
Token

Cookie A small piece of data stored by the browser that can automatically be
sent with requests.

Both are used to identify users in sessions (like when you log in to a website and refresh but
still stay logged in).

🔒 Real-World Use Case: Login System


● Frontend (React App) at [Link]

● Backend (Express API) at [Link]

✅ Goal:
1. User logs in from frontend

2. Backend sets a secure cookie with a token

3. Frontend sends cookie on every request

4. Backend checks the cookie/token and returns protected data

1. Backend: [Link] Setup (with CORS and Cookies)


js
Copy code
const express = require('express');
const cors = require('cors');
const cookieParser = require('cookie-parser');

const app = express();

[Link](cookieParser());
[Link]([Link]());

// ✅ Allow CORS from frontend + credentials


[Link](cors({
origin: '[Link]
credentials: true
}));

// ✅ Login route: sets cookie with token


[Link]('/login', (req, res) => {
const token = 'fake-jwt-token'; // In real app, generate JWT
[Link]('token', token, {
httpOnly: true,
secure: false, // true if using HTTPS
sameSite: 'Lax'
});
[Link]({ message: 'Logged in' });
});

// ✅ Protected route: check token in cookie


[Link]('/profile', (req, res) => {
const token = [Link];
if (token === 'fake-jwt-token') {
[Link]({ user: 'John Doe', role: 'Admin' });
} else {
[Link](401).json({ error: 'Unauthorized' });
}
});

[Link](5000, () => {
[Link]('API running on [Link]
});
🍪 Notes:

● cookie-parser is used to read cookies from incoming requests.

● [Link]() sets the cookie on login.

● Cookies are httpOnly so JavaScript on frontend cannot access them — making it


safer.

● CORS allows frontend to send cookies with credentials: true.

🌐 2. Frontend: React Example Using fetch


js
Copy code
// Login Button Click
fetch('[Link] {
method: 'POST',
credentials: 'include' // 👈 Send/receive cookies
})
.then(res => [Link]())
.then(data => [Link](data));

// Fetch protected data


fetch('[Link] {
method: 'GET',
credentials: 'include' // 👈 Required to include cookie in request
})
.then(res => [Link]())
.then(data => [Link]('User:', data))
.catch(err => [Link](err));

🧩 Why credentials: 'include' is Required?


It ensures cookies (or HTTP credentials like session tokens) are sent with the request to the
backend. Without this, the browser won’t attach the cookie, and the backend won’t know who
the user is.
🚫 Common Mistakes (and Fixes)
Problem Fix

Cookie not sent Use credentials: 'include' on frontend

Cookie rejected Backend must send Access-Control-Allow-


Credentials: true
CORS error Ensure origin is exact match (not *) in CORS setup

Cookie not visible in dev If httpOnly: true, cookies don’t show in


tools [Link] (but still work)

🔹 Slide 1: React + Vite Frontend + Express Backend


(CORS Example)
Frontend Code (React + Vite)
javascript
Copy code
useEffect(() => {
fetch('[Link]
.then((res) => [Link]())
.then((data) => setData(data))
.catch((err) => [Link]("CORS issue?", err));
}, []);

📌 What it does:

● React runs useEffect() once the component mounts.

● Makes a GET request to the backend ([Link]

● Updates the state with the data fetched.

✅ If the backend allows CORS, this works.


❌ If not, you'll get a CORS error in the browser console.

Backend Code (Express + CORS)


javascript
Copy code
import express from 'express';
import cors from 'cors';

const app = express();

[Link](cors({
origin: '[Link] // allow only frontend origin
}));

[Link]('/data', (req, res) => {


[Link]({ message: 'Hello from backend!' });
});

[Link](5000, () => {
[Link]('Server running on [Link]
});

✅ This uses the cors middleware to enable cross-origin requests from


[Link]

🔸 Slide 2: CORS is Basically Middleware


🔧 Middleware — Simple Definition
Middleware is code that sits between the request and the response in an application — it
acts like a bridge that processes or modifies requests before they reach the final destination
(like a route handler), and can also handle the response before it’s sent back to the client.

📦 In web development (e.g., [Link]):


Middleware functions are used to:

● 📥 Inspect or modify the request (like logging, parsing JSON, checking authentication)

● ✅ Decide whether to pass the request forward


● 📤 Modify the response before it's sent

CORS is a middleware because it sits between the request and the response and controls
access based on origin.

This slide gives a more explicit configuration example for CORS:

javascript
Copy code
import express from 'express';
import cors from 'cors';

const app = express();

[Link](cors({
origin: '[Link] // Which frontend can
access this
methods: ['GET', 'POST'], // What HTTP methods
are allowed
allowedHeaders: ['Content-Type', 'Authorization'] // What headers
can be sent
}));

[Link]('/data', (req, res) => {


[Link]({ message: 'Using cors middleware' });
});

[Link](5000);

🔍 Why This Is Important:


● This gives you fine-grained control over what requests are allowed.

● You avoid exposing your backend to all origins ('*'), which can be insecure.

🔹 Slide 3: var vs let vs const in JavaScript


❓ What does var do?

var is the older way of declaring variables in JavaScript.


🧠 Characteristics:

● Function-scoped (not block-scoped)

● Can be redeclared

● Gets hoisted (declared at the top of its scope automatically)

javascript
Copy code
function test() {
[Link](x); // undefined, because of hoisting
var x = 10;
}

✅ Why prefer let or const?


Feature var let/const

Scope Function Block

Redeclaration Allowed ❌ Not allowed

Hoisting Yes Hoisted but not initialized


(undefined)
Best ❌ Deprecated ✅ Recommended
practice?

🔒 const is ideal when you never want to reassign a variable.


🔄 let is used when you need to reassign values.

✅ 1. JS Closures and Scoping


● Closure is a feature where an inner function has access to the outer (enclosing)
function’s variables—even after the outer function has returned.

● This behavior is tightly related to scopes: JavaScript uses lexical (static) scoping,
which means scopes are determined at the time of writing code (not during execution).

● Closures form when a function "remembers" its lexical scope even when the function is
executed outside that scope.
✅ 2. Understanding Execution Context
● JavaScript runs in execution contexts—an environment where code is evaluated and
executed.
● There are three main types:

○ Global Execution Context (GEC) – created when the script starts.

○ Function Execution Context (FEC) – created every time a function is invoked.

○ Eval Execution Context – from the use of eval().

● Each context has:

○ Variable Object (VO): stores variables/functions.

○ Scope Chain: access to variables in outer scopes.

○ this keyword: context-dependent.

✅ 3. Variable Hoisting
● Hoisting is JavaScript's default behavior of moving declarations to the top of the current
scope.

● But only declarations are hoisted, initializations are not.

● var is function-scoped and hoisted, but let and const are block-scoped and are
not accessible before their declaration (due to the Temporal Dead Zone).

🔹 Slide 3: Scope Chain vs Call Stack


✅ Scope Chain
● The scope chain determines how variable names are resolved in nested functions.

● Each function keeps a reference to its outer lexical environment.

● When a variable is accessed, JavaScript searches:

1. Inside the current scope.

2. In the outer (enclosing) scope.


3. All the way up to the global scope.

This is the mechanism behind closures.

✅ Example 1: Simple Nested Function


js
Copy
Edit
const a = "global";

function outer() {
const b = "outer";

function inner() {
const c = "inner";
[Link](a); // 🔍 scope chain → outer → global → found "global"
[Link](b); // 🔍 scope chain → outer → found "outer"
[Link](c); // local → found "inner"
}

inner();
}

outer();
🧠 Scope Chain:
inner() → outer() → global

✅ Example 2: Variable Not Found


js
Copy
Edit
function outer() {
const b = "outer";

function inner() {
[Link](b); // found
[Link](a); // ❌ ReferenceError: a is not defined
}

inner();
}

outer();
🧠 a is not declared anywhere in the chain → ReferenceError
✅ Example 3: Same Variable Name in Different Scopes
js
Copy
Edit
const message = "global";

function outer() {
const message = "outer";

function inner() {
const message = "inner";
[Link](message); // 🟢 "inner" (closest scope wins)
}

inner();
}

outer();
🧠 Variable shadowing — JS uses nearest scope.

✅ Example 4: Dynamic Execution vs Lexical Scoping


js
Copy
Edit
function foo() {
[Link](x);
}

function bar() {
const x = 42;
foo(); // ❌ not 42, still undefined
}

const x = "global";
bar(); // 🔍 logs "global"
🧠 foo uses the scope where it's defined, not where it's called → this is lexical scoping.

✅ Call Stack
● The call stack is the mechanism JavaScript uses to keep track of function calls.

● When a function is called:


○ A new execution context is pushed to the stack.

● When a function returns:

○ That context is popped off the stack.

● The call stack is runtime-based and manages the order of function execution.

🔄 Final Output:
vbnet

Copy code

ReferenceError: c is not defined

📌 Scope Chain vs Call Stack (from the Image):

Concept Explanation
Call Stack Shows the order in which functions were called at runtime

Scope Shows how variables are resolved based on where functions were
Chain written (lexical scope), not called

Important third() is in global scope → It cannot see b or c, even if it's


called from inside second()

🔹 Slide 1: Call Stack & Execution Order


💡 Main Idea:
This slide explains the Call Stack, which is a mechanism in JavaScript’s V8 engine
(used in Chrome/[Link]) that manages function execution order.

🔍 Breakdown:
● The call stack works like a stack of plates — last-in, first-out (LIFO).

● When a function is called, it's pushed onto the stack.

● When it finishes, it's popped off.

📘 Code Example:
js
Copy code
function foo(b) {
let a = 10;
return a + b + 11;
}

function bar(x) {
let y = 3;
return foo(x * y);
}

[Link](bar(7)); // ➜ returns 42
🧠 Execution Flow (Call Stack Order):

1. Main() is running and calls bar(7) → bar is pushed on stack.

2. Inside bar, foo(21) is called → foo is pushed on stack.

3. foo returns 42 → popped off.

4. bar returns 42 → popped off.

5. [Link](42) is printed.

🔑 Key Takeaway:
✅ Valid Access ❌ Invalid Access

Function accesses its own Function tries to access variables from another function’s
variables scope

Function uses parameters Function assumes outer variables that don’t exist in its
scope chain

A new Function Execution Context (FEC) is created whenever a function is


invoked (or called). This provides encapsulation and enables each function
to have its own private scope.
function secretBox() {
let secret = "Top Secret"; // 🔐 Encapsulated variable
[Link]("Inside box:", secret);
}

secretBox();
// [Link](secret); // ❌ ReferenceError: secret is not defined

🔹 Slide 3: Module Scope & Lexical Environment


💡 Main Idea:
Introduces module scope and emphasizes that each scope is a lexical
environment that also includes a reference to its outer environment.

✅ Module Scope:
html
Copy code
<script type="module">
const foo = "foo";
</script>

<script>
[Link](foo); // ❌ ReferenceError: foo is not defined
</script>

🔍 Explanation:

● type="module" creates its own isolated scope.

● Variables declared in modules are not added to global scope.

● So the second <script> tag cannot access foo, hence ReferenceError.

✅ Final Green Highlight:


"Scope = Lexical Environment + Outer Reference"

This summarizes how JavaScript handles scopes:


● A Lexical Environment holds:

○ The current scope’s variables/functions.

○ A reference to its outer lexical environment (forming the scope chain).

This chain is what allows closures to access outer variables and what the engine uses to
resolve variable names.

🔹 Parent
The enclosing (outer) function or scope in which a function is defined.

🔹 Reference
A link or pointer to a value, variable, or object stored in memory.

🔹 Data Structure
A way to organize and store data (e.g., arrays, objects, stacks) for efficient access and
modification.

🔹 Local Variable
A variable declared inside a function or block, accessible only within that scope.

🔹 Execution Context
A runtime environment created whenever a function runs, containing everything needed for
code execution (like variables, this, scope).

🔹 Lexical Environment
A structure that holds variable names and their references at the time and place a function is
defined.

✅ Definition: Lexical Environment


A lexical environment in JavaScript is a structure that holds:

1. The variables and functions defined in the current scope, and

2. A reference to its outer (parent) lexical environment.

🧠 Think of it like:
A box containing all the local variables and function declarations that were
created in that particular block or function, along with a pointer to the outer
scope where it was defined.

🔹 Environment Record
An internal object inside the lexical environment that stores actual variable bindings (names
and values).

✅ You can think of it like:


A notebook page where a function writes down all the variables it declares, with their values.

For example:

js

Copy code

function greet() {

const name = "Alice";

let age = 25;

function sayHi() {

[Link]("Hi!");

}
Inside the greet() function, the Environment Record would look like:

js

Copy code

name: "Alice",

age: 25,

sayHi: function

These entries are stored in the Environment Record — which is part of the Lexical
Environment created for greet().

🔹 Parent’s Lexical Environment


The lexical environment of the outer function or scope from which a function inherits
variable access via the scope chain.
Every rectangular block on the previous slide is an Execution Context.
Every execution context creates a Lexical Environment for variables.
The lexical environment is basically a data structure that keeps the variable and their value
reference in memory so that it can easily find it for execution context.
Lexical environment consists of two parts: Environment Record and Outer Reference to outer
lexical environment.
While Environment Record keeps the local variable data,
Outer Reference keeps a reference for the parent’s lexical environment.

Closure
(inner function’s memory to remember variables and outer lexical environment in its current
scope)
There are many uses of closures, from creating class-like structures that store state and
implement private methods (Encapsulation), to passing callbacks to event handlers, enabling
Higher-Order Functions (HOFs), and supporting recursion.
✅ Explained Keywords:
● Private methods: Closures hide internal variables/functions from the outside (like
private properties).

● Encapsulation: Keeps internal logic hidden within closures.

Recursion: A function can call itself and still remember the surrounding state via closure.

🔹 What does this mean?


"Callbacks: Closures retain access to surrounding scope when passed as
arguments."

It means:
When you pass a function (a callback) into another function, that inner function remembers
the variables from where it was created — even if it's used later or elsewhere.

That memory is the closure.

🧠 Think of it like this:


A function doesn’t just carry its code — it also carries its backpack of variables from its original
scope.

✅ Example:
javascript
Copy code
function outer() {
let name = "Alice";

// This function is a closure


function greet() {
[Link]("Hello, " + name);
}

// greet is passed as a callback


setTimeout(greet, 1000);
}

outer();

🔍 What happens here?

● outer() is called → name = "Alice" is created.

● greet() is defined inside outer() and uses name.

● setTimeout(greet, 1000) runs greet after 1 second — outside outer()!

✅ But greet still works and logs "Hello, Alice"


🧠 Because greet remembers name from its original scope — that's a closure.

💬 In short:
A closure lets a callback keep access to its original variables, even when it's run
later or elsewhere.

IF I CHANGE THE VALUE OF NAME FROM ALICE TO SOMETHING ELSE ? THAN WILL IT
STILL RETAIN ALICE ?

🎯 Short Answer:
No, it won’t retain "Alice" permanently.
The closure does not freeze the value — it retains a reference to the variable, not a copy
of its original value.

So if the value changes, the closure sees the updated value.

✅ Definition Recap:
A Higher-Order Function is a function that either takes another function as an
argument, or returns a function.

Closures come into play when the returned function remembers variables from the outer
function — even after that outer function has finished running.
🧪 Example: HOF Returning a Function Using Closure
javascript
Copy code
function greetingGenerator(greeting) {
// This function returns another function (a closure)
return function(name) {
[Link](greeting + ", " + name + "!");
};
}

// Create different greeter functions


const sayHello = greetingGenerator("Hello");
const sayGoodMorning = greetingGenerator("Good morning");

// These inner functions remember the `greeting` variable


sayHello("Alice"); // Output: Hello, Alice!
sayHello("Bob"); // Output: Hello, Bob!
sayGoodMorning("Charlie"); // Output: Good morning, Charlie!

🔍 Explanation:

● greetingGenerator("Hello") creates a new inner function with greeting =


"Hello".

● That inner function remembers the value of greeting even after


greetingGenerator has finished → that’s a closure.

● sayHello and sayGoodMorning are customized functions created using a HOF.

Haha! It does look like sorcery at first — but it’s just one of JavaScript’s most powerful
and beautiful features: Closures.

Let’s break it down in a simple, story-like way:

🔮 The Code in English

You have a function called greetingGenerator(greeting).

Imagine this function as a factory 🏭 that builds greeting bots.


You pass it a greeting (like "Hello" or "Good morning"), and it gives you back a new
function that says that greeting to anyone you want.

js

CopyEdit

const sayHello = greetingGenerator("Hello");

You gave it "Hello" — it builds a bot that says:

"Hello, [name]!"

Later:

js

CopyEdit

sayHello("Alice");

The bot remembers its original greeting "Hello" and uses it.

🔁 What’s Actually Happening:

1. You call greetingGenerator("Hello").

Inside, a new function is created and returned:

js
CopyEdit
return function(name) {

[Link](greeting + ", " + name + "!");

};

2.
3. This inner function remembers the greeting variable from its outer function’s
scope, even after greetingGenerator has finished running.

This “memory” is called a closure.


🧠 What is a Closure?
A closure is when a function “remembers” the variables from the scope
where it was created — even if that scope is no longer active.

🤹 What’s the “sorcery”?

● When sayHello("Alice") runs, it's not re-calling greetingGenerator.

● It’s just calling the inner function returned earlier.

● But — thanks to closures — it still has access to greeting = "Hello".

✅ Scope Chaining in Action


“The ability for closures to access variables from outer scopes even after
those scopes have exited…”

🔍 What it means:
● JavaScript looks for variables in the current scope.

● If not found, it goes up the chain to outer scopes — this is called scope chaining.

● This is how an inner function can use a variable declared in a parent function.

🧪 Example:
javascript
Copy code
function outer() {
let outerVar = "I’m outside!";

function inner() {
[Link](outerVar); // JavaScript "chains up" to find outerVar
}
return inner;
}

const innerFunc = outer(); // outer() finishes, but...


innerFunc(); // Output: I’m outside!

🔗 Why it works:

● innerFunc is a closure — it remembers outerVar.

● Thanks to scope chaining, it knows where to find outerVar, even though


outer() has finished.

✨ The Magic: Persisting State


“What’s magical about closures is that they remember the environment in
which they were created…”

🔥 Key point:
● The inner function keeps a reference to the lexical environment where it was
defined.

● That’s how closures persist state — even if the outer function has exited.

🔁 Real-Life Analogy:
Imagine leaving a backpack in a room.
Even after you leave the room, someone else (the inner function) still has
access to your backpack (variables).

Persisting state means that a function remembers and keeps access to variables from
the time and place it was created — even after the outer function has finished running.

✅ Slide 1: Closures and Lexical Scope


✨ Key Concept:
A child function remembers and has access to the variables of its parent
function, even after the parent has executed and returned.

🧠 Code Breakdown:
js
Copy code
function outer() {
let secret = "I am a secret!";

return function inner() {


[Link](secret); // inner function has access to 'secret' from
outer
};
}

const myClosure = outer(); // outer returns inner function


myClosure(); // logs: "I am a secret!"

📌 Explanation:

● The function outer() defines a variable secret.

● It returns an inner function.

● Even after outer() finishes execution, the returned function (inner) retains
access to secret via closure.

● This happens because of lexical scoping—inner() is defined inside outer(), so


it "remembers" its surrounding scope.

✅ Slide 2: Nested Functions and Scope Chain


🧠 Code Breakdown:
js
Copy code
var globalVar = 'global';
var outerVar = 'outer';
function outerFunc(outerParam) {
function innerFunc(innerParam) {
[Link](globalVar, outerParam, innerParam);
}
return innerFunc;
}

const x = outerFunc(outerVar); // outerVar = 'outer'


outerVar = 'outer-2'; // changes global outerVar
globalVar = 'guess'; // changes globalVar
x('inner'); // calls innerFunc

🌀 Scope Chain (see diagram):


Think of scope like a layered onion:

1. Local scope (inside innerFunc)

2. Enclosing scope (inside outerFunc)

3. Global scope

📌 Explanation:

● The inner function innerFunc has access to:

○ innerParam (local)

○ outerParam (from outerFunc)

○ globalVar (from the global scope)

● Even after outerFunc returns, innerFunc still retains access to outerParam via
closure.

📤 Output:
sql
Copy code
guess outer inner
Because:

● globalVar was changed to 'guess'

● outerParam was captured as 'outer' when outerFunc was called

● innerParam is 'inner'

✅ Slide 3: Loop + Closure Pitfall with var


🧠 Code Breakdown:
js
Copy code
const arrFuncs = [];

for (var i = 0; i < 5; i++) {


[Link](function () {
return i;
});
}

[Link](i); // Outputs 5

for (let i = 0; i < [Link]; i++) {


[Link](arrFuncs[i]()); // What will this print?
}

❌ Issue:

● Using var in the loop means all closures share the same i.

● After the loop ends, i is 5.

● All functions in arrFuncs return 5.

⚠ Output:
Copy code
5
5
5
5
5

💡 Fixes:

1. Use let instead of var in the loop:

js
Copy code
for (let i = 0; i < 5; i++) {
[Link](function () {
return i;
});
}

2. Or use an IIFE (Immediately Invoked Function Expression):

js
Copy code
for (var i = 0; i < 5; i++) {
(function(j) {
[Link](function () {
return j;
});
})(i);
}

✅ Explanation:

● let is block-scoped, so each iteration gets a new i.

● Closures now correctly "remember" their unique value of i.


🧪 Code:
js
Copy code
const arrFuncs = [];

for (var i = 0; i < 5; i++) {


[Link](function () {
return i;
});
}

[Link](i); // ?

for (let i = 0; i < [Link]; i++) {


[Link](arrFuncs[i]()); // ?
}

🧠 DRY RUN
🗂 Memory Before Loop

● arrFuncs → []

● i is undefined
🔁 Loop Execution (with var)

🧾 First Iteration (i = 0):

● function () { return i } is pushed to arrFuncs

● i is still accessible globally (function-scoped)

🧾 Second Iteration (i = 1):

● Another function (return i) is pushed

● Still same i variable (shared)

🧾 Third Iteration (i = 2)

🧾 Fourth Iteration (i = 3)

🧾 Fifth Iteration (i = 4)

Each time, the function that gets pushed:

js
Copy code
function () { return i }

still closes over the same i variable.

🔁 After Final Iteration (i = 5)

Loop ends.

● [Link] = 5

● i = 5

📤 [Link](i)
js
Copy code
[Link](i); // 5
Because i is declared with var, it exists after the loop in the same scope.

🌀 Now run each function:


js
Copy code
for (let i = 0; i < [Link]; i++) {
[Link](arrFuncs[i]());
}

● Each function is:

js
Copy code
function () {
return i; // closes over the same `i` from outer scope
}

● At this point, i is 5

So each function returns:

scss
Copy code
arrFuncs[0]() → 5
arrFuncs[1]() → 5
arrFuncs[2]() → 5
arrFuncs[3]() → 5
arrFuncs[4]() → 5

📋 Final Output:
txt
Copy code
5 // from [Link](i)
5
5
5
5
5

🧠 Why? TL;DR
● All 5 functions in arrFuncs share the same i, not separate copies.

● That i ends up being 5 after the loop finishes.

● When the functions are finally called, they all return the current value of i, which is 5.

💡 Why globalVar is different:

● globalVar is used directly inside innerFunc, not as a parameter.

● That means innerFunc reaches out to the global scope for the current value of
globalVar at the time it runs.

So when you later do:

js
Copy code
globalVar = 'guess';

it does affect what innerFunc prints, because it's reading globalVar live from the global
scope

This code is not working as we expected because of [Link] var keyword makes a
function-scoped variable, and when we push a function we return the same variable i.
So, when we call one of those functions in that array after the loop it logs 5 because we
get the current value of i which is 5 and we can access it because it's a function-scoped
variable. Because closure keeps the reference of that variable not its values at the time of
its creation. We can solve this using an IIFE or changing the var keyword to let for block
scoping.

✅ SLIDE 1: IIFE – Immediately Invoked Function


Expression
🔹 What is an IIFE?
IIFE stands for Immediately Invoked Function Expression.

It’s a function that:

● Is defined and immediately executed.

● Creates a new scope, perfect for isolating variables.

● Is often used to capture values uniquely in situations like loops.

🔹 Example Syntax:
js

Copy code

(function() {

[Link]("Hi there!");

})();

● Defined as a function expression.

● Immediately called using () at the end.

● Helps avoid polluting the global scope.

🔹 Why use IIFE in Loops?

When using var in a loop, every function shares the same i variable due to function scoping.

IIFE helps by:


✅ Creating a new scope per iteration
✅ Capturing the value of i, not the reference
✅ Avoiding the common closure bug where all functions return the same final value.

✅ The Code We're Explaining:


js
Copy code
const arrFuncs = [];

for (var i = 0; i < 5; i++) {


(function(j) {
[Link](function () {
return j;
});
})(i);
}

🔍 Concept Breakdown
🔸 PROBLEM FIRST (No IIFE):
In the version without IIFE:

● Every function shares the same i.

● That i keeps incrementing to 5 after the loop.

● So all functions return 5.

🔸 GOAL:

We want each function to remember the value of i at the time it was created, not the final
value (5).

✅ HOW THE FIX WORKS (Line-by-line


Explanation)
🟨 Line 1:
js
Copy code
const arrFuncs = [];
We start with an empty array to store functions.

🟨 Line 2 (Loop Begins):


js
Copy code
for (var i = 0; i < 5; i++) {

We’re using a var-declared loop. So i is function scoped, and shared across all
iterations.

i will take values 0 → 1 → 2 → 3 → 4

🟨 Inside the Loop:


js
Copy code
(function(j) {
[Link](function () {
return j;
});
})(i);

This is an Immediately Invoked Function Expression (IIFE).

Let’s explain this slowly:

🧠 DRY RUN: STEP BY STEP


Iteration i What gets passed to j inside IIFE What function returns
IIFE
1 0 0 0 function()
{ return 0 }
2 1 1 1 function()
{ return 1 }
3 2 2 2 function()
{ return 2 }
4 3 3 3 function()
{ return 3 }
5 4 4 4 function()
{ return 4 }

Each time:

● i is passed into the IIFE as j ((function(j) { ... })(i);)

● The IIFE creates a new scope, and j is a new local copy

● The returned function closes over j, which is now fixed for that iteration

💡 Visual Representation (Iteration 2):


js
Copy code
i = 1
(function(j) {
[Link](function() {
return j;
});
})(1);

● The function inside .push now remembers j = 1 because of closure

● It won’t be affected by future changes to i, because j is now fixed in the IIFE


scope

🟨 After the Loop Ends:

You now have this in arrFuncs:

js
Copy code
[
function() { return 0 },
function() { return 1 },
function() { return 2 },
function() { return 3 },
function() { return 4 }
]

Each function is returning the unique j value from its own IIFE scope.

🟨 Finally:
js
Copy code
for (let i = 0; i < [Link]; i++) {
[Link](arrFuncs[i]());
}

✅ You get:

js
Copy code
0
1
2
3
4

✅ WHY IT WORKS
1. IIFE creates a new scope per loop iteration.

2. j is a local variable inside that scope.

3. The inner function closes over j, which is fixed to that loop’s value of i.

4. So each function has its own separate j, unlike the shared i in the original
problem.
🔁 Comparison With the Bugged Version
Version Scoping Variable captured Output

Without IIFE i is shared Reference to same 5, 5, 5, 5,


i 5
With IIFE j is per- Each j is a new 0, 1, 2, 3,
iteration copy 4
What’s happening here? copy of becomes a new for each loop iteration via the IIFE. So
is captured uniquely for every .

Absolutely! Let’s deep dive and elaborate on this closure concept — especially in the
context of:

js
Copy code
function getCarsByMake(make) {
return [Link](x => [Link] === make);
}

You asked about this line:

“The function x => [Link] === make remembers the variable make from its
outer function (getCarsByMake), even though it's used after getCarsByMake
is done running.”

Let’s break this down line-by-line, visually, and conceptually.

🔧 Step-by-step Breakdown
✅ Code again:
js
Copy code
function getCarsByMake(make) {
return [Link](x => [Link] === make);
}

Let’s say you call:

js
Copy code
getCarsByMake("Toyota");

Now:

🟩 Step 1: make = "Toyota"

This value is passed as an argument into the function. So, inside getCarsByMake, make
is just a normal parameter — a local variable.

🟩 Step 2: [Link](...)

Inside the function, we call .filter() on a cars array.

This method expects a callback function:

js
Copy code
x => [Link] === make

This arrow function is passed into .filter(), and used later as .filter() loops
through the array.

Now here’s where closure happens:

🔥 The Key Moment: Closure in Action


That inner arrow function:

js
Copy code
x => [Link] === make

uses the variable make, but...


📌 make is not defined inside the arrow function.

So what happens?

JavaScript doesn’t throw an error. Instead, it:


● Looks up the scope chain

● Finds make in the outer function scope of getCarsByMake

● "Closes over" that variable

💡 This is a closure:

A function "remembers" the variables from where it was defined, even if it's
used after that context is finished executing.

Visualization
pgsql
Copy code
getCarsByMake("Toyota")

├── make = "Toyota"

├── filter(x => [Link] === make)
│ ↑
│ This function is defined *inside* getCarsByMake
│ So it has access to make, *even after* getCarsByMake
returns

└── getCarsByMake is done ✅
But filter is still running

Even though getCarsByMake has returned,

the x => [Link] === make function still has access to make, because it
was created inside that scope.

This access is preserved by JavaScript because of closures.

🧠 WHY This Is Powerful


Closures allow:

● Functions to maintain state from their defining scope


● Asynchronous functions (like callbacks, timers, etc.) to use values later

● Encapsulation of data

🟨 Fill-in-the-Blanks (Answers)
Slide 2:

j becomes a new copy of i for each loop iteration via the IIFE.
So j is captured uniquely for every function.

Slide 3:

make is available in the callback because of closure,


(lexical scoping/scope chaining/closure) and the value of make is persisted
when the anonymous function is called by .filter because of a closure.

✅ Slide 1: Write testing code for given


getCarsByMake function
🧩 Code to test:
js

Copy code

function getCarsByMake(make) {

return [Link](x => [Link] === make);

🧪 What this function does:


● Takes a car make as input (e.g., "Toyota")

● Filters a global cars array to only return cars that match that make

● Uses closure to access the make variable inside the callback

✅ Test It (You must do two things):


1. Define a test array:

js

Copy code

const cars = [

{ make: 'Toyota', model: 'Corolla' },

{ make: 'Honda', model: 'Civic' },

{ make: 'Toyota', model: 'Camry' }

];

2. Call the function:

js

Copy code

[Link](getCarsByMake('Toyota'));

🧾 Expected Output:
js

Copy code

{ make: 'Toyota', model: 'Corolla' },


{ make: 'Toyota', model: 'Camry' }

🔍 Key Concept:

This uses a closure because the arrow function (x => [Link] === make) still uses the
make variable from its outer scope, even after the function has started filtering.

✅ Slide 2: Closures return objects from f()


that store state
🧩 Code Overview:
js

Copy code

function makePerson(name) {

let _name = name;

return {

setName: (newName) => (_name = newName),

getName: () => _name

};

🧠 What’s happening:

● makePerson creates a private variable _name.

● It returns an object with methods to get and set the name.


● The returned object remembers _name even after makePerson has finished running.

🔍 Key Quotes Explained:


"Closures do not copy the values of variables from a function's outer scope
during creation."

✅ Meaning:

● Variables like _name are not just copied.

● They're referenced and kept alive by the closure.

"Instead, they maintain a reference throughout the closure’s lifetime."

✅ So:

● Changes made via setName() are reflected in future getName() calls.

● That’s because both methods share access to the same reference of _name.

✅ Dry Run:
js

Copy code

const me = makePerson("Strange");

[Link](); // "Strange"

[Link]("Humera Tariq");

[Link](); // "Humera Tariq"

Even though makePerson has returned, [Link]() still works — because of closure.
❓ So... How is privateSetName private?
Here’s the relevant code again:

js
Copy code
function makePerson(name) {
let _name = name;

function privateSetName(newName) {
_name = newName;
}

return {
getName: () => _name,
setName: (newName) => privateSetName(newName)
};
}

✅ What makes privateSetName "private"?


🔐 It’s not returned and not exposed to the outside world.

● privateSetName() is defined inside makePerson

● It is not part of the object returned by makePerson


● So you cannot directly call privateSetName from outside the function

Only this method is publicly accessible:

js
Copy code
setName: (newName) => privateSetName(newName)

So privateSetName is used internally — it's hidden from outside code.

✅ Example:
js
Copy code
const person = makePerson("Ali");

[Link]([Link]()); // "Ali"

// Change name using public method


[Link]("Zara");

[Link]([Link]()); // "Zara"

// ❌ Cannot call privateSetName directly


[Link]([Link]); // undefined

So if you try:

js
Copy code
[Link]("Hack"); // ❌ Error: not a function

…it fails, because privateSetName is not exposed.

🎓 Why is this called “private”?


This is JavaScript's way of mimicking private methods, like in other languages (e.g.,
private in Java, C++).

JavaScript doesn’t have true access modifiers like private/public, but you can simulate
them using:

1. Function scope

2. Closures

This is called encapsulation — hiding internal details and exposing only what’s needed.

🔶 Title: Closures + Event Handler + Callback


This slide illustrates how closures, event handlers, and callbacks work together in JavaScript
through a practical code example.

🔹 HTML + JavaScript Code (Left Side)


🧾 HTML:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Closure + Event Handler</title>
<script>
function setupButton(name) {
const button = [Link]('button');
[Link] = `Click me: ${name}`;

[Link]('click', function () {
alert(`Hello, ${name}`);
});

[Link](button);
}
[Link] = function () {
setupButton('Humera');
};
</script>
</head>
<body></body>
</html>

💡 What It Does:

1. When the page loads ([Link]), it calls setupButton('Humera').

2. setupButton:

○ Creates a <button>.

○ Sets its label to “Click me: Humera”.

○ Adds an event listener (click) with a callback function.

○ This callback displays an alert: “Hello, Humera” when the button is clicked.

3. The button is added to the page ([Link](button)).

🔹 Code (Middle Section: JS only)


This is a cleaner view of the same JavaScript logic:

javascript
Copy code
function setupButton(name) {
const button = [Link]('button');
[Link] = `Click me: ${name}`;

// Event handler with closure


[Link]('click', function () {
alert(`Hello, ${name}`);
});
[Link](button);
}

setupButton('Humera');

🔁 Concepts Demonstrated Here:

🔸 1. Closure
A closure is when a function “remembers” the variables from its outer scope even after the
outer function has finished executing.

➡️In this code:

● function () { alert("Hello, " + name); } is a closure.

● It remembers the value of name that was passed to setupButton, even after
setupButton finishes executing.

🔸 2. Callback
A callback is a function passed as an argument to another function to be called later.

➡️Here:

● function () { alert("Hello, " + name); } is passed to


addEventListener.

● It is called when the button is clicked (later).

● Hence, it's a callback function.

🔸 3. Event Handler
An event handler is a function that runs in response to an event (like a click).
➡️addEventListener('click', function () { ... }) registers the callback as a
click event handler.

🔹 Explanation Text (Right Side)


Let’s explain each part of the text:

🟡 Yellow: "The setupButton function"

"The setupButton function creates a variable (name) and attaches a callback


(anonymous function) as an event handler."

✔️Correct — The function takes a parameter name, creates a button, and registers a click
handler (anonymous function).

🔵 Blue: "setupButton has finished executing"

"Even though setupButton has finished executing, the click event still has access
to name."

✔️This is the key idea of closure — the inner function (click handler) remembers the variable
name.

🟢 Green: Closure description


"When the button is clicked later, the callback remembers the value of name via a
closure."

✔️Yes — this shows that the value 'Humera' is captured and preserved by the callback due
to closure.

WEEK:12 SLIDES
When we call and enter a function, a new execution context is created on the call stack to
keep track of variables, parameters, and the function’s scope as we execute the
function’s code.

🔹 Slide 1: Static vs Dynamic Scoping (Visual + Code


Example)
🟪 Explanation:
● In static (lexical) scoping, JavaScript looks at where the function was defined, not
where it was called.

● In dynamic scoping (used in some older languages), the function would look up
variables from the calling context.

Given code:

js
Copy code
const x = 1;

const inner = () => {


[Link](x);
};

const outer = () => {


const x = 2;
inner(); // Called from inside outer
};

outer();

Here, when inner() is called from inside outer(), you might think it uses x = 2, but it
actually prints 1, because JavaScript uses static scoping and x = 1 was in scope when
inner was defined.

✅ The answer is: 1


Why? Because inner was defined in the scope where x = 1 (global), and JavaScript uses
static scoping.

🔹 Slide 2: Fill in the blanks


✅ Filled Version:
The answer is 1.
Why? When inner is called, x is defined in outer (outer/inner) EC which sits just
below inner’s EC, but JavaScript doesn’t care about that.
JavaScript uses static (static/dynamic) scoping, meaning it only cares about which
variables are in-scope at the time a function is created.

Explanation (below box):

When inner is created, lexically the top-level x (value 1) is in scope and outer’s x
(value 2) is not, so it only refers to that x (value 1) when it’s called.

This reinforces that lexical scope means JavaScript resolves variables based on where the
function was written, not where it’s called from.

🔹 Slide 3: JavaScript with Static Scoping (Real Behavior)


Code:
js
Copy code
let a = 10;
function foo() {
[Link](a);
}

function bar() {
let a = 20;
foo(); // What will this print?
}

bar();

✅ Filled Explanation:

● foo() looks for a where it was defined, not where it was called.

● Since foo was defined when a = 10 in global scope, it prints 10, even though bar()
has a different a = 20 locally.

✅ Final Fill-in-the-Blanks:

foo() looks for a where it was defined, not where it was called.
Since foo was defined when a = 10 in global scope, it prints 10, even though
bar() has a different a = 20 locally.

🔹 Slide 1: Closures and Lexical Scoping


Code:
js
Copy code
const x = 1;
const outer = () => {
const x = 2;
const inner = () => {
[Link](x); // 2
};
return inner;
};
const foo = outer();
foo();

✅ What’s Happening:

● The variable x = 2 is lexically closer to inner.

● Even though outer() has finished executing, the function inner still remembers x =
2.

🟩 Blanks Filled:

🟦 Final filled-in sentence:

✅ Filled Answer:
Here, the inner function is
defined inside
the outer function.
The first thing to note is that
now we’ll be console logging x with a value of 2,
not 1, because the x from
the outer function
appears first lexically as we
zoom out from
the inner function.

But the more important thing is that by the time we call, foo(), and we’ve assigned
our inner function to foo,
outer’s execution context (stack frame) can no longer live on the call stack,
because we’re now outside that function completely.
So how can foo know to output 2 when we reach [Link](x)?

because we’re now outside that function completely.


So how can foo know to output 2 when we reach [Link](x)?

🔹 Slide 2: What Is a Closure?


💡 Explanation:
A closure is a function along with its lexical environment. It allows a function to
"remember" variables from the scope where it was created, even after that scope
has finished executing.

js
Copy code
function outer() {
let x = 2;
function inner() {
[Link](x);
}
return inner;
}
const foo = outer();
foo(); // Still prints 2

🟩 Blanks Filled:
This brings us to closures.
A closure is simply a function paired with a reference to its parent environment.
When we create our inner function,
we actually create a closure consisting of the inner function and a reference to
the lexical environment of the outer function.

When inner is created, it stores an internal [[Scopes]] property


which captures the lexical environment of the outer function.
Then, when we call foo, we use the [[Scopes]] property to
traverse the scope chain and find the value of x.

Dynamic scoping provides no way of closing over variables, because it will


always traverse the call stack itself to find the value of a given variable at runtime.
That means as soon as an outer function returns, its local variables are lost.

🔁 Let’s Break it Down Line by Line

🟥 1. "Dynamic scoping provides no way of closing over variables..."


● In dynamic scoping, the scope chain is determined by the calling context, not the
declaration context.
● So when a function accesses a variable (e.g. x), it doesn’t care where the function was
defined. It searches up the call stack (the functions that called it).

● This means:

○ It cannot retain variables from the function that defined it.

○ Therefore, closures (which “remember” variables from where a function


was defined) are not possible.

🔁 Dynamic Scoping Conceptual Example


Let’s assume a language that uses dynamic scoping:

// Pseudo-JavaScript (acts like dynamically scoped language)

let x = 1;

function foo() {
[Link](x);
}

function bar() {
let x = 2;
foo(); // In dynamic scoping, this would log 2
}

bar();

🔍 What Happens in Dynamic Scoping:

● foo() logs x.

● With dynamic scoping, it looks up the call stack to find the nearest x.

● Since foo() is called inside bar(), it finds let x = 2 → 🔥 logs 2.

You provided this code (which uses static scoping, like in JavaScript):

const x = 1;
const outer = () => {
const x = 2;
const inner = () => {
[Link](x);
};
return inner;
};

const foo = outer(); // outer() is called, returns inner


foo(); // inner() is called

✅ With Static Scoping (actual JavaScript)

● inner is defined inside outer, so it remembers the x = 2 declared in outer.

● When foo() is called (which is inner()), it logs:

➡️Output: 2

🔁 With Dynamic Scoping (hypothetical)


Here’s what would happen if JavaScript used dynamic scoping:

● When inner() is called via foo(), dynamic scoping says:

"Look at the current call stack, not where I was defined, to resolve variables."

So at the time foo() (which is inner()) is called, it's called in the global context — not
inside outer() anymore. The function outer has already returned, and its local variables are
gone.

So now, when [Link](x) inside inner() runs, and it looks up the call stack, the only
visible x is:

const x = 1;
🟢 So with dynamic scoping, the output would be: 1

Slide 1: "Memory fixed or not???"


Concept: Closures and Lexical Scoping

Here, we define a function outer() inside which we define another function inner().
When outer() is called, it returns inner().

js

CopyEdit

const outer = () => {

const x = 2;

const inner = () => {

[Link](x); // closure accesses x

};

return inner;

};

Then we call outer() and store the returned inner function into foo, and finally call
foo().

💡 What's happening?

● When outer() runs, it creates its own execution context with its local variable x
= 2.

● inner() is defined within outer(), so it "remembers" the environment (x) where


it was created.

● When foo() (which is actually inner()) is executed later, it still remembers the
value of x from outer() — this is a closure.

🧠 Closure means a function remembers the variables from the scope in which it was
created, even after that outer function has finished execution.
🔍 So How Is Memory Managed?
● When outer() finishes, its local variables would normally be removed from
memory.

● BUT because inner() closed over those variables, JavaScript keeps them alive
— in a structure called the "closure context".

● That context is stored in the heap, not the stack, because it needs to live longer.

Slide 2: "Memory + hof/closure as dynamic objects"


Concept: Closures can capture dynamic values
js

CopyEdit

function foo(a) {

return function(b) {

return a === b;

};

Here, calling foo(5) creates a function that checks if the input b equals 5.

js

CopyEdit

const isFive = foo(5); // a = 5

isFive(5); // true

isFive(6); // false

Then again:
js

CopyEdit

const isHello = foo("hello");

isHello("hello"); // true

isHello("world"); // false

💡 This proves closures are dynamic and retain the context (i.e., the variable a) they were
created with, even after the outer function has finished.

🧠 Higher-order functions (HOF): Functions that return or take other functions.

● Closures make HOFs powerful because they can preserve and use variables from
earlier contexts.
✅ 1. What is a “Dynamic Object” in This
Context?
In JavaScript:

● An object is a structure that holds properties (key-value pairs).

● A dynamic object means:


🔹 It’s created at runtime (not hard-coded)
🔹 Its contents can vary depending on how and when it’s created

A closure is an example of a dynamic object because:

● It is created each time you call the outer function.

● It remembers different values depending on what was passed.

● The closure is actually a function + a hidden context object (the


environment/scope).

That hidden context is what makes the closure dynamic in memory.

🧠 2. Closures as Dynamic Memory Objects


Let’s revisit the code:
js

CopyEdit

● function foo(a) {
● return function(b) {
● return a === b;
● };
● }

Each time you do:

js

CopyEdit

● const isFive = foo(5);


● const isHello = foo("hello");

You are dynamically creating new closures.

➡️isFive is a closure with a = 5


➡️isHello is a closure with a = "hello"

Slide 3: "Why Closures Require Heap Allocation"


Concept: Context stored on Heap in JavaScript engines like V8
When JavaScript creates a closure, it creates a "context" object to store the
captured variables.

🔍 In V8 (JavaScript engine), if a function is defined inside a scope and references


variables from that scope, then:

● A context is created.

● That context is stored on the heap instead of the stack.

● This allows the inner function to access those variables even after the outer
function has exited.
🧠 Heap is a memory region where data persists longer and is accessed indirectly (e.g.,
through pointers).

● Stack is temporary and used for function calls — it gets cleared once a function
finishes.

➡️Why heap?
Because closures may outlive their outer functions, the context must survive — hence,
it's stored in the heap.

Slide 4: "Problem?????"
Concept: Closures retain entire scope even if only part is needed
js

CopyEdit

const outer = () => {

const x = 2;

const y = 1;

const HUGE = { one: 1, two: 2 };

const bar = () => [Link](HUGE);

const inner = () => [Link](x);

return inner;

};

Here, inner only uses x, but the closure still captures the entire environment of outer,
including y, HUGE, and bar.
💣 Problem:
Even though HUGE is not used, it's retained in memory because it's part of the scope
inner closed over.

🧠 This is inefficient — it keeps large data in memory that is not needed.

Slide 5: "Closure-related memory leaks"


Concept: How closures can cause memory leaks
Because:

● Closures retain the entire outer scope.

● Even if the inner function only uses a small part of it.

● Large variables (like HUGE) get stored in the heap and stay in memory until the
closure itself is garbage collected.

💣 This causes a memory leak — memory that could have been freed is kept alive
unnecessarily.

➡️Your app might waste MBs or GBs of memory just because closures retain
unnecessary variables.

Slide 6: "How to fix / optimize"


Concept: Avoid capturing unnecessary variables
The optimized version:

js

CopyEdit

const outer = () => {

const x = 2;

const inner = () => {

[Link](x); // only x is needed


};

return inner;

};

💡 Now HUGE and bar are not even declared — they are excluded from the closure’s
scope.

✅ Only what is needed is retained — resulting in:

● Less memory usage.

● Faster garbage collection.

● No memory leaks from unnecessary variables.

Fil in the blanks:

✓ inner function forms a closure over the variables it uses or might need.
✓ inner uses only x, and NOT HUGE directly.

🔹 Slide 1: Execution Contexts Table


This slide explains Execution Contexts — a fundamental concept in JavaScript’s runtime.

What is an Execution Context?


It’s an abstract environment where JavaScript code runs. It contains things like
variables, the value of this, the scope chain, etc.

Here’s the breakdown of the table:

Who? Where It Lives Purpose / Behavior

Global Execution Stack initially, This is the very first context created when a
Context references script starts. It holds the global object (window
objects on Heap in browsers) and global variables.

Execution Stack Created every time a function is called. It


Context manages local variables, this, and scope. This
context is destroyed once the function call
finishes (unless it’s part of a closure).
Closure Context Heap Captures variables from outer scopes needed by
(V8 Context) inner functions. This context survives even after
the outer function finishes, enabling closures to
work.

Lexical Abstract model An invisible structure that links variable names


Environment (realized via to memory locations. It's implemented using
contexts) Execution or Closure Contexts to manage scope
and variables.

Summary:

● JavaScript starts with a global context.

● Each function call creates a new execution context on the call stack.

● When functions return, their contexts are removed — unless they are part of a
closure, in which case their variables are preserved on the heap.

● The lexical environment is the underlying model that keeps track of variable
bindings.

🔹 Slide 2: Title Slide


Reduce Repeated Calls with Throttling and Debouncing

This slide introduces the topic: how to optimize repeated function calls in JavaScript,
especially for events like typing, scrolling, or resizing, which can trigger many calls very
fast.

🔹 Slide 3: Debouncing Visual


This slide shows the idea of debouncing with a visual example.

What is Debouncing?
Debouncing is a technique that delays the execution of a function until after a certain
amount of time has passed since the last time it was invoked.
Use case: Imagine a search box where you fetch search results only when the user
pauses typing for 300ms. Without debouncing, the search might fire on every keypress,
causing too many calls.

🔹 Slide 4: Key Concepts in Debouncing Example 1


Here, two important JavaScript concepts that make debouncing possible are introduced:

Closures:
● A closure is when an inner function remembers variables from its outer function
even after the outer function has finished executing.

● In debouncing, the returned function keeps access to a timer variable (interval


or timeoutId) that is declared in the outer function’s scope.

Higher-Order Functions:
● A higher-order function is a function that takes another function as an argument
or returns a new function.

● The debounce function takes a callback function and returns a new debounced
function that wraps the original logic.

🔹 Slide 5: debounce() JSDoc


This slide gives a documentation-style comment for a debounce function:

js

CopyEdit

/**

* Function: debounce

* -------------------

* Returns a debounced version of the provided callback function.

* The debounced function delays the execution of the callback


* after a specified delay has elapsed since the last time

* the debounced function was invoked.

* Parameters:

* - callback: The function to debounce.

* - time: The delay in milliseconds.

* Returns:

* - A debounced version of the callback function.

*/

What this means:

● You give debounce a function and a delay time.

● It returns a new function.

● When you call this new function repeatedly, it postpones running the original
function until the calls stop for at least the delay period.

🔹 Slide 6: HTML + JS Example


This slide shows a simple example of adding an event listener in HTML + JS:

html

CopyEdit

<button id="app">Save</button>

<script>
[Link]("app").addEventListener("click", () =>

[Link]('document saved!'));

</script>

● When you click the button, it logs "document saved!" in the console.

● This example is basic and does not include debouncing yet — but imagine if this
event was firing many times rapidly (e.g., scroll or input event). Then, debouncing
could optimize it by reducing how often the callback runs.

🔧 What is Debouncing?
Debouncing is a programming pattern used to limit how often a function runs. It’s
especially useful for handling rapid-fire events like:

● Button clicks

● Keypresses (e.g. search input)

● Window resizing

● Scroll events

🧠 Imagine this:
Every time you press a key in a search bar, a function fires. If you type 10 characters
quickly, it could call the server 10 times. That’s inefficient.

With debounce, we make sure that:

● We wait until the user stops typing, and then

● Trigger the function only once, after a delay.

📸 Slide 1: saveDoc() Function


javascript

Copy code
function saveDoc() {

[Link]('document saved!');

This is just a basic function that logs when a document is saved. Nothing fancy yet. But
if we call this every time someone clicks a button (especially repeatedly), it could flood
the console or backend.

📸 Slide 2: Implementing Debounce


javascript

Copy code

function debounce(func, waitTime) {

let timeout;

return function () {

clearTimeout(timeout); // cancel previous timer

timeout = setTimeout(() => {

func(); // run the actual function

}, waitTime);

};

🔍 Explanation:

● func: This is the function we want to delay.

● waitTime: How long to wait after the last event (e.g., 2000ms = 2s).
● timeout: Keeps track of the timer ID.

How it works:

1. Every time the returned function is called, it clears the old timer.

2. Then it sets a new timer to run func after waitTime.

3. If another event happens before time is up, the timer is cleared and restarted.

4. Only when no more events happen within the wait time, the function finally runs.

This prevents the function from being called too often.

📸 Slide 3: Using Debounce with a Button


javascript

Copy code

[Link]('app')

.addEventListener('click', debounce(saveDoc, 2000));

Here, we:

● Get the button or app element.

● Add a click event.

● Instead of calling saveDoc() directly, we wrap it inside debounce() with a 2-


second delay.

🔁 What happens when user clicks repeatedly?


● The function waits 2 seconds after the last click.

● If user keeps clicking, the wait resets.

● saveDoc() runs only once, 2 seconds after the last click.


📸 Slide 4: Visual Breakdown with Clock
This section shows a timeline of how debounce behaves.

1. User clicks once: A timer is set.

2. User clicks again before time is up: Old timer is cleared, a new one is set.

3. User keeps clicking: Keeps resetting the timer.

4. User stops clicking: After wait time (e.g. 1000ms), function finally runs.

5. ✅ This is efficient: only one function call no matter how many clicks.

✅ What is Throttling?
Throttling is a technique used to limit the number of times a function can run
over a specific time period.

Example: You don’t want a scroll or resize event firing a function 1000 times per second. You
want it to fire once every 300ms, no matter how often the event happens.

🟪 Slide 1 – Throttle Button vs Regular Button


Code Summary:
js
Copy code
let counter = 0;
let counterRegular = 0;

[Link]("btn").addEventListener("click",
throttle(function () {
counter++;
[Link]("clickCount").innerText = "Click Count: "
+ counter;
})
);
[Link]("btnRegular").addEventListener("click",
function () {
counterRegular++;
[Link]("clickCountRegular").innerText =
"Click Count: " + counterRegular;
});

Concept:
● Regular Button: Every click increases the counter immediately.

● Throttled Button: Even if you click fast, the counter increases only once per throttle
interval.

This shows how throttling limits the number of function executions even when events happen
rapidly.

🧠 Goal of This Code:


To limit how often a function runs, even if the event fires frequently.
For example, if you click a button rapidly, it will only register once per second.

✅ Full Code:
js
Copy code
const throttle = (func, duration) => {
let shouldWait = false;

return (...args) => {


if (!shouldWait) {
[Link](null, args); // Execute the actual function
shouldWait = true; // Block future calls

setTimeout(() => {
shouldWait = false; // Re-enable after duration
}, duration);
}
};
};

let counter = 0;

[Link]("btn").addEventListener("click",
throttle(function () {
counter++;
[Link]("clickCount").innerText = "Click Count: "
+ counter;
}, 1000) // Throttle duration: 1000ms = 1 second
);

🔍 Step-by-Step Breakdown:
✅ throttle(func, duration):
This is a higher-order function, meaning it returns a new function that adds throttling logic
around func.

✅ Inside throttle:
js
Copy code
let shouldWait = false;

This boolean tracks whether we should allow the function to run.

● false → Run allowed

● true → Skip function call

✅ Returned Function:
js
Copy code
return (...args) => {
if (!shouldWait) {
[Link](null, args);
shouldWait = true;
setTimeout(() => {
shouldWait = false;
}, duration);
}
};

1. When the returned function is called:

○ If shouldWait is false, it calls the actual function func

○ Sets shouldWait = true to block future calls

2. After duration milliseconds:

○ setTimeout sets shouldWait = false, allowing the next call

✅ Real Use Case:


js
Copy code
let counter = 0;

[Link]("btn").addEventListener("click",
throttle(function () {
counter++;
[Link]("clickCount").innerText = "Click Count: "
+ counter;
}, 1000)
);

● This sets up a click listener on the button with id "btn"

● When clicked, the throttled version of the function is triggered

● Even if the user clicks the button 10 times in a second, the counter will only increment
once per second
✅ Example:
Let’s say you throttle this function:

js
CopyEdit
function greet(name) {
[Link]("Hello, " + name);
}

And then you throttle it:

js
CopyEdit
const throttledGreet = throttle(greet, 1000);
throttledGreet("Alice"); // "Hello, Alice"

Inside throttledGreet, args = ["Alice"], and

js
CopyEdit
[Link](null, args);

translates to:

js
CopyEdit
[Link](null, ["Alice"]);

which logs:

CopyEdit
Hello, Alice

🟦 Slide 2 – Explanation of Throttle


Text Summary:
● Throttling limits how often a function is called.

● Commonly used with:

○ Scroll events

○ Resize events

○ Input events

● Why? To improve performance.

● How? Use a timer like setTimeout or a time-check like [Link]().

Think of throttling like a gate that only opens once every few milliseconds — no
matter how many people knock, it won’t open again until the timer expires.

🟨 Slide 3 – Throttling Visualization (Diagram)


Visual Summary:
● Rapid clicks are shown.

● Only some clicks are allowed to trigger the function.

● Others are blocked because the throttle delay hasn't passed.

Key Concept:
js

Copy code

if (enoughTimePassed) {

runFunction();

If the required wait time has not passed since the last execution, ignore the new
trigger.

This helps visualize how throttling blocks extra calls.


⬛ Slide 4 – Throttle with [Link]()
Code Summary:
js

Copy code

let lastTime = 0;

function throttleExample() {

const now = [Link]();

if (now - lastTime > 300) {

[Link]("Ball is thrown!");

lastTime = now;

} else {

[Link]("Wait! Ball is still being thrown too soon.");

Concept:

● [Link]() returns the current time in milliseconds.

● You compare now with lastTime.

● If 300ms has passed, run the function.

● If not, skip execution.

This is a simple and effective way to implement throttling based on time gaps.
🟧 Slide 5 – Throttle using setTimeout and timerFlag
Code Summary:
js

Copy code

function throttle(mainFunction, delay) {

let timerFlag = null;

return (...args) => {

if (timerFlag === null) {

mainFunction(...args);

timerFlag = setTimeout(() => {

timerFlag = null;

}, delay);

};

Concept:

● timerFlag tracks whether the function is currently in the cooldown period.

● If not, run the function and start a timer.

● During the delay, all other calls are ignored.

● Once the timer finishes, it resets timerFlag.

This pattern is great for preventing too-frequent API calls or heavy UI updates.
🟧 Slide 6 – Throttle using Closure (shouldWait flag)
Code Summary:
js

Copy code

const throttle = (func, duration) => {

let shouldWait = false;

return (...args) => {

if (!shouldWait) {

[Link](null, args);

shouldWait = true;

setTimeout(() => {

shouldWait = false;

}, duration);

};

};

Concept:

● Very similar to Slide 5, but uses a closure variable shouldWait.

● shouldWait = true right after function execution.


● After the delay, shouldWait = false so the function can run again.

This version is often easier to understand for beginners and cleanly manages
function access timing.

🧠 Summary: Debounce vs Throttle (Bonus Tip)


Feature Debounce Throttle

Fires When? After user stops At regular intervals


triggering

Common Search input, resize, typing Scroll, drag, button mashing


Use

Behavior Ignores all until silence Executes at controlled pace

🔹 1. Debouncing vs Throttling (Conceptual Explanation)


✅ Debouncing
● What is it? A technique to delay a function until a pause happens in a rapid event.

● Real-world Example: A user types in a search bar. You don’t want to search on every
keystroke—only when they stop typing.

● How it works: Waits for a delay after the last event. If another event occurs, the timer
resets.

● Best for: Forms, auto-suggestions, filtering, etc.

● Goal: Run function once, after the final action.

✅ Throttling
● What is it? A technique to ensure a function runs at most once in a fixed time interval.

● Real-world Example: Scrolling or resizing the window—you might want to limit the rate
at which events fire.
● How it works: Only allows execution every X milliseconds, ignoring excess calls in
between.

● Best for: Scroll events, mouse movement tracking, resize handling, etc.

● Goal: Run function at regular intervals, even during continuous actions.


✅ Fill in the blanks:


"Higher-order functions allow for functions to be created
dynamically at runtime. In languages like JavaScript,**
functions are first-class objects, meaning, they can be saved in
variables, passed to other (possibly higher-order) functions, and
returned from (possibly higher-order) functions. To enable this,
HOF are typically managed on the heap at runtime."** ✅

🔹 2. Set-Based Duplicate Removal


✅ Code:
js

Copy code

const arr = [1, 2, 2, 3, 4, 5, 5, 3, 6];

const uniqueUsingSet = [...new Set(arr)];

✅ Key Concept:

● Set is a data structure that only stores unique values.

● This method is clean, quick, and great for performance.

● Use case: Quickly remove duplicates from an array.

💡 Why Use It?


● No loops.
● Cleaner and faster than using includes() manually for large arrays.

🔹 3. Loop-Based Duplicate Removal


✅ Code:
js

Copy code

const uniqueUsingLoop = [];

for (let i = 0; i < [Link]; i++) {

if (![Link](arr[i])) {

[Link](arr[i]);

✅ Key Concept:

● We manually build a unique array by checking if an item is already added using


includes().

● More manual control, but slower for large arrays due to repeated scanning (includes
is O(n)).

💡 When to Use?
● When you want to understand logic step by step.

● Great for beginners learning arrays and loops.

🔹 4. reduce() Method – Signature and Usage


✅ reduce() signature:
js

Copy code

[Link]((accumulator, currentValue, currentIndex, array) => {},


initialValue);

✅ Parameters:
● accumulator: Carries the result as it loops.

● currentValue: Current item being processed.

● currentIndex (optional): Index of current element.

● array (optional): Full array being iterated.

✅ Use Case – Removing Duplicates:


js

Copy code

const uniqueUsingReduce = [Link]((acc, curr) => {

if (![Link](curr)) [Link](curr);

return acc;

}, []);

💡 Why Use It?

● reduce() is very powerful and flexible—you can build almost anything with it.

● Encourages functional programming style.

● Best for custom accumulations like sums, averages, flattening arrays, etc.
🔹 5. Higher-Order Functions (HOF)
✅ What are HOFs?
● Functions that either:

○ Take other functions as arguments OR

○ Return a function

✅ Why Important?
● They allow modularity, reuse, and functional programming patterns.

✅ Examples:
js

Copy code

// HOF taking a function

setTimeout(() => [Link]("Hi"), 1000);

// HOF returning a function

function multiply(x) {

return function(y) {

return x * y;

};

💡 Key Concept:
● In JavaScript, functions are first-class citizens.

● This means they can be assigned, returned, and passed—like any variable.
● Closures often form with HOFs (a function "remembers" its outer scope).

✅ Filled-in Version:
Higher-order functions can either accept functions, return functions, or both, but not
always both!

forEach, map, reduce, filter accept a callback function as an argument and execute
that function on each element of the array.

✅ Slide 1: Global Variables and Reduce – The


Problem
🔍 What's Happening:
js
CopyEdit
const seen = new Set(); // Global variable

● You're using a global Set called seen to keep track of duplicates.

● This works technically, but it’s dangerous and against best practices.

❌ Problems:
● seen is leaked outside the reducer.

● If multiple reduce functions use the same seen, they might clash.

● Violates OOP principles: no encapsulation or abstraction.

🧠 Key Concept:
Avoid leaking state outside functional scopes. Functional programming favors pure
functions that don’t depend on or modify shared state.

✅ Slide 2: Using Closures for Safe Reducers –


The Solution
🔍 What's Happening:
js
CopyEdit
function createUniqueReducer() {
const seen = new Set();
return function (accumulator, currentValue) {
...
};
}

● A factory function (createUniqueReducer) returns a closure.

● Each call gets a fresh new seen Set, isolated from others.

✅ Benefits:

● seen is now private and scoped within the closure.

● No side effects or shared state.

● Safe, reusable, and aligns with functional programming best practices.

🧠 Key Concept:
Closures help encapsulate logic and state. Every call to a factory function can return a new
function with its own preserved environment.

✅ Slide 3: Comparing Approaches – Set vs


Closure
🔍 Two Solutions:

1. Set in accumulator: Efficient but requires Set-specific logic.

2. Set in closure: Cleaner, more modular.

js
CopyEdit
const uniqueUsingReduce = [Link]((acc, cur) => {
if (![Link](cur)) [Link](cur);
return acc;
}, new Set());

VS

js
CopyEdit
const uniqueNumbers = [Link](createUniqueReducer(), []);

🧠 Key Concept:
● Both remove duplicates.

● Closure-based version promotes better encapsulation.

● Accumulator-based version might be faster but is less readable and reusable.

✅ Slide 4: HOF and Currying


js
CopyEdit
var f = function (x) {
return function (y) { return y - x; };
};

var g = f(7);
[Link](g(5)); // Output: -2

🧠 Key Concept:
● Higher-order function (HOF): A function returning another function.

● f creates a function that remembers x due to closure.

● g = f(7) means g(y) is now y - 7.

This is similar to currying, where functions are broken into smaller, unary functions.

✅ Simple Definition of Currying:


Currying is the process of turning a function that takes multiple arguments into a sequence of
functions that each take one argument.

💡 In Simple Terms:
Instead of writing:

js

CopyEdit

add(2, 3) // 5

You write:

js

CopyEdit

add(2)(3) // 5
🧠 Example:
js

CopyEdit

function add(x) {

return function(y) {

return x + y;

};

const add2 = add(2);

[Link](add2(3)); // 5

This is currying: breaking add(x, y) into add(x)(y).

✅ Slide 5: Understanding Scope and Closures


🔍 Code Breakdown:
js
CopyEdit
var b = 6;

var foo = function (a) {


a = b + a;
return function () { return a; };
};

b = 2;

var bar = function () {


var b = 3;
return foo(b); // foo(3), global b is 2
};

x = bar();

📌 What happens?

● foo(3) → a = 2 + 3 = 5 → returns function () { return 5; }

● So bar() returns a function, not a value.

🧠 Key Concept:
● JavaScript uses lexical (static) scoping.

● b inside foo refers to the global b, which is 2, not the one inside bar.

✅ Slide 6: Dynamic vs Static Scope


🔍 Same code, but now imagining JavaScript is dynamically scoped.
js
CopyEdit
var b = 6;

var foo = function (a) {


a = b + a;
return function () { return a; };
};

b = 2;

var bar = function () {


var b = 3;
return foo(b); // What if JS were dynamically scoped?
};
📌 Hypothetical Output:
● In dynamic scoping, variables are resolved from the call stack, not from where the
function was defined.

● So b would be 3 (from bar), and a = 3 + 3 = 6.

🔰 PART 1: Understanding Closures in JavaScript

🔹 Slide: "Practice closure with reasoning"


"Closures allow JavaScript to emulate private variables by keeping a function's
local state alive after its parent has returned."

🔍 Explanation:

● A closure is formed when a function “remembers” the variables from its outer (lexical)
scope even after that outer function has completed execution.

● This is key to memory safety, privacy, and encapsulation (i.e., preventing variables
from being globally accessible).

🔹 Slide: Counter Question (Global vs Closure-based)


❌ Example 1 (Global counter):

js

CopyEdit

let count = 0;

function increment() {

count++;

return count;

}
🔍 Problem:

● count is global.

● Any part of the program can directly modify it (count = 999;) — so no encapsulation
or safety.

✅ Example 2 (Closure-based):

js

CopyEdit

function createCounter() {

let count = 0;

return function() {

count++;

return count;

};

const counter = createCounter();

🔍 Advantage:

● count is now a private variable inside the outer function.

● Only the returned inner function can access/update it.

● This is true closure behavior and safer!

🔹 Slide: Login Attempt Tracker


js
CopyEdit

function createLoginAttemptTracker() {

let attempts = 0;

return function() {

attempts++;

if (attempts > 3) {

[Link]('Account locked!');

} else {

[Link]('Login attempt:', attempts);

};

✅ Concept Used:

● Tracks login attempts privately using a closure.

● Every function call shares the same attempts variable scoped in the closure.

🧠 Memory-Safe Filtering: Closures + Set

🔹 Slide: Remove Duplicates using Set with Closure


js

CopyEdit

function createUniqueCollector() {
const seen = new Set();

return function(value) {

if (![Link](value)) {

[Link](value);

return true;

return false;

};

🔍 Explanation:

● seen is a private Set maintained in the closure.

● Helps in filtering out duplicates safely.

● Encapsulates state (no external seen variable).

🧠 Caching / Memoization Using Closures

🔹 Slide: Memoized Square Function


js

CopyEdit

function createMemoizedSquare() {

const cache = {};


return function(n) {

if (cache[n]) {

[Link]('from cache:', cache[n]);

return cache[n];

const result = n * n;

cache[n] = result;

[Link]('calculated:', result);

return result;

};

✅ Concept Used:

● cache is stored inside the closure.

● If a result exists, it reuses it.

● If not, it calculates and saves it.

🔁 This technique is called memoization, great for performance!

🚀 PART 2: Full-Stack Project (Remove Duplicates)

🔹 Backend: Setup Instructions


bash

CopyEdit

npm init -y
npm install express cors

npm install --save-dev nodemon

📦 Add this to [Link]:

json

CopyEdit

"dev": "nodemon [Link]",

"type": "module"

Then run:

bash

CopyEdit

npm run dev

🔹 Backend: [Link]
js

CopyEdit

import express from 'express';

import cors from 'cors';

import { getSharedPosts } from './controllers/[Link]';

const app = express();

[Link](cors());
[Link]('/api/shared-posts', getSharedPosts);

[Link](5000, () => {

[Link]('Server running on [Link]

});

🧠 Concept:

● API endpoint /api/shared-posts is handled by getSharedPosts.

● CORS is enabled for frontend compatibility.

🔹 [Link]
js

CopyEdit

export const getSharedPosts = (req, res) => {

const shares = [

{ userId: 1, postId: 101 },

{ userId: 2, postId: 101 },

{ userId: 1, postId: 101 }, // duplicate

];

const uniqueShares = [Link](

createUniqueReducer('userId', 'postId'),

[]

);
[Link](uniqueShares);

};

🔹 [Link]
js

CopyEdit

export function createUniqueReducer(...keys) {

const seen = new Set();

return function(acc, item) {

const key = [Link](k => item[k]).join('|');

if (![Link](key)) {

[Link](key);

[Link](item);

return acc;

};

✅ Concept:

● Uses closure to maintain seen Set.

● Ensures unique combinations of userId + postId.


🎨 Frontend (React + Vite)

🔹 Project Setup
bash

CopyEdit

npm create vite@latest remove-duplicates --template react

cd remove-duplicates

npm install

npm run dev

🔹 React Component ([Link])


jsx

CopyEdit

return (

<div className="App">

<h1>Shared Posts</h1>

<ul>

{[Link]((share, index) => (

<li key={index}>

User {[Link]} shared post {[Link]}

</li>

))}

</ul>
</div>

);

🔹 React: Fetching from Backend


jsx

CopyEdit

useEffect(() => {

fetch('[Link]

.then(res => [Link]())

.then(data => setShares(data))

.catch(err => [Link](err));

}, []);

✅ Concept:

● Connects to backend.

● Loads filtered unique posts.

● Uses React useEffect for API call.


book content
let c = 42;
[Link](typeof c); // "number"

✅ 4. String
javascript
CopyEdit
let d = "hello";
[Link](typeof d); // "string"

✅ 5. Native Object representing function


javascript
CopyEdit
function myFunc() {}
[Link](typeof myFunc); // "function"

✅ 6. Native Object not representing function


javascript
CopyEdit
let e = { name: "Lara" };
[Link](typeof e); // "object"
✅ 7. Declared variable with no value

let f;
[Link](typeof f); // "undefined"

✅ 8. Undeclared variable

[Link](typeof g); // "undefined"


// 'g' was never declared, but typeof still returns "undefined"

✅ 9. Nonexistent property of an object

let obj = { name: "Lara" };


[Link](typeof [Link]); // "undefined"
// 'age' does not exist on obj

Primitive Data Types


In JavaScript, a primitive value is a single value with no properties or methods.

JavaScript has 7 primitive data types:

● string
● number
● boolean
● bigint
● symbol
● null
● undefined

🔹 What is the Symbol data type in JavaScript?

The Symbol is a primitive data type introduced in ES6 (ECMAScript 2015).


It is used to create unique identifiers for object properties, especially useful when you want to
avoid name conflicts.

Complex Data Types


A complex data type can store multiple values and/or different data types
together.

JavaScript has one complex data type:

● object

All other complex types like arrays, functions, sets, and maps are just different
types of objects.

The typeof operator returns only two types:

● object
● function

● null, undefined

● Symbols

● BigInts

let str = "hello";


str[0] = "H"; // ❌ Does not change string
[Link](str); // "hello"

Anything not falsy is truthy.

Common examples:

if (true)
if (1)
if (-1)
if ("hello") // non-empty string
if ([]), if ({}) // empty array/object
if (Infinity)
if (Symbol())

✅ Example:

if ("JavaScript") {
[Link]("This is truthy"); // Output: This is truthy
}

✅ TABLE 4.2 — Data Type Conversions to


Boolean
Original Value Boolean
Value
undefined false

null false

0 false

NaN false

"" (empty false


string)
Any other value true

Examples:

[Link](Boolean(undefined)); // false
[Link](Boolean(null)); // false
[Link](Boolean(0)); // false
[Link](Boolean(NaN)); // false
[Link](Boolean("")); // false
[Link](Boolean("hello")); // true
[Link](Boolean(123)); // true
[Link](Boolean([])); // true

✅ TABLE 4.3 — Data Type Conversions to String


Original Value String Value

undefined "undefined"

null "null"

true, false "true", "false"

NaN "NaN"

Infinity, -Infinity "Infinity", "-


Infinity"
Numbers (up to ~20 digits) As-is

Big Numbers (>20 digits) Scientific notation

Object Uses .toString()

Example:

[Link](String(undefined)); // "undefined"
[Link](String(null)); // "null"
[Link](String(true)); // "true"
[Link](String(NaN)); // "NaN"
[Link](String(Infinity)); // "Infinity"
[Link](String(12345)); // "12345"
[Link](String(1e21)); // "1e+21"
[Link](String([1, 2])); // "1,2"
[Link](String({name: "Lara"}));// "[object Object]"

✅ TABLE 4.4 — Data Type Conversions to


Number
Original Value Number Value

undefined NaN

null, false, "" 0

true 1
String (numeric) Parsed number

String (non-numeric) NaN

Object Uses .valueOf


()

Examples:

[Link](Number(undefined)); // NaN
[Link](Number(null)); // 0
[Link](Number(false)); // 0
[Link](Number("")); // 0
[Link](Number(true)); // 1
[Link](Number("123")); // 123
[Link](Number("abc")); // NaN
[Link](Number({valueOf: () => 7})); // 7

🔑 JavaScript Type Conversion – Key Points with


Examples

✅ 1. Arithmetic Operators (+, -, *, /, %)


● Most convert operands to Numbers.
Example:
alert("5" - 2); // 3 (string "5" converted to number)

✅ 2. Special Case for + Operator


● If one operand is a string, the other is converted to string → concatenation.

Example:
alert("5" + 2); // "52

✅ 3. Relational Operators (<, >, <=, >=)


● Convert non-string operands to numbers for comparison.

alert("5" < 10); // true ("5" becomes 5)


✅ 4. String vs String → Lexicographic Comparison


● Compared character by character.

Example:
[Link]("apple" < "banana"); // true
[Link]("abc" < "abcd"); // true

✅ 5. Equality (==) vs Strict Equality (===)

● == allows type conversion

● === checks type and value (no conversion)

Examples:

[Link](5 == "5"); // true (converted)


[Link](5 === "5"); // false (different types)
✅ 6. Special == Case: null == undefined

● They are considered equal with ==

Example:
[Link](null == undefined); // true

✅ 7. Object Equality
● Objects are equal only if they reference the same object.

Example:
let a = {};
let b = {};
[Link](a == b); // false (different objects)

✅ 8. Unary + or -
● Converts to Number

Example:
[Link](+"5"); // 5
[Link](-"5"); // -5

✅ 9. Logical Operators (&&, ||, !)


● Convert operands to Boolean

Example:
[Link](!""); // true (empty string is falsy)

● [Link]("hi" && 5); // 5 (both truthy → returns 2nd value)

🔹 && (Logical AND) in JavaScript


In JavaScript, the && operator does not always return a boolean. Instead, it returns one of the
operands based on truthiness.
✅ Concept:
javascript
CopyEdit
A && B

● If A is falsy, it returns A.

● If A is truthy, it returns B.

🟦 1. JavaScript Objects = Key-Value Pairs


● Objects are like containers with named properties (like variables inside the object).

var person = {

name: "Lara",

age: 22

};

🟦 2. Properties Can Have Any Data Type


● You can assign Boolean, String, Number, etc., to the same property:

var obj = {};

[Link] = true;

[Link] = "hello";

[Link] = 42; // all valid

🟦 3. No Classes Required (Unlike Java/C++)


● JavaScript doesn't require classes to define objects.

● You can directly add/remove properties anytime.

var o1 = new Object();

[Link] = "Hi";

delete [Link]; // Removes property

🟦 4. Adding Properties Dynamically


● Properties can be added at any time—even after the object is created.

var car = {};

[Link] = "red"; // Added later

🟦 5. delete Keyword Removes a Property

delete [Link]; // Removes the 'color' property

🟦 6. new Keyword Creates an Empty Object

var obj = new Object(); // same as {}

🟦 7. Object Initializer = Shortcut to Create Object

var o2 = {
p1: 5 + 9,

p2: null,

testing: "This is a test"

}; // Creates object with 3 properties


⚠️8. No Error for Misspelled Property
● JavaScript just creates a new property:

[Link] = "Lara"; // Typo: creates new property, no error

✅ Are objects iterable?

No, plain JavaScript objects are not iterable with for...of — only with for...in.

🔄 Loops in JavaScript – Basic Concepts & Examples

🔹 for...in → Iterates over object keys

const user = { name: "Lara", age: 22 };

for (let key in user) {

[Link](key); // name, age

[Link](user[key]); // Lara, 22

✅ Best for: objects

🔹 for...of → Iterates over iterable values (arrays, strings, etc.)

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

for (let fruit of fruits) {

[Link](fruit); // apple, banana

✅ Best for: arrays, strings, maps, sets

❌ Does not work directly on plain objects.


🔹 .forEach() → Calls a function for each array element

const nums = [1, 2, 3];

[Link](function(num) {

[Link](num); // 1, 2, 3

});

✅ Best for: arrays

🔁 for...of vs .forEach() – Comparison

Feature for...of .forEach()

Works on Iterables (e.g. arrays, Arrays only


strings)

Syntax Loop syntax Method with callback function

Break/Continue ✅ Yes ❌ No (must use return in


callback)
🎯 The Goal:
Understand how object references behave in a function in JavaScript.

Imagine this like two bowls of food:

● o1 = bowl1 with "original"

● o2 = bowl2 with "original"

You hand these bowls to someone (param1 and param2) and ask them to:

1. Change the food in bowl1 to "changed".

2. Start using bowl1 instead of bowl2.

Step-by-step from the diagram:


✅ (a) Before function starts:
● param1 holds o1 (bowl1).

● param2 holds o2 (bowl2).

So:

param1 → { data: "original" } (same as o1)

param2 → { data: "original" } (same as o2)

✅ (b) After [Link] = "changed":

You modify the contents of bowl1 (which both o1 and param1 point to).

Now:

param1 → { data: "changed" } (o1 also sees this change)

param2 → { data: "original" } (o2 stays the same)

✅ (c) After param2 = param1:

You tell param2:

"Hey, stop using your old bowl (o2). Use the same bowl as param1 now (which is
o1)."

Now:

param1 → { data: "changed" } (same as o1)

param2 → { data: "changed" } (now same as param1)

BUT o2 is still → { data: "original" }

So o2 is untouched. You only changed what param2 points to — not o2 itself.

🧠 Final Concept:
● Objects in JS are passed by reference (like handing someone your bowl).

● But if they point param2 to a new object, it doesn’t affect the original bowl (o2).

● Changing the contents = affects original.

● Changing the pointer = affects only the copy.

Key Points on JavaScript Constructors (Section 4.10.6)

● Every JavaScript function can act as a constructor when called with the new
keyword.

● When a function is called as a constructor:

○ A new empty object is created automatically.

○ The this keyword inside the function refers to this new object.

○ The function initializes properties and methods on this.

○ The new object is returned implicitly (no need to use return).

Example constructor function for a binary tree node (BTNode):


function BTNode(value) {

[Link] = null;

[Link] = null;

[Link] = value;

[Link] = function() {

return [Link] == null && [Link] == null;

};

var node1 = new BTNode(3);

var node2 = new BTNode(7);

[Link] = node2;

[Link]([Link]()); // false (has a child)


[Link]([Link]()); // true (no children)

● The created objects node1 and node2 are called instances of BTNode.

● You can check if an object is an instance of a constructor function using the


instanceof operator:

[Link](node1 instanceof BTNode); // true

Key Points: Common Array Methods in JavaScript

toString()
Converts the array to a comma-separated string.
Example:
[1, 2, 3].toString(); // "1,2,3"

sort([compareFunction])
Sorts the array elements. You can provide a function to define the sort order.
Example:
[3, 1, 2].sort(); // [1, 2, 3]

● splice(start, deleteCount, itemToAdd)


Adds/removes elements at a specified index.

○ Add element without removing:

let arr = [1, 2, 4];

[Link](2, 0, 3); // arr is now [1, 2, 3, 4]

○ Remove elements:

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


[Link](1, 2); // removes 2 elements starting at index 1, returns
[2, 3]

push(element)
Adds an element to the end of the array and returns the new length.
Example:

let arr = [1, 2];

[Link](3); // arr: [1, 2, 3], returns 3

pop()
Removes the last element and returns it.
Example:
let arr = [1, 2, 3];

[Link](); // returns 3, arr is now [1, 2]

shift()
Removes the first element and returns it, shifting all others down by one.
Example:
let arr = [1, 2, 3];

● [Link](); // returns 1, arr is now [2, 3]

Sure! Here are the key points from the content in simple terms:

● Global object in JavaScript browsers is window.

● All global variables and functions are stored as properties of window.

● Built-in objects like Object, Array are properties of window (e.g., [Link]).

● Host environment objects (like alert, prompt) are also properties of window.

● When a variable or function is not found locally, JavaScript looks for it in window.

● window also contains useful properties like Infinity (e.g., [Link]).

Example:

var x = 10;

[Link](window.x); // Outputs: 10

alert("Hello"); // same as [Link]("Hello")


[Link]([Link]); // Outputs: Infinity

Yes, the window object is closely related to the DOM because it represents the browser’s
window containing the DOM document. It provides access to the DOM via its document
property (i.e., [Link]), and it also controls browser-related features like timers,
events, and more.

So, window is the global object that hosts the DOM and other browser APIs.

Absolutely! Here’s a clearer, detailed explanation of each method with examples:

1. charAt(index)

● What it does: Returns the character at the specified position (index) in the string.

● Details: Indexing starts at 0 (the first character is at position 0). If the index is out of
range, it returns an empty string.

Example:
let str = "hello";

[Link]([Link](1)); // Output: "e" (the character at index 1)

2. concat(string)
● What it does: Joins (concatenates) the original string with another string provided as an
argument, returning a new combined string.

Example

let str1 = "hello";

let str2 = " world";

[Link]([Link](str2)); // Output: "hello world"

3. indexOf(searchString, startIndex)

● What it does: Returns the index of the first occurrence of searchString within the
string, starting from the position startIndex. If not found, returns -1.
● Details:

○ searchString: The substring you want to find.

○ startIndex (optional): The position in the string from which to start the search.
If omitted, starts at the beginning (index 0).

Example:
let str = "hello";

[Link]([Link]("l")); // Output: 2 (first 'l' found at


index 2)

[Link]([Link]("l", 3)); // Output: 3 (start searching


from index 3)

[Link]([Link]("z")); // Output: -1 (not found)

4. replace(oldString, newString)

● What it does: Returns a new string where the first occurrence of oldString is
replaced with newString.

● Note: Only the first match is replaced unless you use a global regular expression.

Example:
let str = "hello";

[Link]([Link]("l", "p")); // Output: "heplo" (only first


'l' replaced)

5. slice(start, end)

● What it does: Returns a substring starting from start index up to (but not including)
the end index.

● Details:

○ start: The starting index of the slice.


○ end (optional): The ending index (not included in the result). If omitted, goes to
the end of the string.

Example:
let str = "hello";

[Link]([Link](1, 4)); // Output: "ell" (characters from index


1 to 3)

[Link]([Link](2)); // Output: "llo" (from index 2 to end)

6. toLowerCase()
● What it does: Returns a new string with all uppercase characters converted to
lowercase.

Example:
let str = "HELLO";

[Link]([Link]()); // Output: "hello"

7. toUpperCase()
● What it does: Returns a new string with all lowercase characters converted to
uppercase.

Example:
let str = "hello";

● [Link]([Link]()); // Output: "HELLO"

While the value of the Null data type is represented by the


JavaScript keyword null, the Undefined type has no associated keyword
in the JavaScript language. Assume that the variable testVar has been
declared in a JavaScript program. Write JavaScript code that could be
inserted into this program that will output the string undefined if
testVar has the Undefined type’s value and output defined otherwise.

✅ What the Question is Asking


The question is testing your understanding of JavaScript’s undefined and null types:

● null is an intentional absence of any value and is set using the keyword null.

● undefined means a variable has been declared but not assigned a value.

Now, the question says:

Assume that the variable testVar has been declared.

That means something like:

var testVar;

And then it asks you to write JavaScript code that:

● Outputs "undefined" if testVar has the value of type Undefined

● Outputs "defined" otherwise

✅ Explanation

● typeof testVar === "undefined" checks if testVar is of type undefined.

● If it is, it prints "undefined".

● Otherwise, it prints "defined" — which means the variable has some value (even
null would be treated as "defined").

✅ Example Code

var testVar; // declared but not assigned, so it's undefined

if (typeof testVar === "undefined") {

[Link]("undefined");

} else {

[Link]("defined");

If later in the program you assign a value:


testVar = null; // null is a defined value

if (typeof testVar === "undefined") {

[Link]("undefined");

} else {

[Link]("defined");

This will output:

defined

Because null is a valid value — it's not undefined.

4.2 Whatisoutputifthefollowing JavaScript program is executed by atypical webbrowser?


Explain. var i=5; function duh() { var i; window.i=6; } duh(); [Link](i)

✅ What does window.i represent in JavaScript?

In a web browser, the window object is the global object for all JavaScript running in the
browser. Any variable declared with var in the global scope becomes a property of window.

So:

var i = 5;

Is actually the same as:

window.i = 5;

That means:

● i and window.i refer to the same thing if i is declared globally using var.

● Inside a function, if you use var i;, that i is local to the function and does not affect
window.i.

✅ In Your Code Example:


var i = 5; // Global variable, same as window.i = 5

function duh() {

var i; // Local i (not used)

window.i = 6; // Changes the global i

duh();

alert(i); // Outputs 6, since window.i was changed

● window.i refers to the global variable i.

● Even though there's a local i in the function, window.i = 6; updates the global
variable.

✅ Important Notes:

● Only variables declared with var in the global scope are added to window.

● Variables declared with let or const in the global scope do not become properties of
window.

let x = 10;

[Link](window.x); // undefined

Let me know if you’d like to see how this differs in [Link] or using let and const.

4.3 To what does the following JavaScript expression evaluate? Explain in detail how
JavaScript arrives at this result. Number("007") == "007"

✅ Given JavaScript Expression:


javascript

Copy code

Number("007") == "007"
✅ What is Being Asked?
We are being asked to evaluate whether:

● Number("007") is equal to "007"

And to explain how JavaScript processes this expression.

🔍 Step-by-Step Breakdown
▶️Step 1: Number("007")

● "007" is a string.

● When passed into Number(), JavaScript tries to convert it to a number.

● "007" becomes 7 — leading zeros are ignored in numeric conversion.

So:

Number("007") === 7 ✅

▶️Step 2: Comparison with "007"


Now the expression is:

7 == "007"

This is a comparison between:

● A number (7)

● A string ("007")

Because we're using == (the loose equality operator), type coercion happens.

▶️Step 3: Type Coercion Rules for ==


When comparing a number and a string using ==, JavaScript will:

Convert the string to a number, then compare.

So:

"007" → 7

Then:

7 == 7 → true

4.4 Whatisoutputifthefollowing JavaScript program is executed by atypical webbrowser?


Explain. var o1 = new Object(); o1.j = 9; var o2 = o1; function test(o1) { o1.j=10; return; }
test(o1); [Link](o2.j);

✅ Given Code:

var o1 = new Object();

o1.j = 9;

var o2 = o1;

function test(o1) {

o1.j = 10;

return;

test(o1);

[Link](o2.j);

✅ What is the Question Asking?


We want to know:

What will be the output of [Link](o2.j); and why?

🔍 Step-by-Step Explanation
🔸 Step 1: Create an Object
var o1 = new Object();

o1.j = 9;

● o1 is an object: { j: 9

🔸 Step 2: Assign o2 = o1

var o2 = o1;

● This does not create a copy.

● Instead, o2 is now a reference to the same object as o1.

● So o1 and o2 both point to: { j: 9 }

🔸 Step 3: Pass o1 to the function

function test(o1) {

o1.j = 10;

return;

When we call:

test(o1);

Inside the function:

● o1 still refers to the same object.

● So modifying o1.j = 10; actually updates the object shared by both o1 and o2.

🔸 Step 4: Alert o2.j

[Link](o2.j);

Since both o1 and o2 point to the same object, and we updated j to 10, this outputs:

10

4.5 Write JavaScript code that will create an Object with a property named color having a
String value of red.
Here's the JavaScript code to create an object with a property named color having the string
value "red":

var myObject = {

color: "red"

};

✅ Explanation:

● myObject is the name of the object.

● color is a property of the object.

● "red" is a string value assigned to the color property.

🟢 Alternate Way (using new Object() syntax):

var myObject = new Object();

[Link] = "red";

Both methods are valid. The first one (object literal syntax) is more commonly used.

4.6 JavaScript code used by a Web document must be in a file that can be read by
anyone who can access the document. In an attempt to keep others from using their
code, some JavaScript authors obfuscate their code—that is, attempt to reduce the
intelligibility of their code—in various ways. What does the following obfuscated code
do, and why? var weird = "al" + "father".slice(4, 6) + "t"; window[weird]("Weird, but it
works.");

✅ Given Code:

var weird = "al" + "father".slice(4, 6) + "t";

window[weird]("Weird, but it works.");

🧠 Step-by-Step Explanation
▶️Step 1: Evaluate weird

var weird = "al" + "father".slice(4, 6) + "t";

Let's evaluate "father".slice(4, 6):

● JavaScript slice(start, end) extracts characters from index start up to but not
including end.

● "father".slice(4, 6) → "er"

So the full expression becomes:

var weird = "al" + "er" + "t";

Which gives:

var weird = "alert";

▶️Step 2: Evaluate window[weird]("Weird, but it works.");

Since weird = "alert", this becomes:

window["alert"]("Weird, but it works.");

In JavaScript:

● window["alert"] is the same as [Link]

● So it executes:

alert("Weird, but it works.");

✅ Final Output:
A browser popup alert appears with the message:

Weird, but it works.


4.7. Insert parentheses in the following expression in order to make the operator
precedence relationships clear. a=b?z/=y?x:w?v:u: d += e

📌 Original Expression:
a = b ? z /= y ? x : w ? v : u : d += e

It uses several JavaScript operators, including:

● Assignment: =, +=, /=

● Ternary (conditional): ? :

This can get confusing without parentheses. Your goal is to insert parentheses to make the
precedence and associativity explicit.

✅ Step 1: Understand Operator Precedence


Here's a simplified view of the relevant operator precedence (from highest to lowest):

Precedenc Operator(s) Description Associativit


e y
14 () Grouping n/a

13 ?: Ternary (conditional) Right-to-left

12 =, +=, /= Assignment Right-to-left


operators

So:

● Ternary (? :) binds tighter than assignment.

● Assignments evaluate right to left.

● The expression is full of nested ternary and assignment operations, so we’ll need to
disambiguate it carefully.

✅ Step 2: Disambiguate the Expression


Let’s break it down and add parentheses to clarify what's happening.

Original:

a = b ? z /= y ? x : w ? v : u : d += e

Let's read from the outermost a = assignment. Everything on the right is the value assigned to
a.

Now we'll break the ternary structure from inside out.

Ternary structure:

a = b

?( z /= (y ? x : (w ? v : u)) )

: (d += e);
✅ Fully Parenthesized Expression:
a = b

? (z /= (y ? x : (w ? v : u)))

: (d += e);

4.8 Some applications, such as random number generators and certain cryptographic
algo rithms, are explicitly designed to use arithmetic overflow as part of their
computation. An overflow can occur in Java, for example, when two large int’s are
multiplied to gether and the result is stored in an int. If the result of the multiplication
exceeds 32 bits, only the lower 32 bits are stored (recall that a Java int stores 32 bits,
with the most significant being the sign bit). The higher-order bits, including the original
sign bit, are lost, and the new most-significant bit becomes the new sign bit. Explain how
such an overflow can be simulated in JavaScript using one of the JavaScript bit
operators.

📌 What Is the Question Asking?


It's asking how to simulate 32-bit signed integer overflow in JavaScript, which doesn't have a
fixed-size int type like Java does.

🔍 Key Points:

● Java int = 32-bit signed integer.

● Overflow in Java: if a computation result is > 2³¹ - 1 or < -2³¹, it wraps around (i.e.,
overflows).

● JavaScript uses 64-bit floating point numbers for all numeric types by default, so it
doesn’t overflow in the same way.

● But we can simulate 32-bit overflow in JavaScript using bitwise operators.

✅ How to Simulate 32-bit Signed Integer


Overflow in JavaScript
🎯 Solution: Use | 0 (bitwise OR with zero)

In JavaScript, bitwise operators (|, &, ^, etc.) convert operands to 32-bit signed integers
internally. So when you do:
let result = someLargeNumber | 0;

JavaScript simulates the 32-bit signed overflow behavior just like Java.

✅ Example:
Let’s multiply two large numbers that would cause overflow in a 32-bit system:

let a = 50000;

let b = 50000;

let result = a * b;

[Link](result); // 2500000000 — this is a valid JS number


(no overflow yet)

// Simulate 32-bit overflow:

let overflowed = (a * b) | 0;

[Link](overflowed); // -1794967296 — this is the overflowed


result

🔍 Why Does This Work?

● (a * b) gives 2500000000, which is bigger than the max 32-bit signed int
(2,147,483,647).

● Using | 0 forces JavaScript to treat the result as a signed 32-bit integer.

● The higher bits are discarded, just like Java, and it wraps around to a negative
number.

🧠 Visual Analogy:
Think of the 32-bit integer like a circle (ring buffer). If you go above the max limit (2^31 - 1),
you wrap around to the negative side due to the sign bit flipping. That’s what | 0 helps you
simulate.

Why use | 0?
1. Bitwise operators in JavaScript work with 32-bit integers
JavaScript numbers are normally 64-bit floating point (IEEE 754), but bitwise operators
internally convert their operands to 32-bit signed integers. This means:

● When you do someNumber | 0, JavaScript:

○ Converts someNumber to a 32-bit signed integer (throwing away any fractional


part and any bits beyond 32 bits).

○ Then does a bitwise OR with zero.

2. Why OR with zero?


● OR-ing with zero does not change any bits of the number.

● It acts like a "no-op" bitwise operation but forces JavaScript to convert the value to 32-
bit signed int as a side effect.

3. Other similar operations


You might also see other bitwise operators used for the same purpose, such as:

● x << 0 (left shift by 0 bits)

● x >> 0 (right shift by 0 bits)

● x | 0

All these force conversion to 32-bit signed int, but | 0 is the most common and idiomatic.

4.9 Consider the following JavaScript program: function addTo(value) { myVar += value;
return; } // Create an object with property myVar // and method addTo var o = new
Object(); [Link] = 0; [Link] = addTo; // Call the addTo method [Link](12); This
program will throw an exception. Which statement causes the exception? Why?
Howshould this code be corrected?

ou're absolutely right to investigate this carefully—this JavaScript code throws a runtime
exception, and it’s important to understand why.

✅ The problem:

function addTo(value) {
myVar += value; // ❌ This line causes the exception

return;

❌ Why this throws an exception:

● Inside the addTo function, you're trying to use myVar without declaring it.

● So JavaScript looks for a global variable named myVar.

● But myVar is not a global variable, it's a property of the object o.

● Since myVar is not found in the global scope, JavaScript throws:

ReferenceError: myVar is not defined

✅ How to fix it:

You want to refer to the myVar property of the object that is calling the method (o). Inside the
function, you should use [Link] to access it properly:

✅ Corrected code:

function addTo(value) {

[Link] += value; // ✅ Use [Link] instead of myVar

return;

var o = new Object();

[Link] = 0;

[Link] = addTo;

[Link](12);

[Link]([Link]); // ✅ Output: 12
🧠 Explanation of this:

● In JavaScript, inside a method like [Link](), the this keyword refers to the object
before the dot—in this case, o.

● So [Link] correctly refers to [Link].

4.10. What is the output of the following JavaScript program? Explain why this output is
produced. function rusty(a) { this.x = a; return; } var o1 = new Object(); var o2 = new
Object(); [Link] = rusty; [Link] = [Link]; [Link](1); [Link](2); [Link](o1.x
+ "," + o2.x);

✅ Given Code:

function rusty(a) {

this.x = a;

return;

var o1 = new Object();

var o2 = new Object();

[Link] = rusty;

[Link] = [Link];

[Link](1);

[Link](2);

[Link](o1.x + "," + o2.x);

🔍 Step-by-Step Execution:
1. Function Declaration

function rusty(a) {

this.x = a;

}
● rusty is a regular function.

● It assigns a to this.x

2. Creating Objects

var o1 = new Object();

var o2 = new Object();

● Two separate empty objects are created: o1 and o2.

3. Assigning Method

[Link] = rusty;

[Link] = [Link];

● Both o1 and o2 now have the same function rusty as their method rusty.

4. Calling [Link](1)

[Link](1);

● Inside the rusty function, this refers to o1.

● So o1.x = 1 is assigned.

5. Calling [Link](2)

[Link](2);

● Now this refers to o2.

● So o2.x = 2 is assigned.

6. Final Alert

[Link](o1.x + "," + o2.x);


● o1.x is 1

● o2.x is 2

✅ So the output is:

1,2

4.11. Write a JavaScript function drawGrid() that takes a two-dimensional array as its
sole argument. Your function should produce an alert box that displays the array with
grid lines separating the elements. For example, Figure 4.20 shows the output when the
function is called with the array ttt of Section 4.11.1. While this array is rec tangular, your
function should work for ragged arrays as well (a two-dimensional array is ragged if the
one-dimensional arrays that compose it are not all of the same length).

You're being asked to write a JavaScript function drawGrid() that:

● Takes a 2D array as input (like a tic-tac-toe board),

● Displays the content in a grid layout with lines separating rows,

● Works for ragged arrays too (i.e. arrays where inner arrays may not be the same
length),

● And uses alert() to show the final output, like the sample shown in the image you
uploaded.

✅ Example Input:

let ttt = [

['X', 'O', 'O'],

['O', 'X', 'O'],

['O', 'X', 'X']

];

drawGrid(ttt);

✅ Expected Output (shown via alert()):


X|O|O

-----

O|X|O

-----

O|X|X

✅ Solution Code:

function drawGrid(array) {

let output = "";

for (let i = 0; i < [Link]; i++) {

output += array[i].join("|") + "\n";

if (i < [Link] - 1) {

output += "-----\n"; // Adjust number of dashes if needed

alert(output);

💡 Explanation:

● array[i].join("|") joins each row with vertical bars | between elements.

● "-----" separates the rows — you could dynamically calculate the length if rows vary
in size.

● alert(output) shows the entire grid in a popup box.


Works for ragged arrays, e.g.:

let ragged = [

['X', 'O'],

['O', 'X', 'O'],

['X']

];

● drawGrid(ragged);

4.12 Writeafunctionmedian()thatacceptsaone-dimensionalarraycontaininganoddnumber
of integers as its single argument and returns the median value stored in the array (this
is the value of the middle element of a sorted version of the array). The argument array
should not be modified.

✅ Requirements:
1. Accepts a one-dimensional array containing an odd number of integers.

2. Returns the median value (i.e., the middle number when the array is sorted).

3. Does not modify the original array — so you must work on a copy.

💡 What is the median?


● Median = the middle number in a sorted list.

● For odd-length arrays, it's the element at index [Link](length / 2) after


sorting.

📌 Example:

median([7, 1, 3]); // Output: 3

median([9, 2, 5, 1, 4]); // Output: 4

✅ JavaScript Code:

function median(arr) {
// Make a shallow copy to avoid modifying the original array

let copy = [Link]();

// Sort the copy in ascending order

[Link](function(a, b) {

return a - b;

});

// Calculate and return the middle element

let midIndex = [Link]([Link] / 2);

return copy[midIndex];

🧠 Explanation:

● [Link]() → creates a copy of the original array.

● .sort((a, b) => a - b) → sorts numbers in numeric order (not lexicographic).

● [Link]([Link] / 2) → gives the middle index (because it's an odd-


length array).

● return copy[midIndex] → returns the median.

Sure! Let's do a dry run of the sort(function(a, b) { return a - b; }) using an


example array.

🔢 Example Array:

let arr = [7, 2, 5];

We want to sort this array in ascending order using:

javascript

Copy code
[Link](function(a, b) { return a - b; });

✅ Dry Run of sort(function(a, b) { return a - b; })

The sort() function compares pairs of elements and uses the result of a - b to decide the
order.

Let’s follow each step:

Step 1: Compare 7 and 2

● a = 7, b = 2

● a - b = 7 - 2 = 5 → positive

● Result: b (2) comes before a (7)

Array becomes: [2, 7, 5]

Step 2: Compare 7 and 5

● a = 7, b = 5

● a - b = 2 → positive

● Result: b (5) comes before a (7)

Array becomes: [2, 5, 7]

Step 3: Compare 2 and 5

● a = 2, b = 5

● a - b = -3 → negative

● Result: a (2) stays before b (5)


No change needed.

✅ Final Sorted Array:

[2, 5, 7]

4.13 Using a RegExp instance, write a JavaScript function isValid() that accepts a String
argument and returns true if the argument matches one of the following phone-number
formats and returns false otherwise: (123)456-7890 (123) 456-7890 123/456-7890 123-456-
7890 123 456 7890 1234567890

This question asks you to create a JavaScript function named isValid() that uses regular
expressions (RegExp) to check whether a given string matches one of several acceptable
phone number formats.

✅ Valid Formats:
The following are all considered valid:

(123)456-7890

(123) 456-7890

123/456-7890

123-456-7890

123 456 7890

1234567890

🧠 Approach Explanation
We need a regular expression that matches all the above formats.
Let’s break it down:

Format Regex Pattern Part

(123)456- ^\(\d{3}\)\d{3}-\
7890 d{4}$

(123) 456- ^\(\d{3}\)\s\d{3}-\


7890 d{4}$

123/456- ^\d{3}/\d{3}-\d{4}$
7890

123-456- ^\d{3}-\d{3}-\d{4}$
7890

123 456 ^\d{3}\s\d{3}\s\


7890 d{4}$

1234567890 ^\d{10}$

We can combine all these options using the | (OR) operator inside a regular expression.

✅ Final JavaScript Function:

function isValid(phone) {

const pattern = /^(\(\d{3}\)\d{3}-\d{4}|\(\d{3}\)\s\d{3}-\d{4}|\


d{3}\/\d{3}-\d{4}|\d{3}-\d{3}-\d{4}|\d{3}\s\d{3}\s\d{4}|\d{10})$/;

return [Link](phone);

🧪 Example Usage:

[Link](isValid("(123)456-7890")); // true

[Link](isValid("(123) 456-7890")); // true

[Link](isValid("123/456-7890")); // true
[Link](isValid("123-456-7890")); // true

[Link](isValid("123 456 7890")); // true

[Link](isValid("1234567890")); // true

[Link](isValid("123.456.7890")); // false

[Link](isValid("123 456-7890")); // false

The test() function is a method of JavaScript’s RegExp (regular expression) objects.

What does test() do?


● It tests whether a given string matches the pattern defined by the regular expression.

● It returns true if the string matches.

● It returns false if the string does not match.

CHAPTER :03
This table shows the different types of devices or ways people can view a webpage, and how HTML can tell which style to use
for each one using the media attribute.

Easy Meanings:

Word (Value) What it means

all Use this style for everything (default).

aural For devices that read text out loud, like a speech assistant.

braille For braille devices that let blind people read by touch.

handheld For phones or small devices you can carry.

print For printing the page on paper.

projection For projectors, like in a classroom or meeting.

screen For regular computer screens.


tty For old-style devices that use fixed-width text (like old terminals).

tv For TVs with low resolution and little scrolling.

EXAMPLE:

<head>

<!-- Style for computer screens -->

<link rel="stylesheet" href="[Link]" media="screen">

<!-- Style for printing -->

<link rel="stylesheet" href="[Link]" media="print">

</head>

📘 Table 3.2 — Explanation of Pseudo-Classes for <a> (anchor/link)


Elements

Selector What it Targets / Means Simple Example or Situation

a:visite Links the user has already A link that turns purple after you've clicked it.
d clicked/visited before.

a:link Links that the user has never visited A fresh, untouched link that appears blue by
before. default.

a:active A link that is being clicked (mouse is When you click a link and hold the mouse
down but not yet released). button — it might turn red.
a:hover A link that the mouse is hovering over, When you move your mouse over a link and it
but not yet clicked. changes color or gets underlined.

🔹 What This Is About:


This explains descendant selectors in CSS — these are used to style elements only when they are
inside certain other elements.

✅ Easy Examples:
1. Descendant Selector:

ul span {

font-variant: small-caps;

👉 This means:
Only make <span> text small-caps if it’s inside a <ul> (bulleted list).

2. With Class Selector:

.special span {

/* styles here */

👉 This means:
Only style the <span> if it’s inside any element that has class="special".

3. Chain of Descendants:

ul ol li {

letter-spacing: 1em;

👉 This means:
Only apply spacing to a <li> if it’s inside an <ol> (numbered list), and that <ol> is inside a <ul>
(bulleted list).
🌊 CSS Cascade: 4 Simple Steps
✅ Step 1: Select Style Sheets

What happens:
The browser collects all style sheets (main, alternate, inline styles, etc.) and the CSS rules in them.

✅ Step 2: Prioritize by Origin & Weight

What happens:
The browser gives more power (priority) to certain rules:

● User styles with !important (if any)

● Author styles (from the web page)

● Browser default styles (lowest priority)

Also, any rule with !important gets higher weight.

✅ Step 3: Break Ties by Specificity


What happens:
If two rules have the same priority, the browser checks how specific they are.
More specific wins:

● Inline styles (most specific)

● ID selectors

● Class selectors

● Element selectors (least specific)

✅ Step 4: Break Ties by Order

What happens:
If two rules still tie (same specificity), the last one written wins — the one that comes later in the style
sheet.

🧾 HTML:
<!DOCTYPE html>

<html>

<head>

<!-- External style sheet -->

<style>

p {

color: blue; /* Rule 1 - Least specific */

.highlight {

color: green; /* Rule 2 - More specific */

#mainText {

color: red; /* Rule 3 - Even more specific */

}
p {

color: purple; /* Rule 4 - Same selector as Rule 1 but comes later */

</style>

</head>

<body>

<p id="mainText" class="highlight" style="color: orange;">Hello, CSS


Cascade!</p>

</body>

</html>

🔍 What Happens (Step-by-Step):


1. Select All Rules:

The browser gathers all the CSS rules from the <style> tag and the inline style.

2. Origin & Weight:

● All rules are from the same origin (the author's style).

● But style="color: orange;" is an inline style, so it gets highest priority.


✅ Orange wins so far.

3. Specificity:

● Inline style (style attribute) is most specific.

● If it didn’t exist:

○ #mainText (ID) > .highlight (class) > p (element).

✅ Still orange wins due to inline style.

4. Position in Style Sheet:

● If rules had the same specificity, the one that appears last would win.

● Example: p { color: purple; } overrides the earlier p { color: blue; }.


📏 CSS Length Units – Easy Meaning

Unit Stands For What It Means (Easy Explanation)

in Inch 1 inch (same as on a ruler)

cm Centimeter 1 centimeter (a bit less than half an inch)

mm Millimeter 1 millimeter (1/10 of a centimeter)

pt Point 1 point = 1/72 inch (used in print design)

pc Pica 1 pica = 12 points

px Pixel 1 pixel = usually 1/96 inch on screen (smallest screen dot)

em Em Relative to the font size of the element. For example, 2em = 2 times the
current font size.

ex Ex Roughly the height of the lowercase letter "x" in the current font.
📌 Here's how it works:

✅ em

● 1em = current font size of the element.

● Example: If an element has font-size: 16px, then:

○ 2em = 32px

○ 0.5em = 8px

✅ ex

● 1ex ≈ height of the lowercase letter "x" in the element’s font.

● It’s smaller than 1em (usually about half).

● It still depends on the font family and font size.

🔁 Example:
body {

font-size: 20px;

p {

font-size: 1.5em; /* 1.5 × 20px = 30px */

padding: 1em; /* padding = 30px */

Here:

● The paragraph text will be 30px tall (1.5 × 20px).

● The 1em padding will be 30px, based on that paragraph's font


📚 CSS Text Properties Explained Simply

Property What It Does Common Values

text- Adds decorations like underline, none (default), underline, overline, line-
decoration overline, or strikethrough to text. through, or a combination (like underline
overline)

letter- Controls space between letters. normal (default), or a length like 2px (adds
spacing You can add or remove space. space) or -1px (reduces space)

word- Controls space between words. normal (default), or a length like 5px (adds
spacing You can add or remove space. space) or -2px (reduces space)

text- Changes the case of the text none (default), capitalize (first letter
transform automatically. uppercase), uppercase (all uppercase),
lowercase (all lowercase)

text-indent Indents the first line of a block of Length (like 20px) or percentage (like 10%), can
text by a certain amount. be negative to pull text out

text-align Aligns text horizontally within its left (default), right, center, or justify
container. (text stretches to fill line)

white-space Controls how spaces and line normal (default: collapse spaces, wrap lines),
breaks inside the text are handled. pre (preserves spaces and line breaks like in
<pre> tag)
<!DOCTYPE html>

<html>

<head>

<style>

.box {

padding: 20px; /* Space inside the box */

margin: 30px; /* Space outside the box */

border-width: 5px; /* Border thickness */

border-style: solid; /* Border style (solid line) */


border-color: blue; /* Border color */

background-color: lightyellow; /* Background to make padding visible */

width: 200px;

</style>

</head>

<body>

<div class="box">

This is a simple box with padding, margin, and border.

</div>

</body>

</html>
🖼 Canvas
● The canvas is the entire area in which the content of the web page is rendered.

● It includes everything in the document — all elements, no matter how tall the content is.

📦 Initial Containing Block (ICB)


● This is a CSS term that refers to the starting block in which all elements are laid out.

● Its size is based on:

○ The browser’s client area height, or the height of the canvas — whichever is larger.

○ The width is taken as the browser's client area width.

In this image:

● The height of the canvas (dashed box) is greater than the height of the browser
client area.

● So, the ICB height = canvas height.

● But the width of the client area is greater than the canvas width, so ICB width =
client area width.
🖥 Browser Client Area
● This is the visible part of the web page in the browser window — excluding things like
scrollbars, toolbars, and borders.

● It determines:

○ The initial viewport a user sees.

○ Part of the basis for determining the ICB dimensions.

📋 Inside the Canvas


● The canvas contains:

○ Paragraphs

○ Spans (inline elements)

○ Images

● It demonstrates normal HTML layout behavior, stacked vertically.

📌 Purpose of This Figure:


To show that:

● The ICB can be taller than the browser window (if the canvas is taller).

● The ICB can also be wider than the canvas (if the browser's client area is wider).

Why This Matters (Practically):


In CSS, properties like position: absolute are often relative to the initial containing block. So,
understanding how the ICB is defined (based on canvas and browser size) helps control precise element
placement.

📌 CSS position Property: Basic Overview


The position property in CSS determines how an element is positioned in the document flow.

🔹 1. static (default)
● Definition: The element is positioned according to the normal document flow.

Example:

css
CopyEdit
div {

position: static;


● ✅ Use case: Most elements are static by default unless you need to move them.

🔹 2. relative
● Definition: The element is positioned relative to its normal position.

Example:

css
CopyEdit
div {

position: relative;

top: 10px; /* moves 10px down from its normal spot */


● ✅ Use case: Slightly adjust position without removing from the document flow.

🔹 3. absolute
● Definition: Positioned relative to the nearest positioned ancestor (not static).

Example:

css
CopyEdit
.container {
position: relative;

.box {

position: absolute;

top: 20px;

left: 30px;


● ✅ Use case: Tooltips, dropdowns, or placing items inside a specific container.

🔹 4. fixed
● Definition: Positioned relative to the browser window, and stays fixed when scrolling.

Example:

css
CopyEdit
.navbar {

position: fixed;

top: 0;

width: 100%;


● ✅ Use case: Sticky headers, floating buttons, or navigation bars.

🔹 5. sticky
● Definition:
sticky is a hybrid position that behaves like relative until the element reaches a specified
scroll threshold (like top: 0), at which point it becomes fixed but only within its parent
container.

● Example:

css
CopyEdit
h2 {
● position: sticky;
● top: 0;
● }

● ✅ Use Case:
Use sticky for elements like section headers, table headers, or menus that should scroll
with the page but stay visible at the top when reached, without leaving their section.

EXERCISES OF CHAPTER 3
3.1. Practice writing simple style rules. In the following exercises, make use of the
following declarations (one per line): background-color: silver ; font-size: larger ; These
will be referred to as “the background declaration” and “the text declaration,”
respectively. (a) Write CSS style rules that apply the background declaration to div
elements and the text declaration to strong elements. (b) Write a single style rule that
applies both the background and text declarations to both p and em elements. (c)
Writeasingle style rule that applies the background declaration to HTML elements having
a value of Nevada for their id attributes as well as to elements belonging to the shiny
class.

(d) Write a style rule that applies the text declaration to span elements that belong to the
bigger class. (e) Write a style rule that applies the text declaration to span elements that
are descen dants of other span elements. (f) Write a style rule that applies the
background declaration when the cursor hovers over a hyperlink.

✅ (a) Apply background to div and text to strong

div {

background-color: silver;

strong {

font-size: larger;

✅ Explanation:
● This applies silver background to all <div> elements.

● It also increases the font size of all <strong> elements.

✅ (b) Apply both background and text declarations to p and em

p, em {

background-color: silver;

font-size: larger;

✅ Explanation:

● This rule applies both declarations to both <p> and <em> elements.

● The comma (,) is used to group multiple selectors.

✅ (c) Apply background to:

● Elements with id="Nevada"

● Elements of class shiny

#Nevada,

.shiny {

background-color: silver;

✅ Explanation:

● #Nevada targets any element with the ID Nevada.

● .shiny targets all elements with class shiny.


✅ (d) Apply text declaration to span elements with class bigger

[Link] {

font-size: larger;

✅ Explanation:

● This targets only <span> elements that have class bigger.

● [Link] means an element must be a span and must have the class bigger.

✅ (e) Apply text declaration to span elements that are descendants of


other span elements

span span {

font-size: larger;

✅ Explanation:

● This rule selects a span element inside another span.

● It ensures the font-size only increases for nested spans, not the outermost one.

✅ (f) Apply background declaration when cursor hovers over a


hyperlink

a:hover {

background-color: silver;

✅ Explanation:
● a:hover is a pseudo-class selector that targets anchor (<a>) elements when the
user hovers over them with the mouse.

● On hover, it applies the silver background.

✨ Hover behavior improves interactivity and UX by giving visual feedback when


users move the cursor over links.

3.2. Create three external style sheets, using a different subset of the style rules you
wrote
for the previous exercise in each style sheet. Then write a complete XHTML 1.0 Strict
document that uses all of your style rules.
(a) Your document should treat your style sheets as being of three different types:
Anon-persistent and preferred style sheet
An alternate style sheet
Astyle sheet used only if the XHTML document is printed
(b) Usethe @import rule to have the first of your style sheets import the second, which
imports the third. Your XHTML document should treat the first style sheet as a
persistent style sheet.

Here's a full solution to Exercise 3.2 involving:

● Creating 3 external style sheets with subsets of style rules from Exercise 3.1

● Creating an XHTML 1.0 Strict document that:

○ Links to all three style sheets

○ Uses @import

○ Differentiates them as:

■ Preferred & persistent

■ Alternate

■ Print-specific

🎨 Step 1: Create Three CSS Files


✅ [Link] (Preferred and persistent)

This style sheet imports [Link], which in turn imports [Link].

/* [Link] */
@import url("[Link]");

div {

background-color: silver;

strong {

font-size: larger;

✅ [Link] (Imported by [Link] and imports [Link])

/* [Link] */

@import url("[Link]");

p, em {

background-color: silver;

font-size: larger;

#Nevada,

.shiny {

background-color: silver;

✅ [Link] (Will be used for print only)

/* [Link] */

[Link] {
font-size: larger;

span span {

font-size: larger;

a:hover {

background-color: silver;

📝 Step 2: XHTML 1.0 Strict Document


✅ [Link]

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"[Link]

<html xmlns="[Link] xml:lang="en">

<head>

<title>Style Sheet Example</title>

<!-- Preferred and persistent style sheet (style1 imports style2 and
style3) -->

<link rel="stylesheet" href="[Link]" title="Preferred Style"


type="text/css" />

<!-- Alternate style sheet (use if user switches) -->


<link rel="alternate stylesheet" href="[Link]" title="Alternate
Style" type="text/css" />

<!-- Print style sheet -->

<link rel="stylesheet" href="[Link]" type="text/css"


media="print" />

</head>

<body>

<div>

This is a <strong>strong text</strong> inside a div.

</div>

<p>This is a paragraph with <em>emphasized text</em>.</p>

<div id="Nevada">This div has id="Nevada"</div>

<span class="shiny">This span has class="shiny"</span>

<span class="bigger">This is a bigger span</span>

<span>This is outer <span>This is inner span</span></span>

<a href="#">Hover over this link</a>

</body>

</html>

✅ Explanation of Requirements Fulfilled:


Requirement Fulfilled By

3 style sheets [Link], [Link], [Link]

@import chaining [Link] → [Link] → [Link]


Persistent & Preferred <link rel="stylesheet" ... title="Preferred
Style">

Alternate <link rel="alternate stylesheet" ...


title="Alternate Style">

Print-only <link rel="stylesheet" media="print">

XHTML 1.0 Strict Correct DOCTYPE and syntax

<!-- Preferred style sheet -->

<link rel="stylesheet" href="[Link]" title="Preferred Style" />

<!-- Alternate style sheet -->

<link rel="alternate stylesheet" href="[Link]" title="Alternate Style" />

3.3. Write an embeddedstyle sheet (including the appropriate HTML tags) that sets the
value of the font-family property to Gill Sans Bold SmallCaps & OSF for all elements of
the document.

Embedded style (also called internal CSS) means writing CSS rules inside a <style> tag in
the <head> section of an HTML document. It applies styles to that page only.

Opposites of embedded style:

1. Inline style – CSS written directly in the HTML element using the style attribute.
Example: <p style="color: red;">Hello</p>

2. External style – CSS written in a separate .css file and linked to the HTML using a
<link> tag.
Example in HTML: <link rel="stylesheet" href="[Link]">
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8" />

<title>Font Family Example</title>

<!-- Embedded style sheet using <style> tag -->

<style type="text/css">

*{

font-family: "Gill Sans Bold SmallCaps & OSF", sans-serif;

</style>

</head>

<body>

<h1>This is a heading</h1>

<p>This is a paragraph.</p>

<div>This is a <strong>div</strong> element with styled text.</div>

</body>

</html>

3.4. Assume that the author, user, and user agent style sheets for an HTML document
are as follows: Author: div { color:blue } p { color:green; font-size:smaller !
important } .hmm { color:fuchsia } User: p { color:white; background-color:black; font-
size:larger !important } body { color:yellow } User agent: body { color:black } Assume
that these are the only style rules for the document (i.e., no style attributes appear). (a)
What specified value will the browser use for the color property of p elements? For the
background-color property of p elements? For the font-size property? Do any of your
answers change if the p element belongs to the hmm class? Justify your answers. (b)
What specified value will the browser use for the color property of div elements? Does
your answer change if the div element belongs to the hmm class? Does the value depend
on which element type contains the div? Justify your answers. (c) What color value will
be given to a ol element that is a child of the body element, assuming that neither the ol
element nor the body element belongs to the hmm class? Does your answer change if
the body element (not the ol element) belongs to the hmm class? Justify your answers.
(d) Assume now that the user agent rule is changed to * { color:black } and answer the
previous question.
Let's go through each part of Exercise 3.4 step by step and apply the CSS cascade rules
properly, considering:

● Cascade origin and importance

● Specificity

● Inheritance

🧠 Reminder: Cascade Priority Order

Priority Level Origin Importance

1 (lowest) User normal


agent

2 User normal

3 Author normal

4 Author !
important

5 (highest) User !
important

🔹Given CSS Rules:


🟦 Author Style Sheet

div { color: blue; }

p {

color: green;
font-size: smaller !important;

.hmm { color: fuchsia; }

🟩 User Style Sheet

p {

color: white;

background-color: black;

font-size: larger !important;

body { color: yellow; }

🟨 User Agent (default browser styles)

body { color: black; }

✅ (a) Style resolution for <p> elements:


We’ll check:

● color

● background-color

● font-size

➤ 1. color of <p>
Competing Rules:

● Author: color: green;


● User: color: white;
(Both normal declarations, no !important)

✅ Winner: User Rule → color: white

Reason: In the cascade, user normal styles override author styles unless the
author rule is marked !important.

➤ 2. background-color of <p>
Only One Rule:

● User: background-color: black;


(No other background rules.)

✅ Result: background-color: black

➤ 3. font-size of <p>

Competing !important Rules:

● Author: font-size: smaller !important

● User: font-size: larger !important

✅ Winner: User Rule → font-size: larger

Because user !important > author !important

➤ Does this change if <p class="hmm">?

.hmm rule from the author is:

.hmm { color: fuchsia; }

This has higher specificity than the p selector, but it’s from the author and not marked !
important.
✅ Still overridden by user rule for p { color: white; } → so color remains white.

✅ Final result for <p> and <p class="hmm">:

Property Value Reason

color white user rule wins

background- black user rule


color

font-size larger user !important


wins

✅ No change even if p belongs to the hmm class.

✅ (b) Style resolution for <div> elements:


Rule:

● Author: div { color: blue; }

🟨 No user rule or user agent rule sets color for div.

✅ So <div> gets color: blue

➤ What if <div class="hmm">?

● .hmm { color: fuchsia; } (author)

● Both div and .hmm are author rules, so specificity decides.

✅ .hmm has higher specificity than div → color: fuchsia wins.


➤ Does the parent element (e.g., inside <p> or <body>) affect the
div?
Not unless color is inherited and no rule sets it directly.

But here, we have a direct rule for div, so:


✅ The parent doesn't affect the computed color.

✅ Final answer for <div>:

Element color

<div> blue

<div fuchsia
class="hmm">

Parent element No effect (direct rule wins)


type?

✅ (c) Color for <ol> inside <body>


Assume:

<body>

<ol>Item</ol>

</body>

And ol has no style rules defined.

➤ What can be inherited?

● color is inherited.

● background-color is NOT inherited (but not asked here).


Body has these competing color rules:

Rule Value Importance


Source

Author none —

User yellow normal

User Agent black normal

✅ User rule wins → color: yellow on <body> → inherited by <ol>

➤ If <body class="hmm">?

Now .hmm { color: fuchsia; } applies.

But .hmm is from the author, color: fuchsia, and has no !important.

Still overridden by user's body { color: yellow }

✅ So color still: yellow

✅ Final answer for <ol> inside <body>:

Situation color

<ol> inside yellow


<body>

<body yellow
class="hmm">

Why? User rule wins over author


✅ (d) What if user agent rule is changed to:
* { color: black; }

This means every element gets a default color: black unless overridden.

➤ Re-evaluate (c):
Still:

● User rule: body { color: yellow; }

● Author rule: none

● UA rule: * { color: black; }

✅ The user rule still overrides the UA rule.

So:

● <body> → color: yellow

● <ol> → inherits yellow

✅ Answer remains the same: color: yellow

3.5. (a) Write a style rule to create a class named quote. This rule
should set the top and bottom margins to 0 and the left and right
margins to 4em. The rule should contain a single (shortcut)
declaration. (b) Explain why em might be a better length unit to use
for the task of indenting quoted text than px or one of the absolute
length units.

✅ 3.5 (a) — CSS Class Rule with a Shortcut Declaration

To create a class named .quote with:

● Top & Bottom margin = 0

● Left & Right margin = 4em

● Using a single shorthand declaration, we write:

.quote {
margin: 0 4em;

✅ Explanation of the Shorthand:

● margin: [top-bottom] [left-right];

● So margin: 0 4em; sets:

○ margin-top and margin-bottom = 0

○ margin-left and margin-right = 4em

✅ 3.5 (b) — Why em is better than px or absolute units for


indents

Using em for indentation (like margins or padding) is better than


using px or other absolute units like cm, mm, or in because:

🟩 1. Scales with Font Size

● 1em = the current font size of the element.

● If the user increases text size (for accessibility), the indent


also increases proportionally.

🟨 2. Better Accessibility

● Users with vision impairments often increase font size.

● Using em keeps layout and indentation consistent with the text


size — avoiding overlap or layout issues.

🟦 3. Responsive Design Friendly

● em adapts to different screen resolutions and zoom levels better


than fixed units like px.

❌ Why px or absolute units are worse:


● px is fixed and doesn't scale with text size.

● Absolute units (cm, in, pt) are designed for print, not screens.

● They don’t respect user preferences or system scaling.

✅ 3.5 (a) — CSS Class Rule with a Shortcut Declaration

To create a class named .quote with:

● Top & Bottom margin = 0

● Left & Right margin = 4em

● Using a single shorthand declaration, we write:

.quote {

margin: 0 4em;

✅ Explanation of the Shorthand:

● margin: [top-bottom] [left-right];

● So margin: 0 4em; sets:

○ margin-top and margin-bottom = 0

○ margin-left and margin-right = 4em

✅ 3.5 (b) — Why em is better than px or absolute units for


indents

Using em for indentation (like margins or padding) is better than


using px or other absolute units like cm, mm, or in because:

🟩 1. Scales with Font Size

● 1em = the current font size of the element.


● If the user increases text size (for accessibility), the indent
also increases proportionally.

🟨 2. Better Accessibility

● Users with vision impairments often increase font size.

● Using em keeps layout and indentation consistent with the text


size — avoiding overlap or layout issues.

🟦 3. Responsive Design Friendly

● em adapts to different screen resolutions and zoom levels better


than fixed units like px.

❌ Why px or absolute units are worse:

● px is fixed and doesn't scale with text size.

● Absolute units (cm, in, pt) are designed for print, not screens.

● They don’t respect user preferences or system scaling.

✅ Conclusion:

em is a relative unit that keeps quoted text indentation


consistent with the font size, improving readability,
flexibility, and accessibility, especially across devices and
user settings.

3.6. Based on the textbook description of a typical browser’s


implementation of the CSS px (pixel) length measure, quantify how a
1px length changes if a monitor’s resolution is changed from 1024 by
768 to 1280 by 1024.

✅ Exercise 3.6 — How Does 1px Change with Screen Resolution?

To answer this question, we need to understand how the CSS px (pixel)


unit behaves logically versus physically in a browser.
🔹 Step 1: Understand CSS px vs. Device Pixels

● CSS px is a logical pixel, not always equal to a device


(hardware) pixel.

● Modern browsers use a concept called CSS pixel reference that is


device-independent.

● They often rely on the device pixel ratio (DPR) to map CSS pixels
to real screen pixels.

🔹 Step 2: Assume Conditions (as in early browser models)

If we follow the older, simplified textbook model (like pre-high-DPI


era), the browser maps:

● 1 CSS px ≈ 1 physical screen pixel, assuming 96 DPI.

So, let’s proceed under this simple mapping:

1 CSS px = 1 screen pixel

🔹 Step 3: Compare Two Resolutions

Resolutio Width × Total Pixel Density (assuming same


n Height Pixels screen size)

1024 × 786,432 Lower


768 pixels density

1280 × 1,310,720 Higher


1024 pixels density

Let’s assume the monitor size remains the same (e.g., 15-inch
display).
Then:
● Pixels become smaller at higher resolution, since more pixels are
packed into the same space.

🔹 So, what happens to 1px?

● On 1024×768: 1px is physically larger

● On 1280×1024: 1px is physically smaller (because screen pixels


are denser)

✅ Final Answer:

When the resolution changes from 1024×768 to 1280×1024 on a


monitor of the same size, 1 CSS pixel becomes approximately
28% smaller in physical size, assuming 1 CSS px = 1 hardware
pixel.

✅ What is DPI?
DPI stands for Dots Per Inch (sometimes also called PPI, Pixels Per Inch).

It measures how many pixels fit in a physical inch of the display.


● A higher DPI means more pixels per inch → sharper, smaller pixels.

● A lower DPI means fewer pixels per inch → larger, blockier pixels.

3.7. Picture “framing.” (a) Write a style rule that will place a nice “frame” around img
elements. The “frame” should be brown. The inside edges of the “frame” should touch
the outside edges of the image. There should be 10-px distance between adjacent images
(either horizontally or vertically). See the left image in Figure 3.44. (b) Modify your style
rule to “mat” your images. In particular, there should now be a 3-px gap between the
outside edges of your images and the inside edges of the “frames.” This gap should be a
tan color. See the right image in Figure 3.44.

3.7 — Picture “Framing” and “Matting” with CSS


Let’s tackle each part of the problem step by step:

🔹 (a) CSS Rule for Framing img Elements


We need:

● A brown frame around each image

● The frame touches the edges of the image (no space between image and border)

● 10px space between images

✅ CSS:

img {
border: 5px solid brown; /* Frame */

margin: 10px; /* Space between images */

display: inline-block; /* So margin applies horizontally too */

💡 Explanation:

● border: 5px solid brown adds a brown frame.

● margin: 10px gives 10px space between images.


● display: inline-block ensures images behave like inline items with spacing.

🔹 (b) Matting the Image (Adding Tan Gap Inside Frame)


We now need:

● A 3px tan gap (mat) between the image and the frame

● This matting is done using padding (space inside the border)

● The frame remains brown

● The mat color is tan

✅ CSS (Improved for Matting):

img {

border: 5px solid brown; /* Brown frame */

padding: 3px; /* Tan matting space */

background-color: tan; /* Mat color */

margin: 10px; /* Space between images */

display: inline-block; /* Ensures consistent spacing/layout */

💡 Explanation:

● padding: 3px creates space between the image and the border.

● background-color: tan fills that space with a tan "mat".

● border still acts as the frame.

3.8. Figure 3.22 showsaclient area wider than the canvas. Explain howsuchasituation could
occur in an HTML document

✅ 3.8 — Why Can the Client Area Be Wider Than the Canvas in
an HTML Document?
First, Definitions:
● Client Area: The viewport of the browser — the visible part of the browser window
where the page is displayed (excluding toolbars, borders, etc.).

● Canvas: The area used by the HTML document content — how wide the actual web
page layout is rendered.

🔍 So how can the client area be wider than the canvas?


This happens when the webpage content is narrower than the browser window.

✅ Example Scenario:
Let’s say your screen is 1200px wide, but your web page content is only 800px wide.

<style>

body {

width: 800px;

margin: 0 auto;

</style>

● The body is centered and only 800px wide.

● The browser window (client area) may be 1200px or more wide.

● So there's empty space on both sides of the canvas (e.g., 200px on each side).

● This creates a situation where:

Client area > Canvas width


✅ Another Example: Using a <canvas> Element

If you're using the actual <canvas> HTML element:

<canvas width="600" height="400"></canvas>

And your browser window is 1000px wide, then:

● The canvas only takes 600px horizontally.

● The client area (browser window) is still 1000px.

● Again, canvas is narrower than client area.

✅ Summary: Why This Happens


The client area can be wider than the canvas if:

1. The webpage content (or <canvas>) is given a fixed or smaller width.

2. The browser window is resized to be much larger.

3. Centered or constrained layouts (common in responsive design) are used.

📌 This is a normal and often intentional layout behavior in modern web design,
especially for centering or maximizing readability.

3.9. The em and ex units are both related to the height of characters; there is no
unit related to character width. Give a rationale for this difference.

✅ 3.9 — Why Are There CSS Units Based on Character Height


(em, ex) But Not Width?

🔹 First, What Are em and ex?

● em: Relative to the font size (typically the height of the letter "M").

○ 1em = current font size

● ex: Relative to the x-height (height of lowercase "x" in the font)


○ 1ex ≈ half of 1em in most fonts

These units are based on vertical measurements — i.e., character height.

❓ But Why No Unit for Character Width?


Because character width is highly inconsistent across different fonts and characters.

✅ Rationale: Why Height-Based Units Exist but


Not Width-Based
🔸 1. Character Height Is More Consistent Across Fonts
● All fonts define a standard vertical size (font size, x-height, etc.).

● This is a stable reference for line spacing, layout, and readability.

📏 Every font has a clearly defined font height and x-height — reliable for layout
measurements.

🔸 2. Character Width Is Variable in Most Fonts


● Most fonts are proportional fonts:

○ "i" is narrow, "W" is wide

● So there’s no single fixed width for all characters.

❌ If you tried to define 1cw (character width), it would vary depending on the
character and font, making it unreliable for layout.
FILL IN THE BLANKS:
FILL IN THE BLANKS:
Week1:

b) Fill-in-the-blank Activity
This activity asks you to choose correct terms to complete the explanation:

css
Copy code
(HTML, DOM) represents initial page content/state,
and the (HTML, DOM) represents current page content.
When (HTML, JavaScript, DOM) adds, removes, or edits nodes,
the (HTML, DOM, JS) becomes different than the (HTML, DOM, JS).

✅ Correct Filled Version:

HTML represents initial page content/state, and the DOM represents current page
content.
When JavaScript adds, removes, or edits nodes, the DOM becomes different than
the HTML.

Week 3

Section 1: Understanding HTML Structure


This part of the image is talking about the structure of a simple webpage that has a counter
button. The question asks:

(i) __??__ : Displays the heading at the top.

● The answer is <h1>.

● Why? In HTML, the <h1> tag is used for the main heading. In the image, "Hello
Counter" is wrapped inside an <h1> element and styled to be at the top using CSS.

✅ So, (i) <h1>

(ii) A __??__ containing __??__ element is used to group and structure the button
independently.

● The first blank refers to <div>.


○ Why? A <div> is a container element in HTML, used to group together HTML
elements for layout and styling purposes. In the image, the button is placed
inside a <div class="container">.

● The second blank is <button>.

○ Why? That’s the interactive element inside the <div> that users can click on to
increment the counter.

✅ So, (ii) A <div> containing <button> element.

The variables defined under the :root selector are __??__ (local/global).

● The answer is global.

--button-text-color would be a local variable, available only within the button


selector and its descendants.

"Just like [Link] the [Link] protocol is also a scheme in the broader URI
structure."

"Just as HTTP URLs point to resources on the internet, file URLs point to resources on
the local file system."

(i) Same-Origin Policy:

“The default security policy enforced by browsers is called the Same-Origin Policy,
which blocks cross-origin requests between different origins.”

● 🔹 Blank = cross-origin

● This means if a website on [Link] tries to fetch data from [Link], the
browser blocks it unless allowed.

(ii) What is CORS?

“CORS stands for Cross-Origin Resource Sharing, a mechanism that allows or


restricts resource sharing between different domains.”

● 🔹 Blank = resource sharing

● CORS lets servers safely share resources (like APIs, images, etc.) with clients hosted on
different domains.

(iii) Error Example:


“Access to fetch at '[Link] from origin '[Link]
has been blocked by CORS policy”.

“This indicates that the backend server does not include the appropriate CORS
headers in its response.”

● 🔹 Blank = CORS headers

● This error tells you that the API server hasn’t set the correct headers to allow your
request from a different origin

(i) Then Access the app at:

This blank expects the URL where your server is running.

● 🔹 Blank = [Link]

● When you start a local server, your browser accesses it using a localhost address with
the server's port.

(ii) [Link] is a:

“[Link] is a local development server where your app is served (via


a server running on port 8080).”

● 🔹 Blank = local development server

🔹 React (aka [Link] or ReactJS) is an:

Open-source front-end JavaScript library used for building composable user interfaces,
especially for single-page applications (SPA).

✅ Blank 1 (used for building composable user interfaces, especially for →


single-page applications).

🔹 It is used for handling the view layer in web and mobile apps, based on components in
a:

Declarative manner.

✅ Blank 2 (components in a → declarative manner).

React was created by Jordan Walke, a Facebook software engineer. React was:

● First deployed on a Facebook news feed in 2011.

● Then later used on Instagram in 2012


🔴 VIRTUAL DOM COLUMN
Statement Explanation

It is a virtual copy of the ➤ It's not the real DOM, just a lightweight JS
original DOM version used to compare changes.

It is maintained by JavaScript ➤ React (or similar libs) manages this in memory


libraries using JavaScript.

After manipulation, it only re- ➤ React compares the old and new Virtual DOM
renders changed components (called diffing) and only updates parts that
changed.
Updates are lightweight ➤ Because only the changed parts are updated,
it's fast and efficient.

Performance is high and UX is ➤ Smooth and fast updates improve user


optimized experience.

Highly efficient as it performs ➤ Diffing finds differences between Virtual DOM


diffing algorithm versions and updates the minimal amount of
real DOM nodes.

🟡 REAL DOM COLUMN


Statement Explanation

It is a real representation of HTML ➤ The actual structure your browser


elements renders on the page.

It is maintained by the browser after ➤ Browser builds it as it reads HTML.


parsing HTML elements

After manipulation, it re-renders the ➤ Any change might cause full DOM
entire UI refresh — which is slower.

Updates are heavyweight ➤ Because they involve re-rendering and


recalculating layout, style, etc.

Performance is low and the UX quality ➤ Slower page updates can lead to laggy
is low interactions.

Less efficient due to re-rendering of ➤ Even small changes might trigger full
DOM after each update reflows or repaints.

Final Props Column (after filling):


Props (short for "properties") are passed to a component by its parent component
and are immutable meaning that they cannot be modified by the own component
itself.
Props act as an argument for a function. Also, props can be used to customize
the behavior of a component and to transfer data between components.
The components become reusable with the usage of props.

✅ Final State Column (after filling):


The state entity is managed by the component itself and can be modified using
the setter (setState() for class components) function.
Unlike props, state can be modified by the component and is used to manage the
internal state of the component.
i.e. state acts as a component’s memory.
Moreover, changes in the state trigger a re-render of the component.
The components become dynamic with the usage of state alone.

Week 4
✅ Filled Blanks & Key Points:

● V8 is Google’s JavaScript engine (used in Chrome and other browsers).

● SpiderMonkey is Mozilla’s engine and used in Firefox.

● Chakra is Microsoft’s runtime engine. It was originally used in Internet Explorer/Edge.

● In December 2018, Microsoft decided to adopt Chromium (Google’s open-source


browser project).

● JS runtimes are also used in server-side development, mobile apps, IoT.

● Most importantly for us: the [Link] platform is built on top of V8.

Slide 2: JS Engines - Interpret or Compile?


✅ Filled Blanks & Key Points:

● Today’s JavaScript engines both interpret and compile by employing so-called just-in-
time (JIT) compilation.

● JavaScript code that is run repeatedly such as often-called functions is eventually


compiled and no longer interpreted.
Slide 3: What TypeScript Offers
✅ Filled Blanks & Key Points:

● Three of the most well-known languages are TypeScript, CoffeeScript, and Dart.
● JavaScript is a dynamically typed language.

● TypeScript allows you to do that by enabling static (static/dynamic) type checking.

Full sentence filled:

Scoping is the context in which values and expressions are "visible or


accessible".
In contrast to other languages, JavaScript has very few scopes:
A global scope, function scope, and block scope.
A block is used to group a number of statements together with a pair of curly
braces {}.

The difference between let and const is that const does not allow the
reassignment or redeclaration of a variable. The originally assigned element though
can change.

In the code above, var i has function scope, but we actually need it to be of block scope
such that every function has its own separate copy of it.

Printing 11 instead of 1 to 10. Waiting for none between print outs one by one.

STACK:
A stack is a data structure that JavaScript uses to store static data.
Static data is data where the engine knows the size at compile time.
In JavaScript, this includes primitive values (strings, numbers, booleans,
undefined, and null) and references, which point to objects and functions.

HEAP:
The heap is a different space for storing data where JavaScript stores objects and functions.

Unlike the stack, the engine doesn't allocate a fixed amount of memory for these objects.
Instead, more space will be allocated as needed.

All variables first point to the stack. In case it's a non-primitive value, the stack
contains a reference to the object in the heap." The memory of the heap is not
ordered in any particular way, which is why we need to keep a reference to it in the
stack. You can think of references as addresses and the objects in the heap as
houses that these addresses belong to.

Week 5

What is [Link]?
[Link] is an open-source, cross-platform JavaScript runtime environment that allows
developers to execute JavaScript code on the server side. It was released in 2009 by Ryan
Dahl and is built on the Chrome V8 JavaScript engine. [Link] enables the development of
scalable and efficient network applications by allowing JavaScript to run outside of a web
browser.

The function inside a class after ES6 allows multiple instances to share the same method,
improving memory efficiency.

"This proves that Game(n) is just a regular method, your object instances never call it
automatically."

Fill in the Blanks on the Right:

Sentence Correct Fill

Class is just a _________ function

printName() is a _________ prototype


method method

💥 FINAL LINE:
✅ String is primitive, but when you use methods on it, JavaScript treats it like an
object temporarily.

Here’s the filled-in version:

1. Before ES6 (2015), developers had to explicitly use prototypes to share methods.

2. ES6 class introduced a more readable way to define classes, making prototype less visible.

3. But internally, JavaScript still uses prototypes and ES6 class update just hides the prototype.

4. Understanding prototypes helps you debug and optimize JS code better.

5. Prototypes allow method sharing & memory efficiency. Without prototypes, every object would
have its own copy of methods, leading to huge memory waste.
6.

The three main pillars around which JavaScript (JS) is organized are:

Event-driven, Functional, and Object-oriented

✅ Filled Blanks:
● printName is not shared (each object has its own copy)

● Every time new Game(...) is called, a new function is created in memory.

● Instead of creating a new function for every instance,

● we can store it once in the prototype,

● and let all instances access the same function.

WEEK 6

"Back-end will connect to a database, get some results, and do some processing."

"Back-end will expose REST API that the front-end will use to interact with the DB."

✏️Fill-in:

"Backend server will accept HTTP requests from frontend app and use CRUD operations
to interact with the DB."

✏️Fill-in:

"Express is a minimal and flexible web application framework for [Link]. It is designed for
building web applications and APIs."

REST stands for Representational State Transfer.

It is an architectural style for designing networked applications that relies on stateless communication
and standard HTTP methods like GET, POST, PUT, DELETE, PATCH, etc.

RESTful APIs follow a set of principles that make applications scalable, flexible, and easy to use.

The concept of a RESTful API is an architectural style — it's a set of design principles and constraints
for how web applications/services should be built — while Express is just one of many tools
(frameworks) you can use to implement that design. In other words, RESTful API design is independent
of the technology used to build the server. You can build a RESTful API using Express, Django, Flask, or
any other framework; the key is that you follow REST principles such as statelessness, a uniform
interface, and proper use of HTTP methods and codes. Express doesn’t force you to build a RESTful API
—it merely provides a environment to implement RESTful design if you choose to do so.

RESTful APIs are web services in their purest form, meaning the service exposes an interface (usually
via HTTP and data formats like JSON) for other software to consume.

Web applications can—and often do—use RESTful APIs as the communication layer between the client
and the server.

This separation aligns with the client-server architecture, ensuring clarity and maintainability in your
project’s design.

All web applications have a server side (which behaves like a web service),

but not every web service is a complete web application.

✓ Name few real-world examples where you have a web service that isn’t a full web
application — meaning it exposes functionality via APIs without providing a complete user
interface (UI).

JSON is not an inherent requirement of the web service model.


Payment gateways, weather APIs, geocoding APIs, and cloud storage APIs are considered web
services
because they make HTTP requests to their API endpoints for data exchange without a built-in user
interface (UI).
They often use JSON because it’s popular today, but JSON is not an inherent requirement of the web
service model.

Payment gateways, weather APIs, geocoding APIs, and cloud storage APIs are considered web services
because they make HTTP requests to their API endpoints for data exchange without a built-in UI. They
often use JSON because it’s popular today, but JSON is not an inherent requirement of the web service
model.

Endpoints are Fundamental: Every web API exposes endpoints (specific URLs) that represent resources
or services.

Clients make requests (using methods like GET, POST, etc.) to these endpoints, and the server
responds with data (commonly in JSON, XML, etc.).

In many cases, an API is a service without a user [Link], the term “API” can also refer to
function libraries or SDKs that expose a set of function calls.

These aren’t necessarily part of a networked client-server architecture but are still considered APIs
because they define how different software components interact.

When discussing the server side alone, the focus is on REST principles — defining resources, routes,
HTTP methods, and ensuring stateless interactions.

Later, when you integrate the front-end, you’ll see how the REST API serves as the communication
bridge between the server and the React application.

This separation lets you build and test the backend independently before connecting it with the client side.
The base URL is a key component in our RESTful API design. It ensures that both the front-end and
back-end consistently generate and interpret URLs. For instance, our modern front-end (built with
frameworks like React or Angular) will use this base URL to construct API requests, while our Express
server uses it to define its routing logic. This uniformity is crucial for seamless communication between
client and server.

In our project, the base URL (stored in configuration/env files) is a fixed office address for our server.
The RESTful API then provides the “rooms” or endpoints inside that building, which the front-end (like a
React app) uses to retrieve data. This clear separation ensures that even as you build and deploy your
server-side logic in a RESTful style, both components—front-end and back-end—consistently know
where to send requests and how to interpret URLs.

Filled Blanks;-P
A model represents the data for the application.
The view is the visual representation of that data.
A controller takes user input on the view and translates that to changes in the
model.

In a traditional backend MVC setup, the View (V) is responsible for


rendering UI using templating engines like EJS (Embedded JavaScript) , Pug, or Handlebars.

✓ But when using React for the frontend, React itself handles UI rendering.

✓ The backend now only provides data via APIs (JSON responses) instead of rendering
HTML.

✓ In a React + Express setup, the backend only serves data (Model + Controller),
while React takes over the View layer.

[Link]("/api/projects", --------------------- )

is B. Callback function ✅

Why? → Because it is executed only when an HTTP request is received.

✅ First part:

The Arrow Functions in JavaScript helps us to create anonymous functions


or methods i.e. functions without names
As they do not have any names, the arrow makes the syntax concise.
✅ Second part:

1. ()=>{} are a concise way of writing anonymous, lexically scoped


functions in ES6.

✅ Third part:

2. The ()=>{} can contain other ()=>{} or also normal functions.

✅ Fourth part:

3. The ()=>{} accomplishes the same result as a regular function with fewer
lines of code.

✅ Fifth part:

4. The ()=>{} automatically binds this object to the surrounding code’s


context.

✅ Sixth part:

5. The value of this keyword inside the ()=>{} is not dependent on how they
are called or how they are defined.
It depends only on its enclosing context.

✅ Seventh part:

6. If the ()=>{} is used as an inner function,


this refers to the parent scope in which it is defined.

The primary use of arrow functions in the frontend is to attach functionality to UI interactions,
such as click events, form submissions, and hover actions.

This is the callback function (also called a request handler) that gets executed when a GET
request, such as a frontend app making a request to [Link] "/api/projects", hits the
API.

The error "Cannot GET /" happens because your server does not define a route for the "/"
path.
A React component is a function that returns a piece of UI (User Interface),
which can be as straightforward as a fragment of HTML.
Consider the creation of a component that renders a navigation bar.
Recall what is a React Component?
The mixture of JavaScript with HTML tags might seem strange (it's called JSX,
a syntax extension to JavaScript. For those using TypeScript,
a similar syntax called TSX is used). To make this code functional, a compiler is required to
translate the JSX into valid JavaScript code.

Filling in the blanks (with explanation):

First section: (related to Props)


✅ Blank 1:
"Props are basically data that flows from one to another component as parameters."
👉 Why?
Because props carry data from parent to child — props are like variables filled with data.

✅ Blank 2:
"Props are passed to components via attributes."
👉 Why?
When you use a component inside JSX, you pass props like attributes:

jsx

Copy code

<UserProfile name="John" />

Here, name="John" is an attribute.

Second section: (related to State)


✅ Blank 3:
"React components have a built-in state object which is private to a component."
👉 Why?
State is private because it belongs to the component itself and cannot be changed from
outside unless you send it explicitly.
revision stuff
WEEK 1:
🧠 Main Idea:
This diagram explains how a website (like [Link]) is requested from your
computer and how it reaches the destination server and comes back with a response (like the
Google homepage).

1. Client ([Link])

You (the user) type [Link] in your browser. That makes your computer the client
— the one asking for something.

🌐 2. Browser
Your browser (like Chrome or Firefox) takes what you typed and prepares a request. It wraps
your request in a special format called HTTP.

📤 3. GET Request (HTTP/1.1)


This is the actual request message that goes out.
Example:

GET / HTTP/1.1

Host: [Link]

It means: "Hey Google server, give me the homepage!"

🔁 4. Binary/Radio Waves
This message is converted into binary (0s and 1s). If you're using WiFi, it becomes radio
waves to travel wirelessly.

📡 5. Router/Ethernet
This is your WiFi router or wired internet connection. It knows where you are and sends your
request to the next closest internet router.
🔁 6. Next Nearest Router
This is part of the internet backbone — a chain of routers that passes your request forward
until it reaches the server.

📍 7. Destination Address (IP)


This is the server (Google’s computer) that receives your request. It reads your GET request
and sends back a response (like Google’s homepage HTML).

📥 8. Response Comes Back


The server’s response travels back through the same routers, back to your router, then to
your browser.

📲 9. Client Sees the Website


Finally, your browser displays the webpage using the response from the server.

🔷 1. DOM (Document Object Model)


● It’s the HTML structure shown as a tree of elements.

● Each element (like html, body, p, div, etc.) is a node.

● Parent-child relationship means:

○ body is the parent of p, div, img.

○ p is the parent of span.

○ span is the parent of the text web performance.

🧠 Think of it like a family tree — big elements contain smaller elements.

🎨 2. CSSOM (CSS Object Model)


● This is where CSS rules (like font-size, color, etc.) are matched with the HTML
elements.

● Each element gets its style from CSS.

○ For example:

■ p has font-size: 16px, font-weight: bold

■ span has display: none (it will be hidden)

🌲 3. Render Tree
● The browser combines DOM + CSSOM to build a Render Tree.

● This tree shows only the visible elements with their computed styles.

● Elements like the span with display: none are excluded.

📌 Example:

● Only Hello and students appear inside p, because span was hidden.

🔹 HTML Tags vs Elements


✅ Element
An HTML Element is the full structure — from start tag to end tag, including the content
inside.
Example:

html
CopyEdit
<p>Some text</p>

This whole line is called an element.

✅ Tag
Tags are the opening and closing parts of an element.
In the example above:

● <p> is the opening tag

● </p> is the closing tag

So:

● <p> + </p> = tags

● <p>Some text</p> = element

📘 Common Tags in <head> Section


Tag Description

<title> Shows title on browser tab

<meta> Stores metadata (info about the page)

<link> Connects to CSS stylesheet

<script> Adds external JavaScript

<!-- comment Adds comments in code (not visible on the


--> page)
🔄 How It Works (Flow):
1. The client (browser) sends a request via the internet to the server.

2. The API on the server receives the request and communicates with:

○ Logic for processing.

○ Database for data.

○ Media Cache for media content.

3. The API sends back a JSON response.

4. The Front End interprets that data and displays it on the browser.

What is the DOM?


DOM stands for Document Object Model.

● It's a programming interface that represents a web page as a tree of objects.

● Each HTML element (like <h1>, <a>, <body>) becomes a node in this tree.

● This model is built by the web browser when it reads an HTML document.

🔍 Left Side Explanation


● ✅ Model of the web page:
Your browser reads the HTML and creates a model (structure) that includes all
elements (tags, text, etc.).

● ✅ Objects and properties:


All page content becomes objects that can have:

○ Properties (like .innerText)

○ Methods (like .appendChild())

○ Events (like .onclick)

● ✅ Scripting access:
JavaScript or other scripting languages can be used to interact with these objects.
💡 Right Side Explanation
● 🧠 Every item becomes an object:
Each tag (like <h1>, <a>) becomes a manipulatable DOM object.

● 🎨 You can control:

○ Color

○ Transparency

○ Position

○ Sound

○ Behavior (like click actions)

🔗 Every HTML tag is a DOM object


For example:

html
Copy code
<a href="[Link]">Click me</a>
turns into:

js
Copy code
[Link]('a').href // '[Link]'

🌲 Diagram in the Middle


This shows the DOM tree structure:

mathematica
Copy code
Document
└── Root element: <html>
├── <head>
│ └── <title> → Text: "My title"
└── <body>
├── <h1> → Text: "A heading"
└── <a href="..."> → Text: "Link text"

This tree allows scripts to navigate, edit, or add/remove any node.

Telnet (Teletype Network)


🔎 What is it?
Telnet is used to remotely log in to another computer over a network and execute
commands as if you're sitting in front of it.

HTTP (HyperText Transfer Protocol)


🔎 What is it?
It’s the language browsers and websites use to talk to each other. It helps you request and
receive webpages.
🆚 Difference Summary (Easy Words)
Feature HTTP Telnet

Purpos View websites Control another computer


e remotely

Interfac Browser (Graphical) Command-line (Text-based)


e

Exampl Requesting a web page Logging into a server and


e typing commands
Action

Securit Not encrypted (use Not secure at all


y HTTPS for secure)

Real- Surfing the web Remote control of network


Life devices
Use

🎯 Real-Life Analogy:
● HTTP is like ordering food from a restaurant using a menu and a waiter.

● Telnet is like walking into the kitchen and cooking your own food there

🧱 Slide 1: Architecture of Static Website


📌 What's a Static Website?
A static website serves fixed content to users. The same HTML file is sent to everyone who
visits the site. There's no server-side logic or processing involved — everything is already
prepared and stored on the server.
✅ Step-by-Step Breakdown (Diagram 1)
🔴 Step 1 – Web browser requests a static page

● This happens when you type a website URL (like [Link]) in your browser and
press Enter.

● The browser sends an HTTP request to the server where that site is hosted.

🔴 Step 2 – Web Server finds the requested page

● The server simply checks its file system (just like opening a folder on your PC) and finds
the requested file (e.g., [Link]).

🔴 Step 3 – Web Server sends the page back

● The server responds with the exact HTML file to the browser.

● The browser then renders (displays) that page on your screen.

📝 Important Note:
"Static does not mean that it will not respond to user actions."

✅ This is a very common misconception!

● A static site can still use CSS for styling and JavaScript for user interaction (like
clicking buttons or animations).

● However, it cannot change content dynamically based on user input or database data,
because there's no server-side processing involved.

⚙️Slide 2: Architecture of Dynamic Website


📌 What's a Dynamic Website?
A dynamic website can generate different content for different users or at different times. It
uses server-side technologies to build pages on the fly, often using databases to store and
retrieve information.
✅ Key Components (Diagram 2)
1. Client / Web Browser

● This is the user’s device, running a web browser (like Chrome, Firefox, etc.).

● It sends requests to the server and displays the response.

● Also known as the “frontend.”

🖧 2. Web Server

● This receives requests from the browser.

● Unlike a static site, it doesn’t just return a pre-made file — it often needs to construct
the page by combining HTML with real-time data.

● May use languages like PHP, Python (Django/Flask), [Link], or others.

3. Database Server

● Stores data like user accounts, product listings, blog posts, etc.

● When the web server needs data, it queries the database and fetches what it needs.

● Popular databases: MySQL, MongoDB, PostgreSQL, etc.

🔁 Interaction Flow (Left to Right in Diagram):


1. The user makes a request (e.g., log in, view blog post).

2. The web server processes the request.

3. If needed, the server queries the database (e.g., “get blog post #5”).

4. The server uses that data to build a custom HTML response.

5. It sends that HTML back to the browser for display.


✅ XHTML (eXtensible HyperText Markup


Language)
🔹 What it is:
XHTML is a stricter, XML-based version of HTML.

🔹 Why stricter?
Because XHTML follows XML rules, which means the code must be perfectly written — no
exceptions.

🔹 Browser behavior:
If there’s even one small mistake, like a missing tag or wrong case, the browser may not
render the page at all.

Weeek 3:

✅ Steps with explanations:


1. User (1):
➤ Double-clicks [Link].
This action starts the process. It’s the user's intent to open the file.

2. OS (2):
➤ Identifies the file type and associates it with the browser.
The operating system knows .html files should be opened with a web browser (like
Chrome or Firefox).

3. Browser (3):
➤ Receives file path with file:// URL scheme.
The browser gets a path like [Link]

4. OS (4):
➤ Locates and reads the file.
The browser asks the OS to access the contents of the file from disk.

5. Browser (5):
➤ Processes (parses) HTML, CSS, and JS.
The browser reads the file’s contents and starts interpreting the code.

6. Browser (6):
➤ Renders the page and displays the file:// URL.
The final step — the browser draws the page visually on screen.

[Link] vs Vanilla JavaScript


Feature Vanilla JavaScript [Link]

Definition The plain, core JavaScript A JavaScript library developed by


language without any libraries or Facebook for building user interfaces,
frameworks. especially SPAs (Single Page
Applications).

DOM You manipulate the DOM React uses a Virtual DOM, which
Manipulation manually using methods like makes changes more efficient and
getElementById, faster.
querySelector, etc.
Code Procedural or functional code. Component-based architecture —
Structure Managing large UIs can become reusable, isolated pieces of UI
messy. (components).

Reusability Limited; repetitive code is High reusability through components.


common.

State You manage state manually (e.g., Built-in useState, useReducer, and
Management updating values in memory or other hooks make state management
DOM). easier.
UI Updates You have to manually re-render React automatically re-renders
parts of the UI on data changes. components when state or props
change.

Scalability Gets complicated as your app Scales well with features like React
grows. Router, Redux, etc.

Learning Easier to start with. Slightly steeper learning curve due to


Curve JSX, components, hooks, etc.
✅ Why is React Preferred?
Here’s why React is a go-to choice for many developers:

1. 🔁 Reusable Components
You can build UI elements like buttons, cards, forms as reusable pieces — write once, use
anywhere.

2. ⚡ Performance Boost with Virtual DOM


React updates the DOM efficiently using a virtual representation — much faster than updating
the real DOM directly.

3. 🔧 Developer Tools & Ecosystem


Amazing tools like React DevTools and a massive ecosystem (React Router, Redux, etc.) help
in rapid development.

4. 💚 Community Support
Backed by Facebook and loved by millions of devs worldwide — huge support, documentation,
and resources.

5. 🌍 SEO-Friendly
With server-side rendering (e.g., using [Link]), React apps can be optimized for search
engines.

6. 🔄 Unidirectional Data Flow


This makes the data flow predictable, which helps avoid bugs in large applications.

Slide 1: What is React?

🔹 React (aka [Link] or ReactJS) is an:

Open-source front-end JavaScript library used for building composable user interfaces,
especially for single-page applications (SPA).

✅ Blank 1 (used for building composable user interfaces, especially for →


single-page applications).
🔹 It is used for handling the view layer in web and mobile apps, based on components in
a:

Declarative manner.

✅ Blank 2 (components in a → declarative manner).

What Does "Declarative" Mean?


Declarative programming is when you describe what you want the UI to look like, not how to
make it happen step-by-step.

🔁 Opposite: Imperative
In imperative programming, you give exact instructions — like a recipe — for how to do
something.

🎯 Think of It Like This:


☕ Making Tea
● Imperative: Boil water → Add tea leaves → Wait → Strain tea → Pour into cup.

● Declarative: “I want a cup of tea.” (Let the system handle the steps!)

Exampele in Code
🔹 Imperative (Vanilla JavaScript):
const button = [Link]("button");
[Link] = "Click me";
[Link]("click", () => alert("Clicked!"));
[Link](button);

You are telling the browser step-by-step how to create and place a button.

🔹 Declarative (React):
function App() {
return <button onClick={() => alert("Clicked!")}>Click me</button>;
}

Here, you're just describing:


💬 “I want a button that says ‘Click me’ and shows an alert when clicked.”

React handles the how — like creating the element, attaching the event, adding it to the DOM,
etc.

🧠 Why Declarative is Better for UI?


● 🔍 Clearer Code – Easier to read and understand.

● 🔄 Less Error-Prone – You don’t manually update DOM; React does it.

● ⚙️Easier to Maintain – Especially as your app gets complex.

Ahh — that’s such a great question! Let's clear it up with a simple analogy and deeper
explanation.

You're absolutely right — you are still writing a button, so what do we mean when we say
“React is declarative — it's like saying I want a button”?

Let’s break it down step-by-step 👇

✅ Slide 2: Major Features Offered by React

Here’s a breakdown of the main features shown in the image and text on the right:

🔹 JSX Syntax

● JSX is a syntax extension for JavaScript.

● It allows you to write HTML-like code inside JavaScript.

● Makes the code more readable and expressive.

🔹 Virtual DOM
● React uses a virtual DOM for better performance.

● Instead of directly updating the real DOM (which is slow), it updates a virtual copy and
then syncs changes.

● This results in efficient rendering.

Server-side Rendering

● React can render components on the server side.

● Good for performance and Search Engine Optimization (SEO).

● Content gets delivered faster, and it's more crawlable by search engines.

What Are Class Components?


The slide explains that:

"Class components, also known as stateful components, contain state and


lifecycle methods and are written using JavaScript ES6 classes."

So what does this mean?

🔍 Key Concepts
Term Meaning

Class A component created using a JavaScript class instead of a function.


Component

Stateful It can store and manage state (data that can change over time).

Lifecycle Special methods like componentDidMount, componentDidUpdate,


Methods etc., that run at specific times in a component’s life.

ES6 Class A modern way of writing JavaScript classes (introduced in ES6).

🧱 Structure of the Slide


● The diagram shows:

○ Greeting (a class component)


○ Inherits from [Link]

○ Which provides access to:

■ state

■ render() method (used to return JSX/UI)

🧪 Example of a Class Component


Here's a simple class-based React component that displays a greeting message and a button to
change it:

jsx
Copy code
import React, { Component } from 'react';

class Greeting extends Component {


constructor() {
super(); // Required to use "this"
[Link] = {
message: 'Hello, welcome to React!'
};
}
changeMessage = () => {
[Link]({ message: 'You clicked the button!' });
}

render() {
return (
<div>
<h2>{[Link]}</h2>
<button onClick={[Link]}>Click Me</button>
</div>
);
}
}

export default Greeting;


🧠 What’s Happening Here?

● Greeting is a class component.

● It uses state to store message.

● render() outputs the UI.

● When you click the button, the state updates via [Link](), and React re-
renders the component with the new message.

✅ Why Use Class Components?


Before hooks were introduced in React 16.8, class components were the only way to:

● Use state

● Use lifecycle methods like componentDidMount

Now, function components with hooks (like useState, useEffect) are more common—but
class components are still important to learn and understand.

What does this sentence mean?


"Whenever React calls your component, it gives you a snapshot of the state
for that particular render."

This means:

1. When your component renders (or re-renders), React gives it the current state at that
exact moment in time.

2. That state (and props) will not change during the render, even if you update state
later.

3. Think of it like React is taking a photo (snapshot) of the state and giving it to the
component to work with during that render.
📸 Snapshot Analogy
Imagine you are taking a picture of your desk right now.

● You press the shutter → you capture what your desk looks like at this moment.

● Even if someone adds a cup to your desk right after you take the picture, the picture still
shows the old view — the snapshot doesn't change.

React works like that.

🧪 Code Example to Illustrate It


Let's say you write this:

import React, { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0);

const handleClick = () => {


setCount(count + 1); // uses the current snapshot value
setCount(count + 1); // still uses the same snapshot!
};

return (
<div>
<p>Count: {count}</p>
<button onClick={handleClick}>Increase</button>
</div>
);
}

❗What happens when you click the button?


You might expect the count to increase by 2... but it only increases by 1.

Why? Because:
● On that click, the value of count is 0, let’s say.

● setCount(count + 1) → becomes setCount(1)

● Then again, setCount(count + 1) → still becomes setCount(1) (because


count is still 0 in this render's snapshot)

● React batches them, sees no real change, and only updates to 1.

✅ How to Fix This with Functional Updates


If you want to update state based on the latest value, use the functional form of setState:

setCount(prev => prev + 1);


setCount(prev => prev + 1);

Now it correctly increments twice, because:

● The first call sets it to 1.

● The second call sees the updated value (1) and sets it to 2.

First, What is a "Render"?


When React renders a component:

1. It calls your component function or class render().

2. It reads the current state and props.

3. It creates the UI output (usually virtual DOM).

4. It updates the real DOM after the render is done.

💡 Now, What Does Mid-Render Mean?


“Mid-render” refers to during that exact process — while React is still executing your
component’s code to figure out what to display.
So, mid-render = the time when your component is being executed (e.g., your JSX is being
returned).

🧠 What Happens When You Call setState() Mid-Render?


Let’s look at a quick (invalid) example:

function MyComponent() {

const [count, setCount] = useState(0);

// ❌ Don't do this!

setCount(count + 1);

return <div>{count}</div>;

You’re calling setCount() during render — this means you're trying to change the state while
React is still in the middle of calculating what to show.

🔒 But React Doesn't Allow State to Change Mid-Render

React protects you by not letting the state change instantly. So even if you call setState()
during render, the actual state stays the same until React finishes the render and does a new
one.

Think of it like:
React says — “Hold on! Let me finish drawing everything first. THEN I’ll handle
your state update and do another render.”

✅ What Should You Do Instead?

Only call setState() in:


● Event handlers (like onClick)

● Effects (useEffect)

● Lifecycle methods (like componentDidMount)

Example (✅ correct way):

function MyComponent() {

const [count, setCount] = useState(0);

const handleClick = () => {

setCount(count + 1); // happens outside render, inside event

};

return <button onClick={handleClick}>Click {count}</button>;

✅ What is a Side Effect in React?


In React, a side effect is anything that affects something outside the scope of the
component — such as:

● Fetching data from an API

● Subscribing to a stream or socket

● Setting up timers (setInterval, setTimeout)

● Directly modifying the DOM

● Logging to the console

● Adding event listeners

These operations are not pure because they don’t just compute and return JSX — they interact
with the outside world.
🎯 Why Use Side Effects Carefully?
React’s rendering is declarative and predictable, but side effects are not. To keep things
predictable, React separates side effects using a special hook: useEffect().

Here is your original code rewritten to demonstrate all three lifecycle variations (mount,
update, unmount) using useEffect in React.

We’ll show:

1. useEffect() with no dependency array – runs on every render

2. useEffect([]) with empty dependency array – runs only on mount/unmount

3. useEffect([count]) with dependency array – runs on mount and when count


updates

✅ 1. No Dependency Array (runs on every


render)
jsx

CopyEdit

import React, { useEffect, useState } from 'react';

function EffectEveryRender() {

const [count, setCount] = useState(0);

useEffect(() => {

[Link] = `Clicked ${count} times`;

[Link]('✅ Effect: Runs on every render');

return () => {
[Link]('🧹 Cleanup: Before next render or unmount');

};

});

return (

<button onClick={() => setCount(count + 1)}>

Clicked {count} times

</button>

);

✅ 2. Empty Dependency Array [] (runs only once on


mount, cleanup on unmount)
jsx

CopyEdit

import React, { useEffect, useState } from 'react';

function EffectOnMountOnly() {

const [count, setCount] = useState(0);

useEffect(() => {

[Link] = 'Component Mounted';

[Link]('✅ Effect: Runs only on mount');


return () => {

[Link]('🧹 Cleanup: Runs on unmount');

};

}, []);

return (

<button onClick={() => setCount(count + 1)}>

Clicked {count} times

</button>

);

✅ 3. Dependency Array [count] (runs on mount and


when count changes)
jsx

CopyEdit

import React, { useEffect, useState } from 'react';

function EffectOnCountChange() {

const [count, setCount] = useState(0);

useEffect(() => {
[Link] = `Clicked ${count} times`;

[Link](`✅ Effect: Runs on mount and when count changes to ${count}`);

return () => {

[Link]('🧹 Cleanup: Before count changes or on unmount');

};

}, [count]);

return (

<button onClick={() => setCount(count + 1)}>

Clicked {count} times

</button>

);

✅ 1. Run on Every Render (similar to useEffect()


with no dependencies)
In class components, this happens by default in render(), but side effects are usually put in
componentDidUpdate.

jsx

CopyEdit

import React from 'react';

class EveryRenderClass extends [Link] {

state = { count: 0 };
componentDidUpdate() {

[Link] = `Clicked ${[Link]} times`;

[Link]('✅ componentDidUpdate: runs on every render after update');

render() {

return (

<button onClick={() => [Link]({ count: [Link] +


1 })}>

Clicked {[Link]} times

</button>

);

✅ 2. Run Only on Mount and Unmount (similar to


useEffect([]))
This is done using componentDidMount() and componentWillUnmount().

jsx

CopyEdit

import React from 'react';

class MountUnmountClass extends [Link] {

state = { count: 0 };
componentDidMount() {

[Link] = 'Component Mounted';

[Link]('✅ componentDidMount: runs only once when mounted');

componentWillUnmount() {

[Link]('🧹 componentWillUnmount: runs on unmount');

render() {

return (

<button onClick={() => [Link]({ count: [Link] +


1 })}>

Clicked {[Link]} times

</button>

);

✅ 3. Run on Mount and When count Changes


(similar to useEffect([count]))
This requires checking the specific state change inside componentDidUpdate.

jsx
CopyEdit

import React from 'react';

class CountChangeClass extends [Link] {

state = { count: 0 };

componentDidMount() {

[Link] = `Clicked ${[Link]} times`;

[Link]('✅ componentDidMount: runs on mount');

componentDidUpdate(prevProps, prevState) {

if ([Link] !== [Link]) {

[Link] = `Clicked ${[Link]} times`;

[Link](`✅ componentDidUpdate: count changed to ${[Link]}`);

componentWillUnmount() {

[Link]('🧹 componentWillUnmount: runs on unmount');

render() {

return (
<button onClick={() => [Link]({ count: [Link] +
1 })}>

Clicked {[Link]} times

</button>

);

🔄 What is Hoisting?
Hoisting is JavaScript’s default behavior of moving declarations to the top of the
current scope (either global or function scope) before the code is executed.

In simple terms:
💡 You can use some things before you declare them.

🔑 Summary Table
Declaration Type Hoisted? Usable before definition? Notes

var ✅ Yes ⚠️Yes (but undefined) Can be confusing

let / const ✅ Yes ❌ No (Temporal Dead Safer, preferred


Zone)

function ✅ Yes ✅ Yes Full hoist

function ⚠️Partially ❌ No Only variable hoisted,


expression not assignment

How to avoid hoisting problems!


There are a few things you can do to avoid hoisting problems: ✓ Always declare
your variables at the top of their scope. This will make your code more readable and
easier to maintain. ✓ Use the let or const keywords to declare your variables
instead of the var keyword. let and const variables are not hoisted, so they can only
be used after they are declared. ✓ Use JavaScript’s strict mode. Strict mode
prevents you from using undeclared variables, which can help to catch hoisting
problems

Keyword Scope Reassign? Redeclare? Hoisted?

var Function ✅ Yes ✅ Yes ✅ Yes

let Block ✅ Yes ❌ No ✅ (TDZ)

const Block ❌ No ❌ No ✅ (TDZ)

TDZ = Temporal Dead Zone — the time between entering scope and variable declaration where
access throws an error.

JavaScript Hoisting — it's the idea that variable and function declarations (NOT their
assignments) are moved ("hoisted") to the top of their scope before the code actually runs.

🌟 What’s happening in the new example?


You have this JavaScript code:

javascript

Copy code

for (var i = 1; i <= 10; i++) {

setTimeout(function() {

[Link](i);

}, 1000);

You are trying to:

● Print numbers 1 to 10.

● Each after a delay (after 1 second).

🌟 Understanding each part:


1. for loop runs very fast, almost instantly.

2. setTimeout says:
“Hey, after 1 second, run this [Link](i)."

3. But var i does not belong to just inside the {} of the loop.
It’s shared across the whole function.

Meaning:

● When the timers (the setTimeouts) actually run (after 1 second),

● The for loop is already finished.

● By that time, i has become 11 (because the loop stops when i > 10).

So all the setTimeouts print 11, not 1 to 10!

📢 Slide 1:
Js is a single threaded non-blocking asynchrounous concurrent language

Introduction to V8 and JavaScript Concepts

● It starts by asking "Do you have call back, event loop, call back queue?"
➔ These are features needed to handle asynchronous operations (like timers,
HTTP requests, etc.).

● It also asks, "Do you have DOM, HTTP request, setTimeout?" ➔ DOM, HTTP
requests, setTimeout are NOT part of the JavaScript engine itself — they are
provided by the browser or [Link] environment.

● If you say "No", it means you only have the core JavaScript engine (like V8 for Chrome
and [Link]).

✅ V8 itself only knows how to run JavaScript — it doesn't have a DOM or timers. ✅
Things like setTimeout, DOM manipulation, HTTP requests are outside the V8 engine —
they are provided by the browser APIs or [Link] APIs.

📢 Slide 3:
Stack vs Heap — What's the Difference?
Stack Heap

Stack stores static data (known size), like Heap stores dynamic data (objects,
primitive values (numbers, strings, booleans, arrays, functions) that can grow/shrink in
undefined, null). size.

The engine knows exactly how much space is The engine does NOT know the size
needed ahead of time. before — so it uses flexible memory
allocation.

Access is fast because the stack is organized Access is slower because heap is bigger
and small. and less organized.

💬 What does "references, which point to


objects and functions" mean?
When JavaScript deals with objects {} and functions function() {},
it does not store the whole object or function inside the stack.
Instead, it only stores a reference (a pointer) in the stack.

👉 This reference is like a little address — it tells JavaScript,


"Hey, the real object or function is over there in the heap memory."

✅ Example:
javascript

Copy code

let x = 5; // primitive → stored directly in the stack

let obj = { a 1 } :// object → reference stored in stack, real object


stored in heap

function greet() { [Link]("Hi"); } // function → reference in stack,


function body in heap

● x is a primitive → its value 5 is stored directly in the stack.


● obj is an object → the reference (pointer to where { a: 1 } is stored) is kept in the
stack, but the actual { a: 1 } is saved in the heap.

● greet is a function → again, only a reference is stored in the stack, but the actual
function code lives in the heap.

🔹 The Code:
javascript

CopyEdit

function fn(i) {

setTimeout(function () {

[Link](i);

}, 1000 * i);

for (var i = 1; i <= 10; i++) {

fn(i);

}
🔹 What's Happening:
1. Function Definition

javascript

CopyEdit

function fn(i) {

setTimeout(function () {

[Link](i);

}, 1000 * i);

● fn(i) is a function that takes a number i as input.

● Inside it, we call setTimeout, which delays running the function that logs i to the
console.

● The delay is 1000 * i milliseconds (which is the same as i seconds).

➡️For example: if i = 3, [Link](3) will be called after 3 seconds.

2. Loop

javascript

CopyEdit

for (var i = 1; i <= 10; i++) {

fn(i);

● This loop goes from i = 1 to i = 10, and calls the function fn(i) each time.

● So you are setting 10 timeouts:


○ First one logs 1 after 1 second

○ Second one logs 2 after 2 seconds

○ ...

○ Tenth one logs 10 after 10 seconds

YOUSUF PDF:

🔹 The Code:
javascript

CopyEdit

function fn(i) {

setTimeout(function () {

[Link](i);

}, 1000 * i);

for (var i = 1; i <= 10; i++) {

fn(i);

🔹 What's Happening:
1. Function Definition

javascript

CopyEdit

function fn(i) {

setTimeout(function () {
[Link](i);

}, 1000 * i);

● fn(i) is a function that takes a number i as input.

● Inside it, we call setTimeout, which delays running the function that logs i to the
console.

● The delay is 1000 * i milliseconds (which is the same as i seconds).

➡️For example: if i = 3, [Link](3) will be called after 3 seconds.

2. Loop

javascript

CopyEdit

for (var i = 1; i <= 10; i++) {

fn(i);

● This loop goes from i = 1 to i = 10, and calls the function fn(i) each time.

● So you are setting 10 timeouts:

○ First one logs 1 after 1 second

○ Second one logs 2 after 2 seconds

○ ...

○ Tenth one logs 10 after 10 seconds


stack [1]

macro [8]

stack [7]

macro [2]

macro [3]

stack [4]

micro [6]

macro [5]

WEEK 5
nd Event-Driven:
● In [Link], things don't block or wait — it keeps moving without getting stuck on one
request.

● Suppose a user asks for data from a database — [Link] sends the request and
moves on without waiting.

● When the database replies back, an event tells [Link]: "Hey! The data is ready," and
then [Link] responds.

● Result: It can handle many users at the same time without slowing down, making it
perfect for real-time apps like chat apps, live updates, etc.

2. Single-Threaded with Non-Blocking I/O:


● Normally, handling many users would require many threads (heavyweight 💪).

● But [Link] is smart — it uses only ONE thread (like a single line of workers) and still
manages thousands of users.

● Non-blocking I/O means when [Link] does input/output tasks (like reading files,
fetching database results), it doesn’t block the thread. It moves on and deals with
results later.

● Result: High performance 🔥 even with huge traffic and less memory usage.
3. Cross-Platform:
● You don't have to worry about "Will my code work on Windows? Linux? macOS?"

● [Link] can run anywhere easily across all major operating systems.

● Result: One codebase ➔ runs everywhere 💻 without big changes.

4. Rich Ecosystem (NPM):


● NPM (Node Package Manager) is a massive library store where developers share
reusable code (called packages).

● Need to send emails? Build a server? Connect to a database? ➔ There’s


already a package for that.

● It saves time and effort because you don't have to code everything from scratch.

● Result: Faster development, more power, and better apps 🚀

You are getting true because in a JavaScript class, methods like printName() are
automatically shared between all instances.

They are not re-created for every object.


Instead, the method printName is stored once on the prototype of the class, and every
object (g1, g2, etc.) just points to the same function.

👉 In short:
[Link] and [Link] refer to the same function in memory.
That's why [Link] === [Link] is true.

In JavaScript classes, the method that is automatically called when you do new Game()
must be called constructor(), not just any method name.

The problem here:


● You defined a method called Game(n), but in JavaScript it’s NOT the constructor.

● The JavaScript engine expects a method called exactly constructor() inside a


class.
● Since you didn’t define a constructor, JavaScript makes a default empty
constructor by itself.

● The Game(n) method is ignored unless you manually call it yourself (which you didn’t).

🧠 What These Slides Are Teaching:


Topic:
👉 Prototypal Inheritance in JavaScript

🟩 First Part (Top Half of the Slide)


● Main idea:
When you create a child object using a constructor (like Array, String, Number, etc.),
the child object automatically gets access to everything inside the constructor’s
prototype.

● What is a prototype?
It’s like a hidden backpack 🎒 that every JavaScript object carries.
This backpack contains useful methods and properties.

● How inheritance happens:

○ Your object doesn’t "copy" methods from the prototype.

○ Instead, it borrows or looks up into the prototype chain when it needs


something.

● Example:

○ Arrays (like [1, 2, 3]) can use .length, .push(), .map(), etc.

○ Strings ("hello") can use .split(), .toUpperCase(), etc.

○ This happens because [Link] and [Link] have these


methods, and your object inherits from them!

🟩 Second Part (Bottom Diagram)


● This is the “Prototypal Inheritance Tree”
Here's what it shows:

○ At the very top, everything starts from [Link].


(Every object in JS is based on Object by default.)

● Then from Object come specialized types:

○ Array → has methods like .map(), .filter(), .length

○ String → has .split(), .toUpperCase(), .length

○ Number → has .toFixed(), .toPrecision()

○ Function → has .call(), .apply(), .bind()

○ Boolean → has .toString(), etc.

● So if your object doesn't find a method on itself,


it climbs up the prototype chain (like a ladder) and looks inside its parent’s
prototype!

🔥 Quick Summary:
Concept Meaning

Prototype A hidden object where methods are stored

Inheritance Objects can use methods from their prototype

Chain Objects look upward (parent → grandparent) for missing


methods
Object at Everything eventually inherits from [Link]
Top
In JavaScript, Arrays and Functions are objects
and have an internal [[Prototype]] property.
However, String, Number, and Boolean are
primitive types, but JavaScript temporarily
wraps them in their object counterparts (String,
Number, Boolean) when accessing properties or
methods.

● YES 🔥💯
● In JavaScript, a string is a primitive, but when you use it like an object, JavaScript
automatically wraps it into a String object behind the scenes.

🧠 Normally:
const str = "hello";

● str is a primitive type (not an object).

🧹 BUT — when you do this:


[Link]([Link]());

JavaScript automatically does this for you:

const temp = new String(str);

[Link]([Link]());
● It wraps your primitive "hello" into an object temporarily.

● Calls the method .toUpperCase().

● Then throws away the temporary object.

🎯 So in short:
What you see What happens behind

"hello" new
String("hello")

✅ That's why you can use methods like .toUpperCase(), .slice(), .charAt() on
strings!

Prototype Chain Search


✅ Order of Lookup:

1. It first checks the object itself (g1).

2. If not found, it checks the prototype ([Link]).

3. If still not found, it checks [Link] (the top-most prototype).

4. If it finds nothing even there, it returns undefined.

This is called the prototype chain.

In JavaScript, any function can act as a constructor when you call it with the new keyword.

So even though this looks like a normal function:

function Game(name) {

[Link] = name;

[Link] = function() {
[Link]([Link]);

};

👉 When you call it like this:

let g1 = new Game("Chess");

It becomes a constructor call.


○ Example in the image:

■ foo1 and foo2 inherit from Foo.

■ bar1 and bar2 inherit from Bar.

■ Bar might itself inherit from Foo.

● Idea:

○ A copy-like relationship:
Child objects copy properties/methods from parent objects when created.

● Static Binding:
(Orange box in the middle)

○ Early binding → Code is linked at compile time.

○ Compile time → Structure is known before running the program.

○ Method overloading → Methods with the same name but different signatures.

2. Behavior Delegation (Right side)


● Explanation:

○ Here, instead of copying behavior, objects delegate behavior at runtime.

○ Example in the image:

■ foo1 and foo2 point to [Link].


■ bar1 and bar2 point to [Link].

■ [Link] may also link to [Link].

● Idea:

○ A link-like relationship:
Child objects look up their parent’s behavior dynamically if they don't have it.

● Dynamic Binding:
(Gray box in the middle)

○ Late binding → Code is linked at runtime.

○ Runtime → Structure can be flexible and determined when the program runs.

○ Method overriding → Methods can be replaced/modified at runtime.

REST stands for Representational State Transfer.

It is an architectural style for designing networked applications that relies on stateless communication
and standard HTTP methods like GET, POST, PUT, DELETE, PATCH, etc.

RESTful APIs follow a set of principles that make applications scalable, flexible, and easy to use.

An API (Application Programming Interface) is a set of rules and protocols that allows different software
applications to communicate and exchange data. It acts as a bridge between software systems, enabling
them to interact and share functionality.

Examples:

Google Maps API: Allows websites to embed Google Maps on their pages.

Social Media APIs: Enable applications to connect with social media platforms.

Payment APIs: Allow businesses to integrate payment processing into their applications.

Key RESTful API Principles


Statelessness: The server does not store any client state between requests. Each request must contain
all the information the server needs to understand and process it.

Client-Server Architecture: There is a separation between the client (user interface) and server (data and
logic), ensuring that both can evolve independently.

Uniform Interface: RESTful APIs use a consistent, standardized approach to interacting with resources
using HTTP methods and URLs. This includes standardized naming conventions for resources and
actions.

Cacheability: Responses from the server must be explicitly labeled as cacheable or non-cacheable,
promoting high performance in certain cases.
Layered System: The client does not need to know whether it is directly communicating with the server or
an intermediary.

🟡 1. User
● Who? — A person using your website or application.

● What do they do? — They interact with your application's View (what they can see and
click).

✅ Example:
Imagine you are visiting an Online Book Store.
You (User) want to search for a book.

🟡 2. View
● Who? — This is what the User sees: the UI (User Interface).

● What happens? — The View displays buttons, forms, etc. to the user.

● It captures user actions and sends the request to the Controller.

✅ Example:
You type "Harry Potter" into the search bar and click Search.
The View captures this input and sends it to the Controller.

🟡 3. Controller
● Who? — The brain that handles user actions.

● What happens? — The Controller processes the user's request.

● It decides what to do next — mostly it asks the Model for some data.

✅ Example:
The Controller says:

"User is searching for 'Harry Potter'. Let's find books matching that title."

It tells the Model to fetch the relevant data.


🟡 4. Model
● Who? — This handles the data and business logic.

● What happens? — The Model talks to the Database to get or update information.

✅ Example:
The Model sends a request to the Database:

"Give me all books where title matches 'Harry Potter'."

It fetches this data and returns it.

🟡 5. Database
● Who? — Your storage system (SQL, MongoDB, etc.).

● What happens? — Stores all your application's data.

✅ Example:
Database finds all matching books and sends the data back to the Model.

🟡 6. Returning and Rendering


● What happens after fetching data?

● The Model returns the data to the Controller.

● The Controller tells the View:

"Here is the list of Harry Potter books. Please show them to the user."

The View renders (displays) the data back to the user!

✅ Example:
You now see a beautiful list of Harry Potter books on your screen!
Why is the Controller Needed Between
Model and View?
In short:

The Controller is needed to keep the View and the Model separated and make
each part focused on its own job.

Now let's compare them carefully:

Feature CommonJS (CJS) ES Modules (ESM)

Import require('module') import something from 'module'


Syntax

Export [Link] = export default something / export


Syntax something { something }

Loading Synchronous (blocking) Asynchronous (non-blocking)

Default In Older [Link] versions Browsers and modern [Link] (type:


"module" in [Link])

File .js usually .js or .mjs


Extension

Performance Good for small apps Better for large-scale apps (optimized for async
loading)

ehavior:

● Synchronous loading:

○ If you require() a file, Node waits (blocks) until the module is fully loaded.

○ Slower for huge apps but simple for small ones.

ES Modules (ESM) Details

Behavior:
● Asynchronous loading:

○ Modules are fetched without blocking other operations.

○ Very useful for large apps, modern web development.

Sure! Below are 3 tricky but practical JavaScript/React use cases where using arrow
functions instead of regular functions solves real problems — especially with this binding
and cleaner syntax. These examples are written in .js / .jsx style and each includes:

● A realistic use case

● A problem with regular function

● A solution with arrow function

✅ Example 1: React Component Event Handler


❌ Problem with Regular Function:

jsx

CopyEdit

class Counter extends [Link] {

state = { count: 0 };

increment() {

[Link]({ count: [Link] + 1 }); // ❌ this is undefined

render() {

return <button onClick={[Link]}>Click</button>;

}
✅ Fixed with Arrow Function:

jsx

CopyEdit

class Counter extends [Link] {

state = { count: 0 };

increment = () => {

[Link]({ count: [Link] + 1 }); // ✅ this is preserved

};

render() {

return <button onClick={[Link]}>Click</button>;

Use case: Avoids the need for binding this in constructor. Cleaner, shorter, and
less error-prone.

✅ Example 2: Callback inside Array Method (map, filter, etc.)


❌ Problem with Regular Function:

js

CopyEdit

function Person(name, hobbies) {

[Link] = name;
[Link] = hobbies;

[Link] = function () {

[Link](function (hobby) {

[Link]([Link] + " likes " + hobby); // ❌ undefined

});

};

const p = new Person("Ali", ["Coding", "Reading"]);

[Link]();

✅ Fixed with Arrow Function:

js

CopyEdit

function Person(name, hobbies) {

[Link] = name;

[Link] = hobbies;

[Link] = function () {

[Link]((hobby) => {

[Link]([Link] + " likes " + hobby); // ✅ Correct `this`

});

};

}
Use case: Arrow functions inherit this from the enclosing function, solving
context issues in callbacks.

✅ Example 3: setTimeout inside Class Method


❌ Problem with Regular Function:

js

CopyEdit

class Timer {

message = "Time’s up!";

start() {

setTimeout(function () {

[Link]([Link]); // ❌ this is undefined

}, 1000);

✅ Fixed with Arrow Function:

js

CopyEdit

class Timer {

message = "Time’s up!";

start() {
setTimeout(() => {

[Link]([Link]); // ✅ works fine

}, 1000);

Use case: Inside asynchronous code (setTimeout, Promise, etc.), arrow


functions retain this from the class scope.

💡 Why Arrow Functions Matter in These Cases:

● Arrow functions don’t have their own this — they capture it from the parent scope.

● Regular functions have their own this that depends on how they're called — this often
causes confusion and bugs in class components or callbacks.

Great! Here's a problematic React class component example that uses a regular function
without binding this, which leads to an error.

❌ Problematic Code (Without Arrow Function or Binding)


jsx

CopyEdit

import React from "react";

class MyComponent extends [Link] {

state = { count: 0 };

handleClick() {

[Link]({ count: [Link] + 1 }); // ❌ Problem here


}

render() {

return (

<button onClick={[Link]}>

Clicked {[Link]} times

</button>

);

⚠️What’s the Problem?

● handleClick is a regular function.

● In JavaScript, regular functions don’t keep the this context automatically when
used as event handlers.

● So when handleClick runs (after a button click), this becomes undefined (in strict
mode).

● [Link] fails → ❌ Cannot read properties of undefined (reading 'setState')

✅ How to Fix It?


Option 1: Use Arrow Function ✅ (Best in React)

jsx

CopyEdit

handleClick = () => {
[Link]({ count: [Link] + 1 });

Option 2: Bind this in the constructor

jsx

CopyEdit

constructor() {

super();

[Link] = [Link](this);

🔁 Summary

Code Line Problem

onClick={[Link] Passes a method without binding. Loses


lick} this.

[Link](...) Crashes because this is undefined.

🧠 Final Definition (Simple)


🔸 Regular Function:

this depends on how the function is called.

🔸 Arrow Function:

this depends on where the function is written (called lexical this).


📘 1. React Component
Definition:
A React component is a JavaScript function or class that returns JSX (a special HTML-like
syntax) to describe what the UI should look like.

Types of Components:
● Functional Component – Written using a function.

● Class Component – Written using a class (less common in modern React).


Example (Functional Component):
jsx

CopyEdit

function Navigation() {

return (

<nav>

<li>Home</li>

<li>Blogs</li>

<li>Books</li>

</nav>

);

This creates a navigation menu with three list items.

🧠 2. JSX (JavaScript XML)


Definition:
JSX is a syntax extension for JavaScript that looks similar to HTML and is used in React to
describe the UI.

React doesn’t understand JSX directly. So, it needs to be compiled into regular JavaScript
using tools like Babel.

🔧 3. JSX Compiles to JavaScript (using Babel)


Example:
JSX:
jsx

CopyEdit

<h1 color="red">Heading here</h1>

After compilation:

js

CopyEdit

[Link]("h1", { color: "red" }, "Heading here");

This is what React actually reads and processes in the browser.

🪝 4. React Hooks
Definition:
Hooks are special functions in React that let you "hook into" React features like state, lifecycle,
and context from functional components.

Common Hooks:

● useState – To manage local component state.

● useEffect – To perform side effects (like fetching data).

● useContext – To use context values.

📌 5. useState Hook
Definition:

useState is a hook that allows you to create and manage state in a functional component.

Syntax:
js

CopyEdit

const [state, setState] = useState(initialState);

● state: the current value

● setState: function to update that value

Example:
js

CopyEdit

const [count, setCount] = useState(0);

setCount(count + 1); // this will increase count by 1

⏳ 6. useState as a Loading Flag


You can use useState to show loading messages while data is being fetched.

Example:
js

CopyEdit

const [loading, setLoading] = useState(true);

// In the render:

{loading ? <p>Loading...</p> : <p>Data Loaded!</p>}


🔁 7. useEffect Hook
Definition:

useEffect lets you perform side effects like data fetching, updating the DOM, or setting up
subscriptions.

Syntax:
js

CopyEdit

useEffect(() => {

// your code here

}, []);

Example: Fetch API Data


js

CopyEdit

useEffect(() => {

fetch("/api/projects")

.then(response => [Link]())

.then(data => {

setProjects(data); // store data in state

setLoading(false); // stop showing loading

});

}, []);
8. Full Example: React with Fetch API
jsx

CopyEdit

function App() {

const [loading, setLoading] = useState(true);

const [projects, setProjects] = useState([]);

useEffect(() => {

fetch("/api/projects")

.then(res => [Link]())

.then(data => {

setProjects(data);

setLoading(false);

});

}, []);

return (

<div>

<h1>Project List</h1>

{loading ? <p>Loading...</p> : [Link](p => <p>{p}</p>)}

</div>

);

}
🔴 What is Redux?
✅ Definition:
Redux is a state management tool for JavaScript apps (especially React apps).
It helps you store and manage data (state) in one central place, instead of passing it
between many components.

🎯 Main Purpose of Redux:


● To manage complex state in big applications.

● To share data easily between components without prop drilling (passing props again
and again).

● To make the state predictable and easy to debug.

🟩 How to Initialize Variables


In Syntax Example

React JS (with const [count, setCount] = ✅


useState) useState(0);

Redux (inside reducer) function(state = 0, action) ✅ default value


{ ... }

Vanilla JS let count = 0; ✅

✔ Example for Each:


React JS

js
CopyEdit
const [name, setName] = useState("Ali");

Redux Reducer

js
CopyEdit
function user(state = { name: "Ali" }, action) {

return state;

Vanilla JS

js
CopyEdit
var name = "Ali";

LIFTING STATE UP
Lifting state up in React involves moving the state to a common ancestor component to share it
between multiple child components. This ensures a single source of truth for the state and
makes data flow more predictable. When two or more components need to share and modify
the same data, instead of each managing their own independent copies, the state is "lifted" to
their nearest common parent.
The process involves:
Identifying the components that need to share the state.
Removing the state from the child components.
Defining the state in the common ancestor component.
Passing the state and the function to update it as props to the child components.
Child components can then access and modify the state through props.
This pattern helps avoid inconsistencies and synchronization issues, simplifies state
management, and ensures all components reflect the same data.

🔹 Slide 1: Execution Contexts Table


This slide explains Execution Contexts — a fundamental concept in JavaScript’s runtime.

What is an Execution Context?


It’s an abstract environment where JavaScript code runs. It contains things like
variables, the value of this, the scope chain, etc.

Here’s the breakdown of the table:


Who? Where It Lives Purpose / Behavior

Global Execution Stack initially, This is the very first context created when a
Context references script starts. It holds the global object (window
objects on Heap in browsers) and global variables.

Execution Stack Created every time a function is called. It


Context manages local variables, this, and scope. This
context is destroyed once the function call
finishes (unless it’s part of a closure).

Closure Context Heap Captures variables from outer scopes needed by


(V8 Context) inner functions. This context survives even after
the outer function finishes, enabling closures to
work.

Lexical Abstract model An invisible structure that links variable names


Environment (realized via to memory locations. It's implemented using
contexts) Execution or Closure Contexts to manage scope
and variables.

You might also like