Web Technology IUnit 912 min read
JavaScript Libraries & Frameworks: jQuery, React, Vue, Angular
Unit 9 of Web Technology I introduces students to JavaScript libraries and frameworks—jQuery, React, Vue.js, and Angular—explaining their purpose, differences, and practical applications in modern web development, with real-world examples and code comparisons.
TAKEAWAYS:
- JavaScript libraries (like jQuery) and frameworks (like React) extend vanilla JS to simplify DOM manipulation, state management, and component-based architecture.
- jQuery is a lightweight library for DOM traversal and effects, while React, Vue, and Angular are full frameworks for building dynamic single-page applications (SPAs).
- React uses a virtual DOM and hooks for state management, Vue combines simplicity with reactivity, and Angular enforces structure with TypeScript and modules.
- Libraries/frameworks reduce boilerplate code, improve performance, and enable reusable components—critical for scalable web apps.
- Real-world use cases include eSewa’s form validations (jQuery), Pathao’s real-time ride tracking (React), and Khalti’s secure payment flows (Angular).
- Exam questions often ask for code snippets (e.g., jQuery selectors, React hooks) or comparisons between frameworks.
Why Use Libraries and Frameworks?
Vanilla JavaScript works, but writing everything from scratch is tedious. Libraries and frameworks abstract repetitive tasks (e.g., DOM updates, AJAX calls, routing) and enforce best practices. For example:
- jQuery simplifies DOM manipulation (e.g.,
$("#submit").click()instead ofdocument.getElementById("submit").addEventListener("click", ...)). - React/Vue/Angular manage application state and render UI dynamically (e.g., updating a cart total without page reloads).
1. JavaScript Libraries vs. Frameworks
Libraries and frameworks both extend JavaScript, but they differ in scope and control:
classDiagram
class Library {
+Lightweight
+Reusable functions
+No opinionated structure
+Examples: jQuery, Lodash
}
class Framework {
+Full-fledged architecture
+Opinionated (e.g., MVC in Angular)
+Includes routing, state management
+Examples: React, Vue, Angular
}
Library --> "Uses" Framework : "Can be integrated into"
note for Library "Extends JS\nNo forced structure"
note for Framework "Controls app flow\nEnforces patterns"Key Differences:
| Feature | Library (e.g., jQuery) | Framework (e.g., React) |
|---|---|---|
| Scope | Modular, plug-and-play | Full application architecture |
| Control | Developer writes logic | Framework dictates structure |
| Learning Curve | Low | Moderate to high |
| Use Case | DOM manipulation, AJAX | SPAs, complex UIs, state management |
2. Popular Libraries and Frameworks
A. jQuery: The DOM Swiss Army Knife
What it does:
- Simplifies DOM traversal, animations, and AJAX calls.
- Example: Hide/show elements with
.hide()/.show()or animate fades.
How it works:
// Vanilla JS
document.getElementById("btn").addEventListener("click", function() {
document.querySelector(".box").style.display = "none";
});
// jQuery
$("#btn").click(function() {
$(".box").hide(); // Chaining: .hide().fadeOut()
});
Real-world use:
- eSewa’s form validations: jQuery validates inputs (e.g., phone number format) before submission.
- NTC’s service request portal: Uses jQuery to toggle dropdown menus dynamically.
Advantages:
- Cross-browser compatibility (handles IE quirks).
- Concise syntax for common tasks.
Disadvantages:
- Slower than modern JS (no virtual DOM).
- Less suitable for complex SPAs.
B. React: The Virtual DOM Pioneer
What it does:
- Uses a virtual DOM to optimize rendering (only updates changed parts).
- Components are reusable UI building blocks.
Core Concepts:
- Components: Self-contained UI pieces (e.g.,
Button,UserCard). - State: Managed via
useStateoruseReducerhooks. - Props: Data passed from parent to child components.
Example: Counter App
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
Real-world use:
- Pathao’s ride tracker: React updates the map and rider location in real-time without full page reloads.
- Daraz’s product filters: React dynamically re-renders search results as users toggle categories.
Advantages:
- High performance (virtual DOM diffing).
- Component-based reusability.
Disadvantages:
- Steeper learning curve (JSX, hooks).
- Requires additional tools (e.g., Redux for global state).
C. Vue.js: The Progressive Framework
What it does:
- Combines simplicity with reactivity (data binds to DOM automatically).
- Uses a directive system (e.g.,
v-if,v-for).
Example: Todo List
<div id="app">
<input v-model="newTodo" @keyup.enter="addTodo">
<ul>
<li v-for="todo in todos" :key="todo.id">
{{ todo.text }}
</li>
</ul>
</div>
<script>
new Vue({
el: '#app',
data: { todos: [], newTodo: '' },
methods: {
addTodo() {
this.todos.push({ text: this.newTodo, id: Date.now() });
this.newTodo = '';
}
}
});
</script>
Real-world use:
- Khalti’s payment success page: Vue updates the transaction status dynamically.
- Nepal Police’s emergency alert system: Vue renders real-time alerts without page refreshes.
Advantages:
- Gentle learning curve (HTML-like templates).
- Flexible (can adopt incrementally).
Disadvantages:
- Smaller ecosystem than React/Angular.
D. Angular: The Full MVC Framework
What it does:
- Enforces MVC (Model-View-Controller) architecture.
- Uses TypeScript for type safety and modules for organization.
Example: Service Injection
// service.ts
@Injectable()
export class DataService {
getData() { return "Hello from Angular!"; }
}
// component.ts
@Component({
selector: 'app-root',
template: `<h1>{{ data }}</h1>`
})
export class AppComponent {
data: string;
constructor(private dataService: DataService) {
this.data = dataService.getData();
}
}
Real-world use:
- Ncell’s billing portal: Angular manages user authentication and subscription data.
- NEPSE’s stock dashboard: Angular handles real-time stock price updates.
Advantages:
- Structured (scalable for large apps).
- Two-way data binding (
[(ngModel)]).
Disadvantages:
- Steep learning curve (TypeScript, RxJS).
- Verbose setup.
3. How to Choose?
Use this flowchart to decide:
flowchart TD
A["Need a quick solution?"] -->|"Yes"| B["Use jQuery"]
A -->|"No"| C["Building a SPA?"]
C -->|"Yes"| D["Need simplicity?"]
D -->|"Yes"| E["Vue.js"]
D -->|"No"| F["Need scalability?"]
F -->|"Yes"| G["React or Angular"]
F -->|"No"| E
C -->|"No"| H["Use vanilla JS or a library"]4. Worked Example: Form Validation with jQuery vs. React
Scenario: Validate a signup form for Khalti’s user registration (phone, email, password).
jQuery Solution
<form id="signupForm">
<input type="text" id="phone" placeholder="Phone">
<input type="email" id="email" placeholder="Email">
<input type="password" id="password" placeholder="Password">
<button type="submit">Sign Up</button>
</form>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$("#signupForm").submit(function(e) {
e.preventDefault();
const phone = $("#phone").val();
const email = $("#email").val();
const password = $("#password").val();
if (!/^\d{10}$/.test(phone)) {
alert("Invalid phone number!");
return;
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
alert("Invalid email!");
return;
}
if (password.length < 6) {
alert("Password too short!");
return;
}
alert("Form submitted!");
});
});
</script>
React Solution
import { useState } from 'react';
function SignupForm() {
const [formData, setFormData] = useState({
phone: "", email: "", password: ""
});
const [errors, setErrors] = useState({});
const validate = () => {
const newErrors = {};
if (!/^\d{10}$/.test(formData.phone)) newErrors.phone = "Invalid phone";
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email))
newErrors.email = "Invalid email";
if (formData.password.length < 6) newErrors.password = "Short password";
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const handleSubmit = (e) => {
e.preventDefault();
if (validate()) alert("Form submitted!");
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={formData.phone}
onChange={(e) => setFormData({...formData, phone: e.target.value})}
placeholder="Phone"
/>
{errors.phone && <p>{errors.phone}</p>}
{/* Repeat for email, password */}
<button type="submit">Sign Up</button>
</form>
);
}
Key Differences:
| Feature | jQuery | React |
|---|---|---|
| Validation | Alerts on submit | Real-time feedback (errors state) |
| State | Global DOM manipulation | Local component state (useState) |
| Performance | Re-renders entire DOM | Virtual DOM updates only changes |
## In the Real World
eSewa’s Form Handling
- Library Used: jQuery
- How: Validates user inputs (e.g., citizen ID format) before processing payments. The lightweight library ensures fast validation even on low-end devices.
Pathao’s Ride Tracking
- Framework Used: React
- How: React’s virtual DOM efficiently updates the rider’s location and estimated time without full page reloads, reducing latency.
Khalti’s Payment Gateway
- Framework Used: Angular
- How: Angular’s MVC structure separates concerns (e.g., user auth in the controller, UI in the view), ensuring secure and scalable payment flows.
NTC’s Service Request Portal
- Library Used: jQuery + Bootstrap
- How: jQuery handles dynamic dropdowns for service types (e.g., electricity, water), while Bootstrap ensures mobile responsiveness.
## Exam Tip
Code Snippets: Expect questions asking for:
- jQuery selectors (e.g.,
$(".class"),$("#id")). - React hooks (
useState,useEffect) or lifecycle methods. - Vue directives (
v-if,v-bind). - Angular services or components.
- jQuery selectors (e.g.,
Comparisons: Be ready to contrast:
- Libraries vs. frameworks (scope, control).
- React vs. Vue (virtual DOM, reactivity).
- jQuery vs. vanilla JS (syntax, performance).
Real-World Scenarios:
- Trace a form submission (e.g., "How does Pathao validate a ride request in React?").
- Explain a performance optimization (e.g., "Why does React use a virtual DOM?").
- Choose a tool (e.g., "When would you use jQuery vs. Vue for a mobile app?").
Common Pitfalls:
- Forgetting to prevent default form submission (
e.preventDefault()in React). - Misusing state vs. props in React (state for internal data, props for parent data).
- Overcomplicating jQuery solutions (e.g., using
.each()when.map()suffices).
- Forgetting to prevent default form submission (
## Practice Questions
Short Answer:
- What is the primary advantage of React’s virtual DOM?
- How does Vue’s
v-fordirective work?
Code:
- Write a jQuery snippet to toggle a
<div>with IDmenuon button click. - Create a React component that displays a list of items fetched from an API.
- Write a jQuery snippet to toggle a
Scenario:
- Nepal Police’s Emergency App: Should they use jQuery, React, or Angular? Justify your choice with 2 reasons.
## Summary Table
| Tool | Type | Key Feature | Best For | Example Use Case |
|---|---|---|---|---|
| jQuery | Library | DOM manipulation | Quick DOM tasks, legacy support | eSewa form validation |
| React | Framework | Virtual DOM, components | SPAs, real-time updates | Pathao ride tracker |
| Vue.js | Framework | Reactivity, directives | Progressive adoption, simplicity | Khalti payment success page |
| Angular | Framework | MVC, TypeScript | Large-scale apps, enterprise | Ncell billing portal |
Based on the TU BITM syllabus for Web Technology I (IT237), unit 9.
Discussion
Loading…