Web Technology IUnit 914 min read
JavaScript Libraries & Frameworks: jQuery, React, Vue, Angular
Unit 9 of Web Technology I explores how JavaScript libraries (like jQuery) and frameworks (React, Vue, Angular) accelerate development, handle DOM manipulation, state management, and component-based architecture—with real-world examples from Nepalese apps and global tech giants.
Core Concepts: Libraries vs. Frameworks
What Are They?
- Libraries: Pre-written JavaScript code snippets (functions, methods) that developers use to extend functionality. They do not dictate project structure.
- Example: jQuery simplifies DOM traversal, animations, and AJAX calls.
- Frameworks: Structured environments that enforce how code should be organized (e.g., MVC, component-based). They provide tools, conventions, and often a build system.
- Example: React enforces a component-based architecture with lifecycle methods.
classDiagram
class Library {
+Pre-written code
+Extends functionality
+No project structure
+Examples: jQuery, Lodash
}
class Framework {
+Structured environment
+Enforces architecture (MVC, components)
+Build tools included
+Examples: React, Angular, Vue
}
Library --> Framework : "Frameworks often include libraries"Why Use Them?
| Libraries | Frameworks |
|---|---|
| Faster development for small tasks | Full control over app architecture |
| Lightweight, no opinionated structure | Built-in tools (routing, state management) |
| Example: DOM manipulation with jQuery | Example: Single-page apps with React |
1. jQuery: The DOM Manipulation Workhorse
How It Works
jQuery is a library that simplifies:
- DOM traversal and manipulation (e.g.,
$("#myButton").click()). - AJAX requests (e.g.,
$.get("api/data", callback)). - Animations (e.g.,
$("#box").fadeOut()). - Cross-browser compatibility (handles IE quirks).
sequenceDiagram
participant User
participant Browser
participant jQuery
participant DOM
User->>Browser: Clicks button
Browser->>jQuery: Triggers $(document).ready()
jQuery->>DOM: $("#submitBtn").on("click", function(){...})
DOM-->>jQuery: Event fired
jQuery->>Browser: Updates UI dynamicallyReal-World Example: eSewa’s Dynamic Forms
eSewa uses jQuery to:
- Validate user inputs without page reload (e.g., checking if a phone number exists before proceeding).
- Dynamically update transaction fees based on selected services (e.g., electricity bill payment).
- Handle AJAX calls to fetch user balances from NTC/Ncell APIs.
Worked Example: Live Search on Daraz
// jQuery AJAX for Daraz’s search-as-you-type
$("#searchInput").on("keyup", function() {
$.ajax({
url: "https://api.daraz.com/search",
data: { query: $(this).val() },
success: function(results) {
$("#suggestions").html(results.map(item => `<div>${item.name}</div>`).join(""));
}
});
});
Visual:
stateDiagram-v2
[*] --> UserTypes: User types in search box
UserTypes --> jQueryListens: jQuery triggers "keyup"
jQueryListens --> AJAXRequest: Sends query to Daraz API
AJAXRequest --> APIResponds: Daraz returns JSON results
APIResponds --> UpdateUI: jQuery updates suggestions list
UpdateUI --> [*]2. React: Component-Based UI Development
Key Features
- Virtual DOM: Efficiently updates only changed parts of the UI.
- Components: Reusable UI pieces (e.g.,
<Button>,<UserProfile>). - JSX: HTML-like syntax inside JavaScript (compiled to
React.createElement()). - State Management: Uses
useState/useReducerhooks for dynamic data.
Real-World Example: Pathao’s Rider App
Pathao’s rider interface uses React to:
- Dynamically update ride status (e.g., "Pickup in 2 mins" → "On the way").
- Render a live map with rider location (using
useEffectto fetch GPS updates). - Handle real-time chat with customers via WebSocket + React state.
Worked Example: Traffic Light Simulation
function TrafficLight() {
const [color, setColor] = useState("red");
useEffect(() => {
const timer = setInterval(() => {
setColor(prev => prev === "red" ? "green" : "yellow");
}, 3000);
return () => clearInterval(timer); // Cleanup
}, []);
return <div style={{ color }}>{color}</div>;
}
Visual:
stateDiagram-v2
[*] --> Red: Initial state (red)
Red --> Green: After 3s (setInterval)
Green --> Yellow: After 3s
Yellow --> Red: After 3s
Red --> [*]3. Vue.js: Progressive Framework
Why Vue?
- Reactivity System: Automatically tracks data changes (no manual
setState). - Single-File Components (SFC):
.vuefiles combine HTML, JS, and CSS. - Lightweight: ~20KB gzipped (ideal for mobile apps like Khalti).
erDiagram
USER ||--o{ ORDER : places
ORDER ||--|{ ITEM : contains
ITEM {
string name
number price
number quantity
}
ORDER {
string orderId
datetime timestamp
string status "pending/shipped/delivered"
}
USER {
string userId
string name
string email
}How Khalti Uses Vue:
- Real-time transaction status: Vue’s reactivity updates the UI when a payment is processed (e.g., "₹500 sent to [User]").
- Dynamic form validation: Input fields highlight errors instantly (e.g., "Invalid card number").
Worked Example: Live Order Tracking
<template>
<div>
<p>Status: {{ orderStatus }}</p>
<progress :value="progress" max="100"></progress>
</div>
</template>
<script>
export default {
data() {
return {
orderStatus: "Processing",
progress: 0
};
},
mounted() {
setInterval(() => {
this.progress += 10;
if (this.progress >= 100) this.orderStatus = "Delivered!";
}, 1000);
}
};
</script>
4. Angular: Full-Fledged Framework
Architecture: MVC + Dependency Injection
- Components: Control UI (like React/Vue).
- Services: Handle business logic (e.g.,
AuthService,PaymentService). - Modules: Group related components (e.g.,
DashboardModule,AdminModule). - Dependency Injection (DI): Manages service lifecycle (e.g.,
@Injectable()).
classDiagram
class AppComponent {
+title: string
+components: Component[]
}
class AuthService {
+login(email, password): Promise~User~
+logout(): void
}
class UserService {
+getUser(id): Promise~User~
}
AppComponent --> AuthService : "Uses for login"
AppComponent --> UserService : "Uses for data"
AuthService ..> UserService : "Depends on"Real-World Example: NEPSE’s Stock Dashboard
Angular powers NEPSE’s:
- Real-time stock ticker: WebSocket integration to update prices instantly.
- Modular UI: Separate modules for "Market Data," "Trading," and "Analytics."
- Form validation: Ensures trade orders meet exchange rules (e.g., lot size constraints).
Worked Example: Loan Calculator (Banking App)
@Component({
selector: 'loan-calculator',
template: `
<input [(ngModel)]="principal" placeholder="Loan Amount">
<input [(ngModel)]="rate" placeholder="Interest Rate (%)">
<p>Monthly Payment: {{ calculatePayment() }}</p>
`
})
export class LoanCalculator {
principal: number;
rate: number;
calculatePayment() {
const monthlyRate = this.rate / 100 / 12;
return (this.principal * monthlyRate) / (1 - Math.pow(1 + monthlyRate, -12));
}
}
Comparison Table: Libraries vs. Frameworks
| Feature | jQuery (Library) | React (Framework) | Vue.js (Framework) | Angular (Framework) |
|---|---|---|---|---|
| Type | Library | Framework | Framework | Framework |
| Learning Curve | Low | Moderate | Low-Moderate | High |
| DOM Handling | Direct manipulation | Virtual DOM | Virtual DOM | Real DOM (with change detection) |
| State Management | None (use external) | Hooks (useState) |
data() + computed |
Services + RxJS |
| Build Tools | None | Create React App | Vue CLI | Angular CLI |
| Use Case | Quick DOM tasks | SPAs, dynamic UIs | Progressive enhancement | Enterprise apps |
| Nepalese Example | eSewa forms | Pathao rider UI | Khalti transactions | NEPSE dashboard |
In the Real World
eSewa (Nepal)
- jQuery: Handles dynamic form validation for bill payments (e.g., electricity, phone) without page reloads. When you type your NTC customer ID, jQuery sends an AJAX request to eSewa’s backend to pre-fill your details.
- How it works: The
$.ajax()call fetches user data from eSewa’s API, and jQuery updates the DOM with<input>values likename,address, andcurrent_balance.
Pathao (Nepal/Global)
- React: Powers the rider app’s real-time order updates. When a customer books a ride, React’s
useEffecthook listens for WebSocket messages (e.g.,"order:accepted","ride:started"), and the UI updates instantly. - Example: The
orderStatusstate changes from"waiting"to"on_the_way"when the rider accepts the trip, triggering a re-render of the<OrderStatus>component.
- React: Powers the rider app’s real-time order updates. When a customer books a ride, React’s
Khalti (Nepal)
- Vue.js: Used for its lightweight, reactive UI during transactions. When you transfer ₹500 to a friend, Vue’s reactivity system ensures the "Processing..." text updates to "₹500 sent to [Friend]" as soon as the backend confirms the transaction.
- Key feature: Vue’s
v-ifandv-showdirectives dynamically hide/show elements (e.g., the "Confirm Payment" button disappears after clicking).
NEPSE (Nepal Stock Exchange)
- Angular: Builds the stock trading platform’s modular UI. Traders see real-time price updates (via WebSocket) in the "Market Data" module, while the "Trading" module uses Angular’s forms to validate orders (e.g., ensuring you don’t buy fractional shares).
- Architecture: Angular’s dependency injection manages services like
AuthService(for login) andTradeService(for order execution).
Global: YouTube (React)
- React: Used for the video player’s dynamic UI (e.g., "Like" button toggling, comments loading as you scroll). The
useStatehook tracks whether a video is "liked," and the Virtual DOM ensures only the button’s icon updates.
- React: Used for the video player’s dynamic UI (e.g., "Like" button toggling, comments loading as you scroll). The
Exam Tip
What to Expect in TU/PU Exams
Definitions & Differences
- Expect questions like:
- "Differentiate between a JavaScript library and a framework with examples."
- "Why does React use a Virtual DOM? Explain with a diagram."
- Answer tip: Use the comparison table above and draw a Virtual DOM vs. Real DOM mermaid diagram in your exam.
- Expect questions like:
Code Snippets & Outputs
jQuery: You may be given a snippet and asked to predict the DOM change or AJAX response. Example:
$("#userList").append(`<li>${user.name}</li>`);Question: What HTML is added to
#userList? Answer:<li>John Doe</li>(ifuser.name = "John Doe").React/Vue: Trace state changes. Example:
const [count, setCount] = useState(0); function increment() { setCount(count + 1); }Question: What is
countafter two clicks? Answer:2(state updates are asynchronous but resolved in order).
Real-World Applications
- Questions may ask:
- "How does Pathao use React to update rider status in real-time?"
- "Explain how Khalti’s Vue.js reactivity works during a payment."
- Answer tip: Tie your explanation to the sequence diagrams or state diagrams shown earlier (e.g., Pathao’s WebSocket → React state flow).
- Questions may ask:
Diagrams
- Must-draw diagrams:
- Layered architecture of React (Virtual DOM → Real DOM).
- Component hierarchy (e.g., Angular modules or React’s
<App>→<Header>→<Button>). - State transition (e.g., Vue’s
data()changes or React’suseEffectlifecycle).
- Example prompt: "Draw the flow of data in a React component when a user clicks a button."
- Must-draw diagrams:
Shortcomings & Use Cases
- "What are the limitations of jQuery in modern SPAs?"
Answer:
- No built-in state management (requires Redux or Vuex).
- Poor performance for complex UIs (direct DOM manipulation).
- Lacks component-based architecture.
- "When would you choose Vue.js over React?"
Answer:
- For progressive enhancement (e.g., adding interactivity to a static site).
- Smaller bundle size (better for mobile apps like Khalti).
- Simpler learning curve for beginners.
- "What are the limitations of jQuery in modern SPAs?"
Answer:
Common Pitfalls to Avoid
Confusing Libraries and Frameworks
- ❌ "Angular is a library." → Wrong. It’s a framework with built-in libraries (e.g.,
@angular/common). - ✅ "jQuery is a library that simplifies DOM tasks."
- ❌ "Angular is a library." → Wrong. It’s a framework with built-in libraries (e.g.,
Overlooking Virtual DOM
- ❌ "React updates the entire DOM on state change." → Wrong. It uses a Virtual DOM to minimize real DOM updates.
- ✅ "React’s Virtual DOM diffs changes and patches only the updated nodes."
Ignoring Real-World Context
- ❌ "React is only for large apps." → Wrong. It’s used in small projects (e.g., a personal portfolio) and enterprise apps (e.g., NEPSE).
- ✅ "React’s component model scales from small UIs (like a counter) to complex SPAs (like Pathao’s rider app)."
Mixing Syntax
- ❌ Using jQuery syntax in React:
// Wrong in React $("#myDiv").html("<h1>Hello</h1>"); - ✅ Use React’s JSX:
// Correct <div><h1>Hello</h1></div>
- ❌ Using jQuery syntax in React:
Summary Checklist
Before your exam, ensure you can:
- Define libraries vs. frameworks with examples (jQuery, React).
- Draw a Virtual DOM diagram and explain its advantage.
- Trace state changes in React/Vue (e.g.,
useState,data()). - Explain how jQuery handles AJAX and DOM events.
- Compare React, Vue, and Angular in a table (use the one above).
- Describe real-world uses in Nepalese apps (eSewa, Pathao, Khalti, NEPSE).
- Write a simple component in React/Vue (e.g., a counter or traffic light).
- Identify when to use each tool (e.g., jQuery for quick fixes, React for SPAs).
Based on the TU BIM syllabus for Web Technology I (IT237), unit 9.
Discussion
Loading…