IAD Notes_
IAD Notes_
💡 Key Points:
1. Direct Communication with Firestore:
2. NoSQL Database:
○ Example: Login system, storage, real-time updates — all with minimal code.
● Web (JavaScript)
● Android / iOS
● Unity / Flutter
You’ll use The Web (JavaScript) setup because you're working with React.
● 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:
1. Sign up / log in
📦 No backend needed! You’re saving data directly to the cloud without creating your own API.
🌍 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:
With Firebase:
● Client (React): .env or .[Link] — special config files that hold sensitive keys (like
Firebase API key).
● Server (Express): Also uses .env.
📝 Note: In React, the variable name must start with VITE_ so Vite can recognize and use it.
🧨 5. Sensitive Data
● Client: ❌ Never store sensitive info, only public Firebase keys.
🌟 7. Best Practices
Frontend (React)
Backend (Express)
🔐 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.
So, you don’t need a backend, but you must write proper rules — otherwise, your entire
database is open to the public 🚨
○ Even though hiding Firebase config doesn’t protect you fully, it’s still a good
habit.
○ You can tell Firebase to only allow requests from certain websites (like your
production domain).
○ It verifies if the request is coming from a genuine app or website (and not from a
hacker's script).
○ Google has guides like this one to help you avoid common mistakes.
● 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.
This means:
● Your UI components (like [Link], [Link]) should not directly connect to
Firebase.
● This hides Firebase's complexity and makes your code easier to manage and update.
● 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.
📦 Layer 3: Firebase
src/services/[Link]
● 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.
useEffect(() => {
return [Link]((user) => {
setUser(user ? user : null);
});
}, []);
return user;
}
● login() → to sign in
Summary:
✅ Again, your component doesn't know about Firebase — it just uses functions from the
service.
🧠 Simple Logic:
● If someone is logged in:
Show their name, a New Article button, and the Sign Out button.
● 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():
● If someone logs in, it fetches all the blog posts using fetchArticles() and saves
them in articles state.
✅ 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>
🧠 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.
👉 We'll use something called container and presentation pattern for clean code.
/components
─ [Link]
[Link]
/utils
└── [Link]
● [Link] → UI display component
<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>
<FriendFeedContainer />
</main>
Child Component:
<li className="friend-post">
<p className="post-content">{[Link]}</p>
● This visualizes how your React components are converted to HTML (DOM).
○ Managing state
● This component will fetch data (soon using fetchFriendPosts()), and pass it down
like
🟢 [Link] (Presenter):
return (
<ul>
{[Link](post => (
<li key={[Link]}>
<p>{[Link]}</p>
</li>
))}
● .map() is used to loop through the posts and display each one as a list item.
useEffect(() => {
}, []):
useEffect(() => {
setFriendPosts(posts); }
fetchData();
}, []);
Part Description
📂 The container fetches data using hooks → passes it down as props → presenter component
shows it.
};
🟨 [Link] (Presenter)
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.
✅ This separation of concerns makes the app cleaner and easier to manage.
useEffect(() => {
}, []);
But this approach can get messy, especially with multiple async calls.
useEffect(() => {
fetchData();
}, []);
This diagram breaks down the logic inside [Link] that decides what to show on the screen.
○ Show “New Article” button (which sets writing = true when clicked).
Middle (Navbar):
● If the user is logged in, show the <Nav /> component with props:
We're switching from fake article data (in memory) to real database data using Firebase
Firestore.
Structure:
3. Firebase:
1. Go to Firebase Console.
○ title → string
○ body → string
○ date → timestamp
✅ This gives you real database entries to fetch later in your app.
○ title
○ body
○ date
✅ This is now your real backend database, replacing the in-memory fake one.
fetchArticles():
createArticle():
● Returns a new article object with id, title, body, and date.
✅ These functions keep the database logic separate from your components.
🧪 It was good for learning, but not practical for real apps.
✅ 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]
🔁 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.
● 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.
● 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.
● 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.
○ For example:
■ p has font-size: 16px, font-weight: bold
🌲 3. Render Tree
● The browser combines DOM + CSSOM to build a Render Tree.
● This tree shows only the visible elements with their computed styles.
📌 Example:
● Only Hello and students appear inside p, because span was hidden.
html
CopyEdit
<p>Some text</p>
✅ Tag
Tags are the opening and closing parts of an element.
In the example above:
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.
● 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.
2. The API on the server receives the request and communicates with:
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).
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:
● DOM is dynamic — it changes as the browser renders and JavaScript manipulates it.
● 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.
● ✅ Scripting access:
JavaScript or other scripting languages can be used to interact with these objects.
○ Color
○ Transparency
○ Position
○ Sound
html
Copy code
<a href="[Link]">Click me</a>
turns into:
js
Copy code
[Link]('a').href // '[Link]'
●
mathematica
Copy code
Document
└── Root element: <html>
├── <head>
│ └── <title> → Text: "My title"
└── <body>
├── <h1> → Text: "A heading"
└── <a href="..."> → Text: "Link text"
Website
● Purpose: Informational or presentational.
🔄 Web Service
● Purpose: Machine-to-machine communication (not designed for human users).
● Example: REST APIs, SOAP services (like weather data APIs, payment gateways).
📌 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.
● Protocols Involved:
● 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:
● Use Case: Transferring confidential documents, like legal or financial files, securely from
one system to another.
● How it works:
○ User enters card details (like the HBL Platinum Visa card shown).
● Use Case: Online shopping, utility bill payment, subscriptions (like Netflix or Spotify).
○ 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:
● Use Case: Sharing project files, assignments, large media files, etc.
[Link]
2.
Your browser sends a HTTP request to the web server of [Link], asking:
pgsql
Copy code
GET /[Link] HTTP/1.1
3.
css
Copy code
200 OK
4.
5. Your browser renders the HTML and shows you the website.
📦 Example:
http
Copy code
Host: [Link]
http
Copy code
HTTP/1.1 200 OK
Content-Type: text/html
<html>
<body>Welcome to Example!</body>
</html>
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
🎯 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.
● 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: 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.
🔚 Outcome:
🧭 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.
● 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.
bash
Copy code
telnet <IP address> <Port>
2.
○ Replace <IP address> with the address of the remote computer.
bash
Copy code
telnet [Link] 1521
3.
4. What does a blank screen mean?
○ Success!
○ 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.
Copy code
Connecting To [Link]...
📘 Explanation:
● Microsoft Telnet Client: This is a command-line tool used to connect to remote servers.
○ 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.
vbnet
Copy code
Content-Length: 54
● As a result, Google returns a 400 Bad Request error. This means the server didn’t
understand the request due to invalid syntax.
vbnet
Copy code
GET / HTTP/1.1
Host: [Link]
● GET / HTTP/1.1:
🔸 You need to press Enter twice at the end to indicate the end of the request headers.
php-template
Copy code
● 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.
● 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.
● The server simply checks its file system (just like opening a folder on your PC) and finds
the requested file (e.g., [Link]).
📝 Important Note:
"Static does not mean that it will not respond to user actions."
● 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.
● This is the user’s device, running a web browser (like Chrome, Firefox, etc.).
🖧 2. Web Server
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.
3. If needed, the server queries the database (e.g., “get blog post #5”).
➡️Built using:
● Backend like [Link], Python, PHP
➡️Uses:
● Real-time databases
🔹 Example:
html
Copy code
<p>This is a paragraph
Even though the </p> is missing, the browser will still show the paragraph.
🔹 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.
xhtml
Copy code
<br /> <!-- Self-closing tags must end with a slash -->
Week 3
● 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.
(ii) A __??__ containing __??__ element is used to group and structure the button
independently.
○ Why? That’s the interactive element inside the <div> that users can click on to
increment the counter.
This improves UX by adding smooth visual feedback when users hover over the button.
The variables defined under the :root selector are __??__ (local/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.
○ 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.
○ Why? Local variables are available within the element they’re defined in and its
child elements.
🔢 Flow:
User (1) → OS (2) → Browser (3) → OS (4) → Browser (5) → Browser (6)
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.
🔲 First Blank:
Just like [Link] the [Link] protocol is also a ?? in the broader URI
structure.
● Why? In a URL, the "scheme" defines how the resource is accessed. Common schemes
include:
○ http, https → for web
🔲 Second Blank:
Just as HTTP URLs point to resources on the ??, file URLs point to resources on
the ??.
● 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."
○ This part denotes the category or region (.com, .org, .pk, .edu, etc.)
○ Managed by ICANN.
○ 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:
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://
● [Link]
○ blog → Subdomain
✅ 3. Port:
● :443
✅ 4. Path:
● /6-parts-of-a-url
✅ 5. Query String:
● utm_source=linkedin&utm_medium=organic
✅ 6. Fragment:
● #definition
● It tells the browser to scroll to a specific section (like an anchor or heading) on the page.
“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.
● CORS lets servers safely share resources (like APIs, images, etc.) with clients hosted on
different domains.
“This indicates that the backend server does not include the appropriate CORS
headers in its response.”
● 🔹 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:
● This means you're running the app locally for testing before deployment.
[Link] vs Vanilla JavaScript
Feature Vanilla JavaScript [Link]
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).
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.
1. 🔁 Reusable Components
You can build UI elements like buttons, cards, forms as reusable pieces — write once, use
anywhere.
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.
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.
Open-source front-end JavaScript library used for building composable user interfaces,
especially for single-page applications (SPA).
🔹 It is used for handling the view layer in web and mobile apps, based on components in
a:
Declarative manner.
🔁 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>;
}
React handles the how — like creating the element, attaching the event, adding it to the DOM,
etc.
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”?
Compare it to a blueprint:
You say:
jsx
Copy code
<button onClick={handleClick}>Click Me</button>
● Call [Link]()
● Bind addEventListener()
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:
Here’s a breakdown of the main features shown in the image and text on the right:
🔹 JSX Syntax
🔹 Virtual DOM
● Instead of directly updating the real DOM (which is slow), it updates a virtual copy and
then syncs changes.
Server-side Rendering
● Content gets delivered faster, and it's more crawlable by search engines.
🔹 Reusable/Composable Components
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.
It is a virtual copy of the ➤ It's not the real DOM, just a lightweight JS
original DOM version used to compare changes.
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.
After manipulation, it re-renders the ➤ Any change might cause full DOM
entire UI refresh — which is slower.
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.
Stateful It can store and manage state (data that can change over time).
■ state
jsx
Copy code
import React, { Component } from 'react';
render() {
return (
<div>
<h2>{[Link]}</h2>
<button onClick={[Link]}>Click Me</button>
</div>
);
}
}
● When you click the button, the state updates via [Link](), and React re-
renders the component with the new message.
● Use state
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.
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={handleClick}>Increase</button>
</div>
);
}
Why? Because:
● The second call sees the updated value (1) and sets it to 2.
So, mid-render = the time when your component is being executed (e.g., your JSX is being
returned).
function MyComponent() {
// ❌ 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.
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.”
● Effects (useEffect)
function MyComponent() {
};
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
4. Blank 4: transfer
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.
🟢 STATE
1. Blank 1: modified
2. Blank 2: component
When state changes, React re-renders the component that owns that state, to reflect
the new data.
Components become dynamic and interactive with state — for example, a counter that
updates on click.
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:
CopyEdit
function EffectEveryRender() {
useEffect(() => {
};
});
return (
</button>
);
CopyEdit
function EffectOnMountOnly() {
useEffect(() => {
return () => {
};
}, []);
return (
</button>
);
CopyEdit
function EffectOnCountChange() {
return () => {
};
}, [count]);
return (
</button>
);
jsx
CopyEdit
state = { count: 0 };
componentDidUpdate() {
render() {
return (
</button>
);
jsx
CopyEdit
componentDidMount() {
componentWillUnmount() {
render() {
return (
</button>
);
CopyEdit
state = { count: 0 };
componentDidMount() {
componentDidUpdate(prevProps, prevState) {
componentWillUnmount() {
render() {
return (
<button onClick={() => [Link]({ count: [Link] +
1 })}>
</button>
);
WEEK:04
Slide 1: JS Runtime Environments
✅ Filled Blanks & Key Points:
● 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.
💡 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.
● Three of the most well-known languages are TypeScript, CoffeeScript, and Dart.
💡 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.
CopyEdit
[Link](a); // undefined
var a = 5;
var a; // hoisted
[Link](a); // undefined
a = 5;
let b = 10;
● let and const are hoisted too, BUT they are in a temporal dead zone (TDZ).
📦 Function Hoisting
✅ Function Declarations are hoisted:
js
CopyEdit
greet(); // "Hello"
function greet() {
[Link]("Hello");
CopyEdit
[Link]("Hi");
};
js
CopyEdit
🔑 Summary Table
Declaration Type Hoisted? Usable before definition? Notes
var ✅ Yes ⚠️Yes (but undefined) Can be confusing
🔥 Best Practice
● Use let and const instead of var.
● So the function six is available even before its place in the code.
Result for x:
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:
✅ 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() {
var x = 10;
[Link](x); // 10
✅ let
Hoisting: Yes, but not initialized — you get a ReferenceError if accessed before declaration.
Edit
{
let x = 10;
x = 20; // ✅ allowed
✅ const
Use case: Use for constants (unchanging values). Note: const objects and arrays can still be
mutated.
Edit
const y = 10;
y = 20; // ❌ Error
⚡ Summary:
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.
function f() {
x = 5;
y = 3;
f();
[Link](x); // 5
[Link](y); // 3
🔵 Explanation:
📝 Important: When you don't use var, let, or const, variables become global — BAD
PRACTICE!
function f() {
a = 5;
b = 3;
f();
[Link](a); // ReferenceError
[Link](b);
🔵 Explanation:
● Because of hoisting, JavaScript moves the var a, b; declaration to the top of the
function f().
function f() {
var a, b;
a = 5;
b = 3;
}
● Outside the function (in [Link](a)), they do not exist — that's why you get a
ReferenceError.
📝 Key Point:
● If var is used, the variable is hoisted to the top of the function but stays inside the
function (local).
Example code:
var a = 10;
function print() {
[Link](a);
var a = 20;
[Link](a);
print();
var a = 10;
function print() {
[Link](a); // undefined
a = 20;
[Link](a); // 20
🔵 Line-by-line behavior:
○ 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.
● Inside a function, a local variable shadows the global variable if declared with var.
SCOPING:
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.
Table Fill:
here/how Scope
[Link](4); // ✅ allowed
[Link](numbers); // [1, 2, 3, 4]
[Link](numbers); // [100, 2, 3, 4]
🧠 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
?
Reassign whole ❌ No
array/object
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.
javascript
Copy code
setTimeout(function() {
[Link](i);
}, 1000);
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:
● By that time, i has become 11 (because the loop stops when i > 10).
CopyEdit
setTimeout(() => {
[Link](i);
}, 1000);
👉 What happens?
● By the time the setTimeout actually runs after 1 second, the for loop has already
finished.
So output:
bash
CopyEdit
js
CopyEdit
setTimeout(() => {
[Link](i);
}, 1000);
bash
CopyEdit
🧠 Why?
4o
You said:
ChatGPT said:
Alright — let me explain it even more simply, like we are sitting side-by-side. 🧠✨
js
CopyEdit
setTimeout(() => {
[Link](i);
}, 1000);
1. The for loop runs very fast — almost instantly — before any setTimeout even fires.
Thus, it prints 5 5 5 5 5.
🔥 Important point:
js
CopyEdit
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.
4o
You said:
dry run
ChatGPT said:
Code:
js
CopyEdit
setTimeout(() => {
[Link](i);
}, 1000);
Dry Run:
At start:
● i = 0
● i becomes 5.
● Loop stops.
● 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.
CopyEdit
setTimeout(() => {
[Link](i);
}, 1000);
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
● 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).
○ Memory Stack: for managing function calls and static memory (small and fast
access).
○ Heap: for storing larger, dynamic objects like arrays, objects, etc.
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.
Copy code
● 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.
● Reference = a memory address that points to where the object or function really is in the
heap.
"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
○ 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.
id: 1,
name: 'John',
age: 25,
};
const dog = {
name: 'puppy',
personId: 1,
};
Red arrows show how variables in the stack point to objects/functions in the heap.
● How errors like RangeError: Maximum call stack size exceeded happen.
function multiply(a, b) {
return a * b;
function square(n) {
function printSquare(n) {
[Link](squared);
printSquare(4);
1. printSquare(4) is called:
○ (It’s waiting to finish printSquare, but it can’t yet because it needs to do more.)
2 square(4)
1 printSquare(4)
Each time you call a function, it’s added to the top of the stack.
○ JavaScript removes multiply(4,4) from the top of the stack (pops it).
● 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
function foo() {
return foo();
foo();
● Eventually, the browser runs out of memory space for the stack.
🔔 This error means: "You have called too many functions without finishing them — the stack is
full!"
and are going to run sometime later, so can’t be pushed immediately inside the call stack,
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);
fn(i);
🔹 What's Happening:
1. Function Definition
javascript
CopyEdit
function fn(i) {
setTimeout(function () {
[Link](i);
}, 1000 * i);
2. Loop
javascript
CopyEdit
fn(i);
● This loop goes from i = 1 to i = 10, and calls the function fn(i) each time.
○ ...
● The first while loop runs for 10 seconds — showing alerts and blocking.
● 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.
✅ 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? 🎯
ChatGPT said:
○ And only after that, the second batch (results alert loop) runs.
Example:
javascript
CopyEdit
});
🔹 2. What is async/await?
● async turns a function into a Promise and allows use of await inside.
Example:
javascript
CopyEdit
[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)."
Example:
javascript
CopyEdit
requestIdleCallback(() => {
});
js
CopyEdit
This means the function waits for the browser to be idle before continuing to show more alerts.
[Link]('stack [1]');
const p = [Link]();
[Link](() => {
setTimeout(() => {
[Link]('stack [4]');
}, 0);
[Link]("stack [7]");
});
[Link]("macro [8]");
Microtasks (Promise Run after stack is empty but before any macrotask (timeout,
.then) interval)
🖨 Output so far:
cpp
Copy code
stack [1]
Copy code
[Link](...)
Important:
● Any nested timeouts inside .then() will again be macrotasks scheduled later.
🖨 Output now:
css
Copy code
stack [1]
macro [8]
🖨 Output now:
css
Copy code
stack [1]
macro [8]
stack [7]
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.)
🖨 Output:
css
Copy code
stack [1]
macro [8]
stack [7]
macro [2]
🖨 Output:
css
Copy code
stack [1]
macro [8]
stack [7]
macro [2]
macro [3]
🖨 Output:
css
Copy code
stack [1]
macro [8]
stack [7]
macro [2]
macro [3]
stack [4]
micro [6]
🖨 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.
● 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.
● It saves time and effort because you don't have to code everything from scratch.
The function inside a class after ES6 allows multiple instances to share the same method,
improving memory efficiency.
javascript
Copy code
class Person {
[Link] = name;
javascript
Copy code
class Person {
[Link] = name;
javascript
Copy code
class game {
constructor(n) {
[Link] = n;
printName() {
[Link]([Link]);
javascript
Copy code
and checked:
javascript
Copy code
You are getting true because in a JavaScript class, methods like printName() are
automatically shared between all instances.
👉 In short:
[Link] and [Link] refer to the same function in memory.
That's why [Link] === [Link] is true.
Quick visualization:
text
Copy code
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
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] = n;
printName() {
[Link]([Link]);
javascript
Copy code
[Link]();
● The Game(n) method is ignored unless you manually call it yourself (which you didn’t).
● So [Link] is undefined.
Then:
[Link]():
● [Link]([Link]); will print undefined.
📋 Final Output:
undefined
"This proves that Game(n) is just a regular method, your object instances never call it
automatically."
Step-by-Step Explanation:
1. typeof Game
javascript
Copy code
✅ 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]);
javascript
Copy code
● What is a prototype?
It’s like a hidden backpack 🎒 that every JavaScript object carries.
This backpack contains useful methods and properties.
● Example:
○ Arrays (like [1, 2, 3]) can use .length, .push(), .map(), etc.
📝 Simple Example:
javascript
Copy code
[Link]('length');
🔥 Quick Summary:
Concept Meaning
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).
[Link]([Link]());
🎯 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";
● "hello" is primitive.
🛠 Visual:
"hello" (primitive)
↪ discarded
💥 FINAL LINE:
✅ String is primitive, but when you use methods on it, JavaScript treats it like an
object temporarily.
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.
5. Prototypes allow method sharing & memory efficiency. Without prototypes, every object would
have its own copy of methods, leading to huge memory waste.
6.
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:
Key Problem:
● Memory is wasted because each object has its own copy of the same function.
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:
Key Benefit:
● Memory efficient: Only one copy of printName exists, shared across all objects.
✅ Order of Lookup:
Key Concept:
In JavaScript, any function can act as a constructor when you call it with the new keyword.
function Game(name) {
[Link] = name;
[Link] = function() {
[Link]([Link]);
};
How it works under the hood when you use new Game("Chess"):
1. A new empty object {} is created.
So g1 becomes:
name: "Chess",
● Idea:
○ A copy-like relationship:
Child objects copy properties/methods from parent objects when created.
● Static Binding:
(Orange box in the middle)
○ Method overloading → Methods with the same name but different signatures.
2. Behavior Delegation (Right side)
● Explanation:
● 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)
○ Runtime → Structure can be flexible and determined when the program runs.
⚡ Key Difference:
Prototypal Inheritance Behavior Delegation
📚 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:
○ 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."
● 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."
✏️Fill-in:
"Backend server will accept HTTP requests from frontend app and use CRUD operations
to interact with the DB."
4. What is [Link]?
● Express is a simple and powerful web framework built for [Link].
✏️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.
📚 Point-by-point Explanation:
1. How REST API Works (Diagram on top half):
● REST Client (usually frontend app) makes a REST Call.
● The REST API Server receives the request and processes it.
● The Server then replies to the client with the requested data.
Example:
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.
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),
✓ 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).
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.
Example:
[Link](3, 5, 7);
● 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.
🎯 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.
🔵 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).
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.
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:
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:
● Inside the building, there are many rooms: /users, /products, /orders.
✏️Explanation:
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).
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
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
environment environment
server server
endpoints endpoints
requests requests
construct construct
nginx
Copy code
GET [Link]
✅ They meet successfully because both sides share the base URL!
pgsql
Copy code
↑ ↓ ↓ ↑
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.
✅ 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.
● 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:
🟡 5. Database
● Who? — Your storage system (SQL, MongoDB, etc.).
✅ Example:
Database finds all matching books and sends the data back to the Model.
"Here is the list of Harry Potter books. Please show them to the user."
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.
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
● Difficult to maintain.
● Difficult to debug.
● Difficult to upgrade.
✅ This way:
Controller Waiter (takes order from customer and tells kitchen what to
cook)
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.
Example:
When you visit /profile, the backend:
● Prepares it in Controller
● Uses EJS to generate an HTML page (View) with user's name, photo, etc.
● 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:
● Frontend (React) fetches the data from APIs and renders the UI.
However:
● You can organize a React app in an MVC-like way if you want.
● 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:
○ Perform the core logic — e.g., calculating, validating data, deciding what to
store/retrieve.
○ Services interact with the database using models. Models define the structure of
the data (like what fields a "User" has: name, email, etc.).
● External APIs:
○ If needed, the backend can talk to other external services/APIs too (e.g.,
payment gateways, third-party services).
csharp
Copy code
npm init -y
●
● What this does:
json
Copy code
"name": "back_end",
"version": "1.0.0",
"description": "",
"main": "[Link]",
"scripts": {
},
"author": "",
"license": "ISC"
}
● It basically defines:
● But how we import and export code depends on the module system you choose.
Behavior:
● Synchronous loading:
○ If you require() a file, Node waits (blocks) until the module is fully loaded.
Behavior:
● Asynchronous loading:
● This means [Link] will wait (pause) until the module is fully loaded before moving
forward.
2. Example: [Link]
javascript
Copy code
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
// Exporting functions
[Link] = {
add,
subtract
};
3. Example: [Link]
javascript
Copy code
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
● Every time someone sends a request (like opening a webpage, submitting a form),
Morgan prints a line in the console.
○ URL
○ Time taken
bash
Copy code
Copy code
● 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.
arduino
Copy code
Server running at [Link]
Copy code
🔥 Final Result:
fullUrl = "[Link]
bash
Copy code
Copy code
});
● (req, res) => {...} is the callback function that handles the request.
javascript
CopyEdit
});
○ 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.
● 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
This would improve the structure, ensuring the client receives a properly structured 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
});
● 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
● It also automatically binds the this context, making it easier to work with inside
callbacks.
● A. Arrow function
● B. Callback function
● C. Anonymous function
[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".
✅ First part:
✅ Second part:
1. ()=>{} are a concise way of writing anonymous, lexically scoped
functions in ES6.
✅ Third part:
✅ Fourth part:
3. The ()=>{} accomplishes the same result as a regular function with fewer
lines of code.
✅ Fifth part:
✅ 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:
✅ 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]
javascript
Copy code
const frog = {
sayHello: function () {
};
arrowFunc();
};
[Link]();
mathematica
Copy code
🧠 Why?
● sayHello is a normal function, so this refers to frog.
● 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.
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() {
};
arrowFunc();
};
[Link](); // prints 42
● 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 = () => {
};
arrow();
Visual:
Think of it like this:
vbnet
CopyEdit
the `this` of
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.
CopyEdit
const obj = {
value: 42,
arrowFunc: () => {
};
[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.
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](); // 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](); // 42
But here, you're hardcoding the object name (obj), which is not flexible and usually bad
practice.
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:
○ 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.
javascript
CopyEdit
const obj = {
value: 10,
regularFunc: function() {
[Link]([Link]);
};
[Link](); // 10
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.
"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)."
"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:
javascript
CopyEdit
const outer = {
outerValue: 100,
createArrow: function() {
return () => {
[Link]([Link]);
};
};
Step-by-Step Explanation
javascript
CopyEdit
const outer = {
outerValue: 100,
};
It has:
● a property outerValue = 100
javascript
CopyEdit
● In regular functions, when you call [Link](), this points to the object.
javascript
CopyEdit
return () => {
[Link]([Link]);
};
● 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]()).
javascript
CopyEdit
● Even though you're calling arrow() from somewhere else (global code), it still
remembers that this = outer.
javascript
CopyEdit
● If you have a variable that holds a function, you call the function by adding
parentheses after the variable name.
Example:
javascript
CopyEdit
[Link]("Hello!");
};
3. In your case:
javascript
CopyEdit
const arrow = [Link](); // arrow holds a function
● So when you write arrow(), you call the function inside the variable.
Copy code
const wizard = {
magicNumber: 50,
castSpell: () => {
[Link]([Link]);
};
[Link]();
Problem:
● 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.
Corrected code:
javascript
Copy code
const wizard = {
magicNumber: 50,
[Link]([Link]);
};
[Link](); // ✅ Output: 50
const hero = {
name: "Thor",
greet: function () {
[Link](`Hello, I am ${[Link]}`);
};
inner();
};
[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:
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 () {
[Link](`Hello, I am ${[Link]}`);
};
inner();
greet: function () {
[Link](`Hello, I am ${[Link]}`);
};
inner();
const wizard = {
magicNumber: 42,
spell: function(a, b) { // Regular function
return a + b + [Link];
};
[Link]([Link](10, 5));
Now, step-by-step:
this refers to the object wizard because you are calling it with dot notation ([Link]).
So:
It prints:
yaml
Copy code
Magic Boost: 42
Copy code
10 + 5 + 42 = 57
Final Output:
yaml
Copy code
Magic Boost: 42
57
javascript
Copy code
fetch("/api/projects")
✅ Filled blanks:
● fetch(" **/api/projects** ")
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:
● 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).
2. Props:
○ Example:
If the parent has a userName in its state, it can pass it to a child like:
3. Child Components:
○ They can also have their own state (local state inside each child).
○ Example:
○ If a child needs to update data (for example, a button click), it calls a function
received through props.
○ This updated state is passed down again through props, refreshing the UI.
5. Example:
It passes it to child:
<ChildComponent changeName={[Link]} />
Child calls it on button click:
[Link]('NewUserName');
[Link]:
function Dashboard() {
const [userName, setUserName] = useState('John Doe');
return (
<>
<UserProfile name={userName} changeName={setUserName} />
<UserPosts user={userName} />
</>
);
}
[Link]:
[Link]:
[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.
○ setUserName is the function you will call whenever you want to update the
userName.
● return (...) ➔ This tells React what to render in the browser.
2. [Link]
function UserProfile({ name, changeName }) {
return (
<div>
<h2>{name}</h2>
<button onClick={() => changeName('Jane Doe')}>Change
Name</button>
</div>
);
}
🔵 Explanation step-by-step:
3. [Link]
function UserPosts({ user }) {
return <h3>Posts by {user}</h3>;
}
🔵 Explanation step-by-step:
🧠 In Short:
● Dashboard controls the state.
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.
✅ 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
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:
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.
🧠 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.
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.
🧠 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.
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.
● 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!");
return (
<div>
<h1>Parent says: {message}</h1>
{/* Pass data and function to child */}
<Child parentMessage={message}
sendToParent={receiveFromChild} />
</div>
);
}
return (
<div>
<h2>Child received: {parentMessage}</h2>
○ It passes data (state) and functions (handlers) down to child components via
props.
🧾 Slide Breakdown
Component A (Parent Component)
This component owns the state and creates the handler function, then passes them to the
children.
Component B (Child of A)
Component C (Child of B)
So, even deeply nested components can access parent functions, as long as they’re passed
down correctly.
Component D (Direct child of A)
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.
● 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>
Line 1
Line 2
● More accessible and semantic in HTML (screen readers & SEO prefer it).
🔹 Example:
<p>Line 1</p>
<p>Line 2</p>
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:
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]
javascript
Copy code
// Code on frontend ([Link]
fetch('[Link]
.then(response => [Link]())
.then(data => [Link](data))
.catch(error => [Link]('CORS error:', error));
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.
javascript
Copy code
const express = require('express');
const cors = require('cors');
const app = express();
arduino
Copy code
Access-Control-Allow-Origin: [Link]
✅ This tells the browser it’s safe to share the response with the frontend.
When the server doesn’t include the right CORS headers, the browser
refuses to share the response and throws this error:
In short, the browser isn’t blocking the request, it’s blocking the response for security reasons.
What it is A browser security rule that blocks web pages from accessing data from a
different origin
What it is A protocol (set of headers) that allows servers to override the Same-Origin
Policy
○ CORS errors happen even if your frontend is perfect. The issue lies in how the
backend responds to the browser.
○ The browser is doing the correct thing by blocking the request for security. It’s
following the Same-Origin Policy.
○ Your server must explicitly tell the browser: “Yes, I allow this origin (e.g.,
[Link] to access my data.”
http
Copy code
Access-Control-Allow-Origin: [Link]
●
● This tells the browser: “[Link] is allowed to access this resource.”
● For requests with methods like POST, or with custom headers, the browser sends an
OPTIONS request first (called a preflight).
http
Copy code
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type
1. Using methods other than GET or POST (like PUT, DELETE, PATCH)
http
Copy code
OPTIONS /api HTTP/1.1
Origin: [Link]
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type
● If setting CORS headers is tricky, you can configure your frontend dev server to proxy
API calls, avoiding CORS issues entirely.
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]
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.
🔶 Example 2:
bash
Copy code
[Link]
● Scheme: https
● Host: [Link]
● 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
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).
✅ Goal:
1. User logs in from frontend
[Link](cookieParser());
[Link]([Link]());
[Link](5000, () => {
[Link]('API running on [Link]
});
🍪 Notes:
📌 What it does:
[Link](cors({
origin: '[Link] // allow only frontend origin
}));
[Link](5000, () => {
[Link]('Server running on [Link]
});
● 📥 Inspect or modify the request (like logging, parsing JSON, checking authentication)
CORS is a middleware because it sits between the request and the response and controls
access based on origin.
javascript
Copy code
import express from 'express';
import cors from 'cors';
[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](5000);
● You avoid exposing your backend to all origins ('*'), which can be insecure.
● Can be redeclared
javascript
Copy code
function test() {
[Link](x); // undefined, because of hoisting
var x = 10;
}
● 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:
✅ 3. Variable Hoisting
● Hoisting is JavaScript's default behavior of moving declarations to the top of the current
scope.
● 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).
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
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.
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.
● The call stack is runtime-based and manages the order of function execution.
🔄 Final Output:
vbnet
Copy code
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
🔍 Breakdown:
● The call stack works like a stack of plates — last-in, first-out (LIFO).
📘 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):
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
secretBox();
// [Link](secret); // ❌ ReferenceError: secret is not defined
✅ Module Scope:
html
Copy code
<script type="module">
const foo = "foo";
</script>
<script>
[Link](foo); // ❌ ReferenceError: foo is not defined
</script>
🔍 Explanation:
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.
🧠 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).
For example:
js
Copy code
function greet() {
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().
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).
Recursion: A function can call itself and still remember the surrounding state via closure.
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.
✅ Example:
javascript
Copy code
function outer() {
let name = "Alice";
outer();
💬 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.
✅ 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 + "!");
};
}
🔍 Explanation:
Haha! It does look like sorcery at first — but it’s just one of JavaScript’s most powerful
and beautiful features: Closures.
js
CopyEdit
"Hello, [name]!"
Later:
js
CopyEdit
sayHello("Alice");
The bot remembers its original greeting "Hello" and uses it.
js
CopyEdit
return function(name) {
};
2.
3. This inner function remembers the greeting variable from its outer function’s
scope, even after greetingGenerator has finished running.
🔍 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;
}
🔗 Why it works:
🔥 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.
🧠 Code Breakdown:
js
Copy code
function outer() {
let secret = "I am a secret!";
📌 Explanation:
● Even after outer() finishes execution, the returned function (inner) retains
access to secret via closure.
3. Global scope
📌 Explanation:
○ innerParam (local)
● Even after outerFunc returns, innerFunc still retains access to outerParam via
closure.
📤 Output:
sql
Copy code
guess outer inner
Because:
● innerParam is 'inner'
[Link](i); // Outputs 5
❌ Issue:
● Using var in the loop means all closures share the same i.
⚠ Output:
Copy code
5
5
5
5
5
💡 Fixes:
js
Copy code
for (let i = 0; i < 5; i++) {
[Link](function () {
return i;
});
}
js
Copy code
for (var i = 0; i < 5; i++) {
(function(j) {
[Link](function () {
return j;
});
})(i);
}
✅ Explanation:
[Link](i); // ?
🧠 DRY RUN
🗂 Memory Before Loop
● arrFuncs → []
● i is undefined
🔁 Loop Execution (with var)
🧾 Third Iteration (i = 2)
🧾 Fourth Iteration (i = 3)
🧾 Fifth Iteration (i = 4)
js
Copy code
function () { return i }
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.
js
Copy code
function () {
return i; // closes over the same `i` from outer scope
}
● At this point, i is 5
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.
● When the functions are finally called, they all return the current value of i, which is 5.
● That means innerFunc reaches out to the global scope for the current value of
globalVar at the time it runs.
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.
🔹 Example Syntax:
js
Copy code
(function() {
[Link]("Hi there!");
})();
When using var in a loop, every function shares the same i variable due to function scoping.
🔍 Concept Breakdown
🔸 PROBLEM FIRST (No IIFE):
In the version without IIFE:
🔸 GOAL:
We want each function to remember the value of i at the time it was created, not the final
value (5).
We’re using a var-declared loop. So i is function scoped, and shared across all
iterations.
Each time:
● The returned function closes over j, which is now fixed for that iteration
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.
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
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);
}
“The function x => [Link] === make remembers the variable make from its
outer function (getCarsByMake), even though it's used after getCarsByMake
is done running.”
🔧 Step-by-step Breakdown
✅ Code again:
js
Copy code
function getCarsByMake(make) {
return [Link](x => [Link] === make);
}
js
Copy code
getCarsByMake("Toyota");
Now:
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](...)
js
Copy code
x => [Link] === make
This arrow function is passed into .filter(), and used later as .filter() loops
through the array.
js
Copy code
x => [Link] === make
So what happens?
💡 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
the x => [Link] === make function still has access to make, because it
was created inside that scope.
● 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:
Copy code
function getCarsByMake(make) {
● Filters a global cars array to only return cars that match that make
js
Copy code
const cars = [
];
js
Copy code
[Link](getCarsByMake('Toyota'));
🧾 Expected Output:
js
Copy code
🔍 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.
Copy code
function makePerson(name) {
return {
};
🧠 What’s happening:
✅ Meaning:
✅ So:
● 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");
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)
};
}
js
Copy code
setName: (newName) => privateSetName(newName)
✅ Example:
js
Copy code
const person = makePerson("Ali");
[Link]([Link]()); // "Ali"
[Link]([Link]()); // "Zara"
So if you try:
js
Copy code
[Link]("Hack"); // ❌ Error: not a function
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.
[Link]('click', function () {
alert(`Hello, ${name}`);
});
[Link](button);
}
[Link] = function () {
setupButton('Humera');
};
</script>
</head>
<body></body>
</html>
💡 What It Does:
2. setupButton:
○ Creates a <button>.
○ This callback displays an alert: “Hello, Humera” when the button is clicked.
javascript
Copy code
function setupButton(name) {
const button = [Link]('button');
[Link] = `Click me: ${name}`;
setupButton('Humera');
🔸 1. Closure
A closure is when a function “remembers” the variables from its outer scope even after the
outer function has finished executing.
● 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:
🔸 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.
✔️Correct — The function takes a parameter name, creates a button, and registers a click
handler (anonymous function).
"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.
✔️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.
● 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;
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.
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.
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.
✅ What’s Happening:
● Even though outer() has finished executing, the function inner still remembers x =
2.
🟩 Blanks Filled:
✅ 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)?
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.
● This means:
let x = 1;
function foo() {
[Link](x);
}
function bar() {
let x = 2;
foo(); // In dynamic scoping, this would log 2
}
bar();
● foo() logs x.
● With dynamic scoping, it looks up the call stack to find the nearest x.
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;
};
➡️Output: 2
"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
Here, we define a function outer() inside which we define another function inner().
When outer() is called, it returns inner().
js
CopyEdit
const x = 2;
};
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.
● 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.
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
isFive(5); // true
isFive(6); // false
Then again:
js
CopyEdit
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.
● 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:
CopyEdit
● function foo(a) {
● return function(b) {
● return a === b;
● };
● }
js
CopyEdit
● A context is created.
● 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 x = 2;
const y = 1;
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.
● 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.
js
CopyEdit
const x = 2;
return inner;
};
💡 Now HUGE and bar are not even declared — they are excluded from the closure’s
scope.
✓ inner function forms a closure over the variables it uses or might need.
✓ inner uses only x, and NOT HUGE directly.
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.
Summary:
● 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.
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.
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.
Closures:
● A closure is when an inner function remembers variables from its outer function
even after the outer function has finished executing.
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.
js
CopyEdit
/**
* Function: debounce
* -------------------
* Parameters:
* Returns:
*/
● When you call this new function repeatedly, it postpones running the original
function until the calls stop for at least the delay period.
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
● 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.
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.
Copy code
let timeout;
return function () {
}, waitTime);
};
🔍 Explanation:
● 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.
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.
Copy code
[Link]('app')
Here, we:
2. User clicks again before time is up: Old timer is cleared, a new one is set.
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.
[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.
✅ Full Code:
js
Copy code
const throttle = (func, duration) => {
let shouldWait = false;
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;
✅ Returned Function:
js
Copy code
return (...args) => {
if (!shouldWait) {
[Link](null, args);
shouldWait = true;
setTimeout(() => {
shouldWait = false;
}, duration);
}
};
[Link]("btn").addEventListener("click",
throttle(function () {
counter++;
[Link]("clickCount").innerText = "Click Count: "
+ counter;
}, 1000)
);
● 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);
}
js
CopyEdit
const throttledGreet = throttle(greet, 1000);
throttledGreet("Alice"); // "Hello, Alice"
js
CopyEdit
[Link](null, args);
translates to:
js
CopyEdit
[Link](null, ["Alice"]);
which logs:
CopyEdit
Hello, Alice
○ Scroll events
○ Resize events
○ Input events
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.
Key Concept:
js
Copy code
if (enoughTimePassed) {
runFunction();
If the required wait time has not passed since the last execution, ignore the new
trigger.
Copy code
let lastTime = 0;
function throttleExample() {
[Link]("Ball is thrown!");
lastTime = now;
} else {
Concept:
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
mainFunction(...args);
timerFlag = null;
}, delay);
};
Concept:
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
if (!shouldWait) {
[Link](null, args);
shouldWait = true;
setTimeout(() => {
shouldWait = false;
}, duration);
};
};
Concept:
This version is often easier to understand for beginners and cleanly manages
function access timing.
● 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.
✅ 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.
Copy code
✅ Key Concept:
Copy code
if () {
[Link](arr[i]);
✅ Key Concept:
● 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.
Copy code
✅ Parameters:
● accumulator: Carries the result as it loops.
Copy code
if () [Link](curr);
return acc;
}, []);
● reduce() is very powerful and flexible—you can build almost anything with it.
● Best for custom accumulations like sums, averages, flattening arrays, etc.
🔹 5. Higher-Order Functions (HOF)
✅ What are HOFs?
● Functions that either:
○ Return a function
✅ Why Important?
● They allow modularity, reuse, and functional programming patterns.
✅ Examples:
js
Copy code
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.
● 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.
🧠 Key Concept:
Avoid leaking state outside functional scopes. Functional programming favors pure
functions that don’t depend on or modify shared state.
● Each call gets a fresh new seen Set, isolated from others.
✅ Benefits:
🧠 Key Concept:
Closures help encapsulate logic and state. Every call to a factory function can return a new
function with its own preserved environment.
js
CopyEdit
const uniqueUsingReduce = [Link]((acc, cur) => {
if () [Link](cur);
return acc;
}, new Set());
VS
js
CopyEdit
const uniqueNumbers = [Link](createUniqueReducer(), []);
🧠 Key Concept:
● Both remove duplicates.
var g = f(7);
[Link](g(5)); // Output: -2
🧠 Key Concept:
● Higher-order function (HOF): A function returning another function.
This is similar to currying, where functions are broken into smaller, unary functions.
💡 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;
};
[Link](add2(3)); // 5
b = 2;
x = bar();
📌 What happens?
🧠 Key Concept:
● JavaScript uses lexical (static) scoping.
● b inside foo refers to the global b, which is 2, not the one inside bar.
b = 2;
🔍 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).
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;
};
🔍 Advantage:
function createLoginAttemptTracker() {
let attempts = 0;
return function() {
attempts++;
if (attempts > 3) {
[Link]('Account locked!');
} else {
};
✅ Concept Used:
● Every function call shares the same attempts variable scoped in the closure.
CopyEdit
function createUniqueCollector() {
const seen = new Set();
return function(value) {
if () {
[Link](value);
return true;
return false;
};
🔍 Explanation:
CopyEdit
function createMemoizedSquare() {
if (cache[n]) {
return cache[n];
const result = n * n;
cache[n] = result;
[Link]('calculated:', result);
return result;
};
✅ Concept Used:
CopyEdit
npm init -y
npm install express cors
json
CopyEdit
"type": "module"
Then run:
bash
CopyEdit
🔹 Backend: [Link]
js
CopyEdit
[Link](cors());
[Link]('/api/shared-posts', getSharedPosts);
[Link](5000, () => {
});
🧠 Concept:
🔹 [Link]
js
CopyEdit
const shares = [
];
createUniqueReducer('userId', 'postId'),
[]
);
[Link](uniqueShares);
};
🔹 [Link]
js
CopyEdit
if () {
[Link](key);
[Link](item);
return acc;
};
✅ Concept:
🔹 Project Setup
bash
CopyEdit
cd remove-duplicates
npm install
CopyEdit
return (
<div className="App">
<h1>Shared Posts</h1>
<ul>
<li key={index}>
</li>
))}
</ul>
</div>
);
CopyEdit
useEffect(() => {
fetch('[Link]
}, []);
✅ Concept:
● Connects to backend.
✅ 4. String
javascript
CopyEdit
let d = "hello";
[Link](typeof d); // "string"
let f;
[Link](typeof f); // "undefined"
✅ 8. Undeclared variable
● string
● number
● boolean
● bigint
● symbol
● null
● undefined
● object
All other complex types like arrays, functions, sets, and maps are just different
types of objects.
● object
● function
● null, undefined
● Symbols
● BigInts
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
}
null false
0 false
NaN false
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
undefined "undefined"
null "null"
NaN "NaN"
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]"
undefined NaN
true 1
String (numeric) Parsed number
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
Example:
alert("5" + 2); // "52
Example:
[Link]("apple" < "banana"); // true
[Link]("abc" < "abcd"); // true
Examples:
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
Example:
[Link](!""); // true (empty string is falsy)
● If A is falsy, it returns A.
● If A is truthy, it returns B.
var person = {
name: "Lara",
age: 22
};
[Link] = true;
[Link] = "hello";
[Link] = "Hi";
var o2 = {
p1: 5 + 9,
p2: null,
No, plain JavaScript objects are not iterable with for...of — only with for...in.
[Link](user[key]); // Lara, 22
[Link](function(num) {
[Link](num); // 1, 2, 3
});
You hand these bowls to someone (param1 and param2) and ask them to:
So:
You modify the contents of bowl1 (which both o1 and param1 point to).
Now:
"Hey, stop using your old bowl (o2). Use the same bowl as param1 now (which is
o1)."
Now:
🧠 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).
● Every JavaScript function can act as a constructor when called with the new
keyword.
○ The this keyword inside the function refers to this new object.
[Link] = null;
[Link] = null;
[Link] = value;
[Link] = function() {
};
[Link] = node2;
● The created objects node1 and node2 are called instances of BTNode.
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]
○ Remove elements:
push(element)
Adds an element to the end of the array and returns the new length.
Example:
pop()
Removes the last element and returns it.
Example:
let arr = [1, 2, 3];
shift()
Removes the first element and returns it, shifting all others down by one.
Example:
let arr = [1, 2, 3];
Sure! Here are the key points from the content in simple terms:
● 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.
Example:
var x = 10;
[Link](window.x); // Outputs: 10
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.
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";
2. concat(string)
● What it does: Joins (concatenates) the original string with another string provided as an
argument, returning a new combined string.
Example
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:
○ 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";
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";
5. slice(start, end)
● What it does: Returns a substring starting from start index up to (but not including)
the end index.
● Details:
Example:
let str = "hello";
6. toLowerCase()
● What it does: Returns a new string with all uppercase characters converted to
lowercase.
Example:
let str = "HELLO";
7. toUpperCase()
● What it does: Returns a new string with all lowercase characters converted to
uppercase.
Example:
let str = "hello";
● 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.
var testVar;
✅ Explanation
● Otherwise, it prints "defined" — which means the variable has some value (even
null would be treated as "defined").
✅ Example Code
[Link]("undefined");
} else {
[Link]("defined");
[Link]("undefined");
} else {
[Link]("defined");
defined
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;
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.
function duh() {
duh();
● 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"
Copy code
Number("007") == "007"
✅ What is Being Asked?
We are being asked to evaluate whether:
🔍 Step-by-Step Breakdown
▶️Step 1: Number("007")
● "007" is a string.
So:
Number("007") === 7 ✅
7 == "007"
● A number (7)
● A string ("007")
Because we're using == (the loose equality operator), type coercion happens.
So:
"007" → 7
Then:
7 == 7 → true
✅ Given Code:
o1.j = 9;
var o2 = o1;
function test(o1) {
o1.j = 10;
return;
test(o1);
[Link](o2.j);
🔍 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;
function test(o1) {
o1.j = 10;
return;
When we call:
test(o1);
● So modifying o1.j = 10; actually updates the object shared by both o1 and o2.
[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:
[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:
🧠 Step-by-Step Explanation
▶️Step 1: Evaluate weird
● JavaScript slice(start, end) extracts characters from index start up to but not
including end.
● "father".slice(4, 6) → "er"
Which gives:
In JavaScript:
● So it executes:
✅ Final Output:
A browser popup alert appears with the message:
📌 Original Expression:
a = b ? z /= y ? x : w ? v : u : d += e
● Assignment: =, +=, /=
● Ternary (conditional): ? :
This can get confusing without parentheses. Your goal is to insert parentheses to make the
precedence and associativity explicit.
So:
● The expression is full of nested ternary and assignment operations, so we’ll need to
disambiguate it carefully.
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.
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.
🔍 Key Points:
● 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.
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;
let overflowed = (a * b) | 0;
● (a * b) gives 2500000000, which is bigger than the max 32-bit signed int
(2,147,483,647).
● 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:
● It acts like a "no-op" bitwise operation but forces JavaScript to convert the value to 32-
bit signed int as a side effect.
● 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;
● Inside the addTo function, you're trying to use myVar without declaring 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) {
return;
[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.
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;
[Link] = rusty;
[Link] = [Link];
[Link](1);
[Link](2);
🔍 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
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);
● So o1.x = 1 is assigned.
5. Calling [Link](2)
[Link](2);
● So o2.x = 2 is assigned.
6. Final Alert
● o2.x is 2
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).
● 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 = [
];
drawGrid(ttt);
-----
O|X|O
-----
O|X|X
✅ Solution Code:
function drawGrid(array) {
if (i < [Link] - 1) {
alert(output);
💡 Explanation:
● "-----" separates the rows — you could dynamically calculate the length if rows vary
in size.
let ragged = [
['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.
📌 Example:
✅ JavaScript Code:
function median(arr) {
// Make a shallow copy to avoid modifying the original array
[Link](function(a, b) {
return a - b;
});
return copy[midIndex];
🧠 Explanation:
🔢 Example Array:
javascript
Copy code
[Link](function(a, b) { return a - b; });
The sort() function compares pairs of elements and uses the result of a - b to decide the
order.
● a = 7, b = 2
● a - b = 7 - 2 = 5 → positive
● a = 7, b = 5
● a - b = 2 → positive
● a = 2, b = 5
● a - b = -3 → negative
[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
1234567890
🧠 Approach Explanation
We need a regular expression that matches all the above formats.
Let’s break it down:
(123)456- ^\(\d{3}\)\d{3}-\
7890 d{4}$
123/456- ^\d{3}/\d{3}-\d{4}$
7890
123-456- ^\d{3}-\d{3}-\d{4}$
7890
1234567890 ^\d{10}$
We can combine all these options using the | (OR) operator inside a regular expression.
function isValid(phone) {
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("1234567890")); // true
[Link](isValid("123.456.7890")); // false
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:
aural For devices that read text out loud, like a speech assistant.
braille For braille devices that let blind people read by touch.
EXAMPLE:
<head>
</head>
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.
✅ 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).
.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.
What happens:
The browser gives more power (priority) to certain rules:
● ID selectors
● Class selectors
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>
<style>
p {
.highlight {
#mainText {
}
p {
</style>
</head>
<body>
</body>
</html>
The browser gathers all the CSS rules from the <style> tag and the inline style.
● All rules are from the same origin (the author's style).
3. Specificity:
● If it didn’t exist:
● If rules had the same specificity, the one that appears last would win.
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
○ 2em = 32px
○ 0.5em = 8px
✅ ex
🔁 Example:
body {
font-size: 20px;
p {
Here:
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 {
width: 200px;
</style>
</head>
<body>
<div class="box">
</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.
○ The browser’s client area height, or the height of the canvas — whichever is larger.
In this image:
● The height of the canvas (dashed box) is greater than the height of the browser
client area.
● 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:
○ Paragraphs
○ Images
● 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).
🔹 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;
●
● ✅ 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.
div {
background-color: silver;
strong {
font-size: larger;
✅ Explanation:
● This applies silver background to all <div> elements.
p, em {
background-color: silver;
font-size: larger;
✅ Explanation:
● This rule applies both declarations to both <p> and <em> elements.
#Nevada,
.shiny {
background-color: silver;
✅ Explanation:
[Link] {
font-size: larger;
✅ Explanation:
● [Link] means an element must be a span and must have the class bigger.
span span {
font-size: larger;
✅ Explanation:
● It ensures the font-size only increases for nested spans, not the outermost one.
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.
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.
● Creating 3 external style sheets with subsets of style rules from Exercise 3.1
○ Uses @import
■ Alternate
■ Print-specific
/* [Link] */
@import url("[Link]");
div {
background-color: silver;
strong {
font-size: larger;
/* [Link] */
@import url("[Link]");
p, em {
background-color: silver;
font-size: larger;
#Nevada,
.shiny {
background-color: silver;
/* [Link] */
[Link] {
font-size: larger;
span span {
font-size: larger;
a:hover {
background-color: silver;
"[Link]
<head>
<!-- Preferred and persistent style sheet (style1 imports style2 and
style3) -->
</head>
<body>
<div>
</div>
</body>
</html>
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.
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>
<style type="text/css">
*{
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</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:
● Specificity
● Inheritance
2 User normal
3 Author normal
4 Author !
important
5 (highest) User !
important
p {
color: green;
font-size: smaller !important;
p {
color: white;
background-color: black;
● color
● background-color
● font-size
➤ 1. color of <p>
Competing Rules:
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:
➤ 3. font-size of <p>
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.
Element color
<div> blue
<div fuchsia
class="hmm">
<body>
<ol>Item</ol>
</body>
● color is inherited.
Author none —
➤ If <body class="hmm">?
But .hmm is from the author, color: fuchsia, and has no !important.
Situation color
<body yellow
class="hmm">
This means every element gets a default color: black unless overridden.
➤ Re-evaluate (c):
Still:
So:
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.
.quote {
margin: 0 4em;
🟨 2. Better Accessibility
● Absolute units (cm, in, pt) are designed for print, not screens.
.quote {
margin: 0 4em;
🟨 2. Better Accessibility
● Absolute units (cm, in, pt) are designed for print, not screens.
✅ Conclusion:
● They often rely on the device pixel ratio (DPR) to map CSS pixels
to real screen pixels.
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.
✅ Final Answer:
✅ What is DPI?
DPI stands for Dots Per Inch (sometimes also called PPI, Pixels Per Inch).
● 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.
● The frame touches the edges of the image (no space between image and border)
✅ CSS:
img {
border: 5px solid brown; /* Frame */
💡 Explanation:
● A 3px tan gap (mat) between the image and the frame
img {
💡 Explanation:
● padding: 3px creates space between the image and the border.
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.
✅ 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>
● So there's empty space on both sides of the canvas (e.g., 200px on each side).
📌 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.
● em: Relative to the font size (typically the height of the letter "M").
📏 Every font has a clearly defined font height and x-height — reliable for layout
measurements.
❌ 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).
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
● 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.
(ii) A __??__ containing __??__ element is used to group and structure the button
independently.
○ Why? That’s the interactive element inside the <div> that users can click on to
increment the counter.
The variables defined under the :root selector are __??__ (local/global).
"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."
“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.
● CORS lets servers safely share resources (like APIs, images, etc.) with clients hosted on
different domains.
“This indicates that the backend server does not include the appropriate CORS
headers in its response.”
● This error tells you that the API server hasn’t set the correct headers to allow your
request from a different origin
● 🔹 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:
Open-source front-end JavaScript library used for building composable user interfaces,
especially for single-page applications (SPA).
🔹 It is used for handling the view layer in web and mobile apps, based on components in
a:
Declarative manner.
React was created by Jordan Walke, a Facebook software engineer. React was:
It is a virtual copy of the ➤ It's not the real DOM, just a lightweight JS
original DOM version used to compare changes.
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.
After manipulation, it re-renders the ➤ Any change might cause full DOM
entire UI refresh — which is slower.
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.
Week 4
✅ Filled Blanks & Key Points:
● Most importantly for us: the [Link] platform is built on top of V8.
● Today’s JavaScript engines both interpret and compile by employing so-called just-in-
time (JIT) compilation.
● Three of the most well-known languages are TypeScript, CoffeeScript, and Dart.
● JavaScript is a dynamically typed language.
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."
💥 FINAL LINE:
✅ String is primitive, but when you use methods on it, JavaScript treats it like an
object temporarily.
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.
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:
✅ Filled Blanks:
● printName is not shared (each object has its own copy)
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."
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),
✓ 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).
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.
✓ 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 ✅
✅ First part:
✅ Third part:
✅ Fourth part:
3. The ()=>{} accomplishes the same result as a regular function with fewer
lines of code.
✅ Fifth part:
✅ 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:
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.
✅ 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
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.
GET / HTTP/1.1
Host: [Link]
🔁 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.
○ For example:
🌲 3. Render Tree
● The browser combines DOM + CSSOM to build a Render Tree.
● This tree shows only the visible elements with their computed styles.
📌 Example:
● Only Hello and students appear inside p, because span was hidden.
html
CopyEdit
<p>Some text</p>
✅ Tag
Tags are the opening and closing parts of an element.
In the example above:
So:
2. The API on the server receives the request and communicates with:
4. The Front End interprets that data and displays it on the browser.
● 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.
● ✅ 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.
○ Color
○ Transparency
○ Position
○ Sound
html
Copy code
<a href="[Link]">Click me</a>
turns into:
js
Copy code
[Link]('a').href // '[Link]'
mathematica
Copy code
Document
└── Root element: <html>
├── <head>
│ └── <title> → Text: "My title"
└── <body>
├── <h1> → Text: "A heading"
└── <a href="..."> → Text: "Link text"
🎯 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
● 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.
● The server simply checks its file system (just like opening a folder on your PC) and finds
the requested file (e.g., [Link]).
● The server responds with the exact HTML file to the browser.
📝 Important Note:
"Static does not mean that it will not respond to user actions."
● 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.
● This is the user’s device, running a web browser (like Chrome, Firefox, etc.).
🖧 2. Web Server
● 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.
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.
3. If needed, the server queries the database (e.g., “get blog post #5”).
🔹 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:
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.
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).
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.
1. 🔁 Reusable Components
You can build UI elements like buttons, cards, forms as reusable pieces — write once, use
anywhere.
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.
Open-source front-end JavaScript library used for building composable user interfaces,
especially for single-page applications (SPA).
Declarative manner.
🔁 Opposite: Imperative
In imperative programming, you give exact instructions — like a recipe — for how to do
something.
● 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>;
}
React handles the how — like creating the element, attaching the event, adding it to the DOM,
etc.
● 🔄 Less Error-Prone – You don’t manually update DOM; React does it.
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”?
Here’s a breakdown of the main features shown in the image and text on the right:
🔹 JSX Syntax
🔹 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.
Server-side Rendering
● Content gets delivered faster, and it's more crawlable by search engines.
🔍 Key Concepts
Term Meaning
Stateful It can store and manage state (data that can change over time).
■ state
jsx
Copy code
import React, { Component } from 'react';
render() {
return (
<div>
<h2>{[Link]}</h2>
<button onClick={[Link]}>Click Me</button>
</div>
);
}
}
● When you click the button, the state updates via [Link](), and React re-
renders the component with the new message.
● Use state
Now, function components with hooks (like useState, useEffect) are more common—but
class components are still important to learn and understand.
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.
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={handleClick}>Increase</button>
</div>
);
}
Why? Because:
● On that click, the value of count is 0, let’s say.
● The second call sees the updated value (1) and sets it to 2.
function MyComponent() {
// ❌ 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.
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.”
● Effects (useEffect)
function MyComponent() {
};
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:
CopyEdit
function EffectEveryRender() {
useEffect(() => {
return () => {
[Link]('🧹 Cleanup: Before next render or unmount');
};
});
return (
</button>
);
CopyEdit
function EffectOnMountOnly() {
useEffect(() => {
};
}, []);
return (
</button>
);
CopyEdit
function EffectOnCountChange() {
useEffect(() => {
[Link] = `Clicked ${count} times`;
return () => {
};
}, [count]);
return (
</button>
);
jsx
CopyEdit
state = { count: 0 };
componentDidUpdate() {
render() {
return (
</button>
);
jsx
CopyEdit
state = { count: 0 };
componentDidMount() {
componentWillUnmount() {
render() {
return (
</button>
);
jsx
CopyEdit
state = { count: 0 };
componentDidMount() {
componentDidUpdate(prevProps, prevState) {
componentWillUnmount() {
render() {
return (
<button onClick={() => [Link]({ count: [Link] +
1 })}>
</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
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.
javascript
Copy code
setTimeout(function() {
[Link](i);
}, 1000);
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:
● By that time, i has become 11 (because the loop stops when i > 10).
📢 Slide 1:
Js is a single threaded non-blocking asynchrounous concurrent language
● 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.
✅ Example:
javascript
Copy code
● 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);
fn(i);
}
🔹 What's Happening:
1. Function Definition
javascript
CopyEdit
function fn(i) {
setTimeout(function () {
[Link](i);
}, 1000 * i);
● Inside it, we call setTimeout, which delays running the function that logs i to the
console.
2. Loop
javascript
CopyEdit
fn(i);
● This loop goes from i = 1 to i = 10, and calls the function fn(i) each time.
○ ...
YOUSUF PDF:
🔹 The Code:
javascript
CopyEdit
function fn(i) {
setTimeout(function () {
[Link](i);
}, 1000 * i);
fn(i);
🔹 What's Happening:
1. Function Definition
javascript
CopyEdit
function fn(i) {
setTimeout(function () {
[Link](i);
}, 1000 * i);
● Inside it, we call setTimeout, which delays running the function that logs i to the
console.
2. Loop
javascript
CopyEdit
fn(i);
● This loop goes from i = 1 to i = 10, and calls the function fn(i) each time.
○ ...
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.
● 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.
● It saves time and effort because you don't have to code everything from scratch.
You are getting true because in a JavaScript class, methods like printName() are
automatically shared between all instances.
👉 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 Game(n) method is ignored unless you manually call it yourself (which you didn’t).
● What is a prototype?
It’s like a hidden backpack 🎒 that every JavaScript object carries.
This backpack contains useful methods and properties.
● Example:
○ Arrays (like [1, 2, 3]) can use .length, .push(), .map(), etc.
🔥 Quick Summary:
Concept Meaning
● 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";
[Link]([Link]());
● It wraps your primitive "hello" into an object temporarily.
🎯 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!
In JavaScript, any function can act as a constructor when you call it with the new keyword.
function Game(name) {
[Link] = name;
[Link] = function() {
[Link]([Link]);
};
○
○ Example in the image:
● Idea:
○ A copy-like relationship:
Child objects copy properties/methods from parent objects when created.
● Static Binding:
(Orange box in the middle)
○ Method overloading → Methods with the same name but different signatures.
● 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)
○ Runtime → Structure can be flexible and determined when the program runs.
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.
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.
✅ 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.
● 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."
● What happens? — The Model talks to the Database to get or update information.
✅ Example:
The Model sends a request to the Database:
🟡 5. Database
● Who? — Your storage system (SQL, MongoDB, etc.).
✅ Example:
Database finds all matching books and sends the data back to the Model.
"Here is the list of Harry Potter books. Please show them 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.
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.
Behavior:
● Asynchronous loading:
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:
jsx
CopyEdit
state = { count: 0 };
increment() {
render() {
}
✅ Fixed with Arrow Function:
jsx
CopyEdit
state = { count: 0 };
increment = () => {
};
render() {
Use case: Avoids the need for binding this in constructor. Cleaner, shorter, and
less error-prone.
js
CopyEdit
[Link] = name;
[Link] = hobbies;
[Link] = function () {
[Link](function (hobby) {
});
};
[Link]();
js
CopyEdit
[Link] = name;
[Link] = hobbies;
[Link] = function () {
[Link]((hobby) => {
});
};
}
Use case: Arrow functions inherit this from the enclosing function, solving
context issues in callbacks.
js
CopyEdit
class Timer {
start() {
setTimeout(function () {
}, 1000);
js
CopyEdit
class Timer {
start() {
setTimeout(() => {
}, 1000);
● 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.
CopyEdit
state = { count: 0 };
handleClick() {
render() {
return (
<button onClick={[Link]}>
</button>
);
● 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).
jsx
CopyEdit
handleClick = () => {
[Link]({ count: [Link] + 1 });
jsx
CopyEdit
constructor() {
super();
[Link] = [Link](this);
🔁 Summary
🔸 Arrow Function:
Types of Components:
● Functional Component – Written using a function.
CopyEdit
function Navigation() {
return (
<nav>
<li>Home</li>
<li>Blogs</li>
<li>Books</li>
</nav>
);
React doesn’t understand JSX directly. So, it needs to be compiled into regular JavaScript
using tools like Babel.
CopyEdit
After compilation:
js
CopyEdit
🪝 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:
📌 5. useState Hook
Definition:
useState is a hook that allows you to create and manage state in a functional component.
Syntax:
js
CopyEdit
Example:
js
CopyEdit
Example:
js
CopyEdit
// In the render:
useEffect lets you perform side effects like data fetching, updating the DOM, or setting up
subscriptions.
Syntax:
js
CopyEdit
useEffect(() => {
}, []);
CopyEdit
useEffect(() => {
fetch("/api/projects")
.then(data => {
});
}, []);
8. Full Example: React with Fetch API
jsx
CopyEdit
function App() {
useEffect(() => {
fetch("/api/projects")
.then(data => {
setProjects(data);
setLoading(false);
});
}, []);
return (
<div>
<h1>Project List</h1>
</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.
● To share data easily between components without prop drilling (passing props again
and again).
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.
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.