Web Programming Technologies Complete Guide
Master HTML5, CSS, JavaScript, Node.js, Express.js, React, and React-Redux for modern web development
Introduction
Web Programming Technologies form the foundation of modern web development. This comprehensive guide covers everything from basic HTML and CSS to advanced React and Redux, following the PG-DAC curriculum for Web Programming Technologies.
What You'll Learn
- Frontend Technologies: HTML5, CSS3, JavaScript, Bootstrap, React
- Backend Technologies: Node.js, Express.js
- Data Formats: JSON, XML
- Libraries & Frameworks: jQuery, Axios, React-Redux
- Web Architecture: HTTP/HTTPS, Web Servers, AJAX
Architecture of Web
The web architecture defines how information is transmitted and accessed over the internet. Understanding this foundation is crucial for web development.
Brief History of the Internet
The Internet began as ARPANET in 1969, connecting computers for research purposes. It evolved into the World Wide Web in 1989 when Tim Berners-Lee invented HTTP, HTML, and the first web browser.
How Does the Internet Work?
The Internet is a network of networks that uses standardized protocols to communicate. When you request a webpage:
- Your browser sends an HTTP request to the web server
- The request travels through routers and switches
- The server processes the request and sends back an HTTP response
- Your browser renders the HTML, CSS, and JavaScript
Visualization: HTTP Request/Response Flow
example.com → 192.0.2.1
3-way handshake
GET /index.html HTTP/1.1
Host: www.example.com
HTTP/1.1 200 OK
Content-Type: text/html
Sequence Diagram: HTTP Request Flow
Concept: OSI Model Layers
The Internet uses a layered architecture. HTTP operates at the Application layer:
Internet Protocol (IP) and HTTP
IP (Internet Protocol): Routes data packets across networks using IP addresses (e.g., 192.168.1.1 or IPv6 addresses).
HTTP (HyperText Transfer Protocol): Application-layer protocol for transmitting hypermedia documents, primarily HTML.
Domain Names and DNS
Domain Names: Human-readable addresses like "example.com" that map to IP addresses.
DNS (Domain Name Service): Translates domain names to IP addresses. When you type a URL, DNS servers resolve the domain to an IP address.
HTTP Versions
| Version | Year | Key Features |
|---|---|---|
| HTTP/1.0 | 1996 | One request per connection, no persistent connections |
| HTTP/1.1 | 1997 | Persistent connections, chunked transfer, caching, pipelining |
| HTTP/2.0 | 2015 | Multiplexing, header compression, server push, binary protocol |
HTTP Methods
- GET: Retrieve data from server (idempotent, cacheable)
- POST: Submit data to server (creates resources)
- PUT: Update existing resource (idempotent)
- DELETE: Remove resource (idempotent)
- HEAD: Get headers without body (idempotent, cacheable)
- PATCH: Partial update of resource
- OPTIONS: Get allowed methods for resource
HTTP Status Codes
| Code | Category | Common Examples |
|---|---|---|
| 1xx | Informational | 100 Continue, 101 Switching Protocols |
| 2xx | Success | 200 OK, 201 Created, 204 No Content |
| 3xx | Redirection | 301 Moved Permanently, 302 Found, 304 Not Modified |
| 4xx | Client Error | 400 Bad Request, 401 Unauthorized, 404 Not Found |
| 5xx | Server Error | 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable |
Stateless Nature of HTTP
HTTP is stateless - each request is independent and the server doesn't remember previous requests. To maintain state, we use:
- Cookies: Small data stored on client
- Sessions: Server-side state management
- Tokens: JWT for authentication
HTTPS (HTTP Secure)
HTTPS encrypts HTTP using TLS/SSL to provide:
- Data encryption in transit
- Server authentication
- Data integrity
GET /index.html HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0
Accept: text/html,application/xhtml+xml
Accept-Language: en-US,en;q=0.9
HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
Content-Length: 1234
Date: Mon, 23 May 2024 22:38:34 GMT
<html>...</html>
Web Servers
- Apache HTTP Server: Open-source, widely used, supports .htaccess
- IIS (Internet Information Services): Microsoft's web server for Windows
- Nginx: High-performance, reverse proxy, load balancer
- Node.js: JavaScript runtime for building servers
HTML5
HTML5 is the latest version of HyperText Markup Language, introducing new elements, attributes, and APIs for modern web development.
Basic HTML Tags
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My First Web Page</title>
</head>
<body>
<h1>Main Heading</h1>
<h2>Subheading</h2>
<p>This is a paragraph with <strong>bold</strong> and <em>italic</em> text.</p>
<a href="https://example.com">Link to Example</a>
<img src="image.jpg" alt="Description">
</body>
</html>
HTML5 New Features
- Semantic Elements: <header>, <nav>, <article>, <section>, <aside>, <footer>
- Form Enhancements: New input types (email, date, number, range, color)
- Media Elements: <audio> and <video> tags
- Canvas: 2D graphics and animations
- Geolocation API: Access user's location
- Local Storage: Store data in browser
- Web Workers: Background processing
HTML Forms
<form action="/submit" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="age">Age:</label>
<input type="number" id="age" name="age" min="18" max="100">
<label>Gender:</label>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label>
<label for="country">Country:</label>
<select id="country" name="country">
<option value="us">United States</option>
<option value="uk">United Kingdom</option>
<option value="in">India</option>
</select>
<label for="message">Message:</label>
<textarea id="message" name="message" rows="4"></textarea>
<button type="submit">Submit</button>
<button type="reset">Reset</button>
</form>
HTML5 Semantic Elements
<header>
<h1>Website Title</h1>
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
</ul>
</nav>
</header>
<main>
<article>
<h2>Article Title</h2>
<p>Article content...</p>
</article>
<aside>
<h3>Sidebar</h3>
<p>Additional information...</p>
</aside>
</main>
<footer>
<p>© 2024 My Website</p>
</footer>
Document Object Model (DOM)
The DOM is a programming interface for HTML and XML documents. It represents the page structure as a tree of nodes that can be manipulated with JavaScript.
Practice Questions - HTML5 8 Questions
The <nav> element is a semantic HTML5 element specifically designed to contain navigation links. It helps screen readers and search engines understand the navigation structure of the page.
The <canvas> element provides a drawing surface that can be manipulated with JavaScript. It's used for creating graphics, animations, games, and data visualizations programmatically.
The type="email" input type provides built-in validation for email addresses and on mobile devices, it shows an email-optimized keyboard layout.
The Document Object Model (DOM) is a programming interface that represents the structure of HTML and XML documents as a tree of nodes, allowing JavaScript to access and manipulate elements.
The <article> element represents independent, self-contained content that could be distributed separately, such as blog posts, news articles, or forum posts.
HTML5 simplified the doctype declaration to just <!DOCTYPE html>. It's case-insensitive and much simpler than previous HTML versions.
The "required" attribute is a boolean attribute in HTML5 that specifies that an input field must be filled out before submitting the form. The browser will prevent form submission if required fields are empty.
The <video> element is used to embed video content in HTML5. It supports multiple source formats and provides built-in controls for playback.
Cascading Style Sheets (CSS)
CSS is used to style and layout web pages, controlling colors, fonts, spacing, and responsive design.
CSS Syntax
selector {
property: value;
property: value;
}
/* Example */
h1 {
color: blue;
font-size: 24px;
margin-bottom: 20px;
}
CSS Selectors
- Element Selector:
p { } - Class Selector:
.class-name { } - ID Selector:
#id-name { } - Descendant Selector:
div p { } - Child Selector:
div > p { } - Attribute Selector:
input[type="text"] { }
Ways to Include CSS
1. Inline CSS
<p style="color: red; font-size: 18px;">This is red text</p>
2. Internal CSS
<head>
<style>
p {
color: blue;
font-size: 16px;
}
</style>
</head>
3. External CSS
<head>
<link rel="stylesheet" href="styles.css">
</head>
CSS Box Model
Every HTML element is a box with:
- Content: The actual content (text, images, etc.)
- Padding: Space between content and border
- Border: Border around padding
- Margin: Space outside the border
Visualization: CSS Box Model
Total Width = margin + border + padding + content-width
box-sizing: content-box (default) - width applies to content only
box-sizing: border-box - width includes padding and border
.box {
width: 300px;
height: 200px;
padding: 20px;
border: 5px solid black;
margin: 10px;
box-sizing: border-box; /* Includes padding and border in width/height */
}
CSS Properties
/* Typography */
font-family: Arial, sans-serif;
font-size: 16px;
font-weight: bold;
font-style: italic;
text-align: center;
text-decoration: underline;
line-height: 1.5;
/* Colors and Backgrounds */
color: #333333;
background-color: #f0f0f0;
background-image: url('image.jpg');
/* Layout */
display: block; /* or inline, flex, grid, none */
position: relative; /* or absolute, fixed, sticky */
float: left;
clear: both;
/* Spacing */
margin: 10px;
padding: 15px;
width: 100%;
height: auto;
Practice Questions - CSS 10 Questions
CSS stands for Cascading Style Sheets. The "cascading" refers to how styles can be inherited and overridden from multiple sources, with priority rules determining which styles apply.
The "color" property is used to set the text color of an element. It accepts color values like named colors, hex codes, RGB, or HSL values.
To select an element by ID in CSS, you use the hash symbol (#) followed by the ID name. For example, #myId { } selects the element with id="myId".
Padding is the space between the content and the border of an element. Margin is the space outside the border, between elements.
When box-sizing is set to border-box, the width and height properties include the padding and border, making it easier to size elements predictably.
The descendant selector "div p" selects all <p> elements that are descendants (children, grandchildren, etc.) of <div> elements. "div > p" selects only direct children.
The default value of the position property is "static", which means the element follows the normal document flow. Other values include relative, absolute, fixed, and sticky.
The font-weight property is used to set the thickness of the text. Common values include normal, bold, or numeric values like 100-900.
display: flex creates a flex container, enabling flexible box layout. It allows you to align and distribute space among items in a container, even when their size is unknown or dynamic.
The border-radius property is used to create rounded corners. You can specify a single value for all corners or individual values for each corner.
Responsive Web Design
Responsive design ensures websites work well on all devices - desktop, tablet, and mobile.
Bootstrap Framework
Bootstrap is a popular CSS framework that provides pre-built components and a responsive grid system.
Bootstrap Grid System
Bootstrap uses a 12-column grid system:
<div class="container">
<div class="row">
<div class="col-md-6">Column 1 (50%)</div>
<div class="col-md-6">Column 2 (50%)</div>
</div>
<div class="row">
<div class="col-md-4">Column 1 (33%)</div>
<div class="col-md-4">Column 2 (33%)</div>
<div class="col-md-4">Column 3 (33%)</div>
</div>
</div>
Bootstrap Components
- Buttons:
btn btn-primary - Cards:
card card-body - Navbar:
navbar navbar-expand-lg - Forms:
form-group form-control - Alerts:
alert alert-success - Modals:
modal modal-dialog
Media Queries
/* Mobile First Approach */
.container {
width: 100%;
padding: 10px;
}
/* Tablet */
@media (min-width: 768px) {
.container {
width: 750px;
margin: 0 auto;
}
}
/* Desktop */
@media (min-width: 992px) {
.container {
width: 970px;
}
}
/* Large Desktop */
@media (min-width: 1200px) {
.container {
width: 1170px;
}
}
JavaScript Basics
JavaScript is a dynamic programming language that adds interactivity to web pages.
Variables and Data Types
// Variables (ES6+)
let name = "John"; // String
const age = 25; // Number (constant)
var isActive = true; // Boolean
// Data Types
let num = 42; // Number
let str = "Hello"; // String
let bool = true; // Boolean
let arr = [1, 2, 3]; // Array
let obj = {name: "John"}; // Object
Operators and Control Structures
// Arithmetic Operators
let sum = 10 + 5; // 15
let diff = 10 - 5; // 5
// Comparison Operators
10 == "10" // true (loose equality)
10 === "10" // false (strict equality)
// If-else
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}
// Loops
for (let i = 0; i < 5; i++) {
console.log(i);
}
Strings and Arrays
// String Methods
let str = "Hello World";
str.length; // 11
str.toUpperCase(); // "HELLO WORLD"
str.indexOf("World"); // 6
// Array Methods
let arr = [1, 2, 3, 4, 5];
arr.push(6); // [1,2,3,4,5,6]
arr.map(x => x * 2); // [2,4,6,8,10]
arr.filter(x => x > 2); // [3,4,5]
Practice Questions - JavaScript Basics 10 Questions
The "const" keyword declares a constant variable that cannot be reassigned after initialization. However, if the value is an object or array, its properties can still be modified.
The == operator performs type coercion, converting "10" to 10 before comparison, so 10 == "10" is true. Use === for strict equality without type coercion.
typeof null returns "object", which is a well-known bug in JavaScript that has been kept for backward compatibility. To check for null, use: value === null
The push() method adds one or more elements to the end of an array and returns the new length. pop() removes the last element, shift() removes the first, and unshift() adds to the beginning.
The map() method creates a new array with the results of calling a function for every array element. Each element (x) is multiplied by 2, resulting in [2, 4, 6].
Array.isArray() is the recommended method. typeof returns "object" for arrays, not "array". While instanceof Array works, Array.isArray() is more reliable across different contexts.
When using the + operator with a string, JavaScript performs string concatenation. The number 3 is converted to the string "3" and concatenated with "5", resulting in "53".
The do...while loop executes the code block once before checking the condition, so it's guaranteed to run at least once. while and for loops check the condition first.
Variables declared with "let" have block scope, meaning they are only accessible within the block (curly braces) where they are declared. This is different from "var" which has function scope.
The filter() method creates a new array containing all elements that pass the test implemented by the provided function. It does not modify the original array.
JavaScript Advanced
Advanced JavaScript concepts including objects, functions, closures, and Object-Oriented Programming.
Objects and Classes
// Object Literal
let person = {
name: "John",
age: 30,
greet: function() {
return "Hello, " + this.name;
}
};
// ES6 Classes
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, ${this.name}`;
}
}
// Inheritance
class Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}
}
Functions and Closures
// Arrow Functions (ES6)
const multiply = (a, b) => a * b;
// Default Parameters
function greet(name = "Guest") {
return `Hello, ${name}`;
}
// Closures
function outerFunction(x) {
return function innerFunction(y) {
return x + y;
};
}
const addFive = outerFunction(5);
addFive(3); // 8
Modern JavaScript Features (ES2020+)
Modern JavaScript introduces powerful features that make code more concise and robust:
Optional Chaining (?.)
// Safely access nested properties
const user = {
profile: {
name: "John",
address: {
city: "New York"
}
}
};
// Without Optional Chaining (verbose)
const city = user && user.profile && user.profile.address && user.profile.address.city;
// With Optional Chaining (clean)
const city = user?.profile?.address?.city; // "New York"
const zip = user?.profile?.address?.zip; // undefined (no error)
// Works with arrays and function calls
const firstItem = arr?.[0];
const result = obj?.method?.();
Nullish Coalescing (??)
// Provides default value only for null/undefined
const username = user.name ?? "Guest";
const count = value ?? 0;
// Difference from || operator
const value1 = 0 || "default"; // "default" (0 is falsy)
const value2 = 0 ?? "default"; // 0 (0 is not null/undefined)
const value3 = "" || "default"; // "default" ("" is falsy)
const value4 = "" ?? "default"; // "" ("" is not null/undefined)
// Practical example
const apiTimeout = config.timeout ?? 5000; // Use 5000 only if timeout is null/undefined
Promise.allSettled()
// Waits for all promises to settle (fulfilled or rejected)
const promises = [
fetch('/api/user'),
fetch('/api/posts'),
fetch('/api/comments')
];
// Promise.all() fails if any promise rejects
// Promise.allSettled() waits for all, regardless of outcome
const results = await Promise.allSettled(promises);
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
console.log(`Promise ${index} succeeded:`, result.value);
} else {
console.log(`Promise ${index} failed:`, result.reason);
}
});
// Useful for: Independent API calls where one failure shouldn't stop others
Top-Level Await
// In ES modules, you can use await at the top level
// config.js (ES module)
const config = await fetch('/api/config').then(r => r.json());
export default config;
// Previously required wrapping in async function:
// (async () => {
// const config = await fetch('/api/config').then(r => r.json());
// })();
Practice Questions - JavaScript Advanced 10 Questions
A closure is a function that has access to variables in its outer (enclosing) lexical scope, even after the outer function has returned. This allows for data privacy and function factories.
The "this" keyword refers to the object that is executing the current function. Its value depends on how a function is called (context), not where it's defined.
Arrow functions don't have their own "this" binding. They inherit "this" from the enclosing lexical scope, while regular functions have their own "this" that depends on how they're called.
The "super" keyword is used to call the constructor or methods of the parent class. In a constructor, super() must be called before using "this".
The bind() method creates a new function that, when called, has its "this" keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
A Promise is an object that represents a value that may not be available yet. It has three states: pending, fulfilled, or rejected. Promises help handle asynchronous operations more elegantly than callbacks.
Both call() and apply() invoke a function with a specific "this" value. The difference is that call() takes arguments as individual parameters, while apply() takes arguments as an array.
Destructuring is a JavaScript expression that allows you to unpack values from arrays or properties from objects into distinct variables. Example: const {name, age} = person;
The spread operator (...) allows an iterable (like an array or string) to be expanded in places where zero or more arguments or elements are expected. It's useful for copying arrays, combining arrays, or passing arguments.
async/await is syntactic sugar built on Promises that makes asynchronous code look and behave more like synchronous code. An async function returns a Promise, and await pauses execution until the Promise resolves.
Document Object Model (DOM)
The DOM represents the HTML document as a tree structure that JavaScript can manipulate.
DOM Selection and Manipulation
// DOM Selection
let element = document.getElementById("myId");
let elements = document.querySelectorAll(".myClass");
// DOM Manipulation
element.textContent = "New Text";
element.style.color = "red";
element.className = "newClass";
// Create and Append Elements
let newDiv = document.createElement("div");
newDiv.textContent = "New Div";
document.body.appendChild(newDiv);
// Event Listeners
element.addEventListener("click", function() {
console.log("Clicked!");
});
Form Validation
function validateForm() {
let email = document.getElementById("email").value;
let emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
alert("Invalid email format");
return false;
}
return true;
}
Practice Questions - DOM 8 Questions
The DOM (Document Object Model) is a programming interface for HTML and XML documents. It represents the page structure as a tree of nodes that can be manipulated with JavaScript.
document.getElementById() is the standard method to select an element by its ID. It returns a single element or null if not found. querySelector('#id') also works but getElementById is more specific.
document.createElement() creates a new HTML element node. The element is created but not yet added to the DOM. You need to use appendChild() or similar methods to add it to the document.
textContent gets/sets the text content and treats everything as plain text. innerHTML gets/sets the HTML content and parses HTML tags. Use textContent when you want to prevent XSS attacks.
addEventListener() attaches an event handler function to an element. It's the modern way to handle events and allows multiple handlers on the same element, unlike the older onclick attribute.
querySelector() returns null if no matching element is found. querySelectorAll() returns an empty NodeList. Always check for null before using the returned element.
Event bubbling is when an event starts from the target element and propagates upward through its ancestors to the document root. You can stop it with event.stopPropagation().
removeChild() removes a specified child node from the DOM. The removed node still exists in memory but is no longer part of the document tree. You need to call it on the parent element.
JSON & jQuery
JSON (JavaScript Object Notation) is a lightweight data format, and jQuery simplifies DOM manipulation and AJAX.
JSON
// JSON Object
let person = {
"name": "John",
"age": 30,
"city": "New York"
};
// JSON String
let jsonString = JSON.stringify(person);
// Parse JSON
let parsed = JSON.parse(jsonString);
jQuery
// jQuery Selectors
$("#myId"); // Select by ID
$(".myClass"); // Select by class
// jQuery DOM Manipulation
$("#myId").text("New Text");
$("#myId").css("color", "red");
$("#myId").addClass("newClass");
// jQuery Events
$("#myButton").click(function() {
console.log("Button clicked");
});
// jQuery AJAX
$.ajax({
url: "data.json",
method: "GET",
success: function(data) {
console.log(data);
}
});
Practice Questions - JSON & jQuery 8 Questions
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate.
JSON.stringify() converts a JavaScript object or value to a JSON string. JSON.parse() does the opposite - converts a JSON string to a JavaScript object.
In jQuery, $("#id") selects an element by ID, similar to getElementById(). The # symbol is used for ID selectors, just like in CSS.
$(document).ready() ensures that code executes only after the DOM is fully loaded and ready for manipulation. It's similar to DOMContentLoaded event.
The addClass() method adds one or more CSS classes to selected elements. removeClass() removes classes, and toggleClass() toggles them.
In JSON, property names must be in double quotes, and string values must also be in double quotes (not single quotes). This is the correct JSON syntax.
The .click() method can both attach an event handler (with a function parameter) or trigger a click event (without parameters). It's a shorthand for .on("click", handler).
JSON.parse() throws a SyntaxError if the string to parse is not valid JSON. Always wrap it in a try-catch block when parsing user input or external data.
AJAX & Axios
AJAX enables asynchronous data exchange, and Axios is a modern promise-based HTTP client.
AJAX with XMLHttpRequest
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
let data = JSON.parse(xhr.responseText);
console.log(data);
}
};
xhr.send();
Axios HTTP Client
// GET Request
axios.get("https://api.example.com/data")
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
// POST Request
axios.post("https://api.example.com/data", {
name: "John",
age: 30
})
.then(response => {
console.log(response.data);
});
Practice Questions - AJAX & Axios 8 Questions
AJAX stands for Asynchronous JavaScript and XML. It allows web pages to update asynchronously by exchanging data with a server without reloading the entire page.
readyState 4 means the request is complete. The states are: 0=UNSENT, 1=OPENED, 2=HEADERS_RECEIVED, 3=LOADING, 4=DONE.
Axios is a popular JavaScript library used to make HTTP requests. It's promise-based, works in both browser and Node.js, and provides a simpler API than XMLHttpRequest.
HTTP status code 200 means "OK" - the request was successful. 400 is Bad Request, 300 is Redirection, and 500 is Internal Server Error.
Axios provides a cleaner, promise-based API that's easier to use than XMLHttpRequest's callback-based approach. It also has built-in request/response interceptors and automatic JSON data transformation.
The .catch() method handles errors and rejected promises in a promise chain. It's used for error handling when an Axios request fails (network errors, HTTP errors, etc.).
The GET method is used to retrieve data from a server. It's idempotent and cacheable. POST is for creating resources, PUT for updating, and DELETE for removing.
CORS (Cross-Origin Resource Sharing) is a security feature that allows web pages to make requests to a different domain than the one serving the page. The server must include appropriate CORS headers to allow such requests.
Node.js
Node.js is a JavaScript runtime built on Chrome's V8 engine, allowing JavaScript to run on the server.
Node.js Basics
// File System Module
const fs = require('fs');
// Read File (Async)
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
// Write File (Async)
fs.writeFile('output.txt', 'Hello World', (err) => {
if (err) {
console.error(err);
return;
}
console.log('File written');
});
Asynchronous Programming
// Promises
function fetchDataPromise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data received");
}, 1000);
});
}
fetchDataPromise()
.then(data => console.log(data))
.catch(error => console.error(error));
// Async/Await
async function fetchDataAsync() {
try {
const data = await fetchDataPromise();
console.log(data);
} catch (error) {
console.error(error);
}
}
Node.js Modules
// Creating a Module (math.js)
function add(a, b) {
return a + b;
}
module.exports = { add };
// Using a Module
const math = require('./math');
console.log(math.add(5, 3)); // 8
HTTP Module
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/') {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<h1>Hello World</h1>');
} else {
res.writeHead(404);
res.end('Not Found');
}
});
server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Practice Questions - Node.js 10 Questions
Node.js is a JavaScript runtime that allows JavaScript to run on the server-side. It's built on Chrome's V8 JavaScript engine and uses an event-driven, non-blocking I/O model.
Node.js uses CommonJS module system by default. require() is used to import modules. ES6 import syntax can be used with .mjs files or when "type": "module" is set in package.json.
package.json contains project metadata (name, version, description) and lists all dependencies and their versions. It's essential for Node.js projects and npm package management.
fs.readFile() is asynchronous and non-blocking, using a callback. fs.readFileSync() is synchronous and blocks execution until the file is read. Async is preferred for better performance.
npm (Node Package Manager) is the default package manager for Node.js. It's used to install, manage, and share packages/modules. It comes bundled with Node.js installation.
module.exports is used to make functions, objects, or values available to other files that require the module. It's the CommonJS way of exporting from a module.
The event loop is what allows Node.js to perform non-blocking I/O operations. It continuously checks for and executes callbacks from the callback queue when the call stack is empty.
__dirname is a global variable in Node.js that contains the absolute path of the directory containing the currently executing file. __filename contains the file path.
Promises are used to handle asynchronous operations in Node.js. They represent a value that may be available now, in the future, or never. They help avoid callback hell and make async code more readable.
The http module provides functionality to create HTTP servers (using http.createServer()) and make HTTP requests (using http.request() or http.get()). It's a core Node.js module.
Express.js
Express.js is a minimal and flexible Node.js web application framework.
Getting Started with Express
const express = require('express');
const app = express();
const port = 3000;
// Basic Route
app.get('/', (req, res) => {
res.send('Hello World!');
});
// Route with Parameters
app.get('/user/:id', (req, res) => {
res.send(`User ID: ${req.params.id}`);
});
// POST Route
app.post('/user', (req, res) => {
res.send('User created');
});
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
Express Middleware
// Built-in Middleware
app.use(express.json());
app.use(express.urlencoded({extended: true}));
// Custom Middleware
app.use((req, res, next) => {
console.log(`${req.method} ${req.path}`);
next();
});
// Error Handling Middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
Practice Questions - Express.js 8 Questions
Express.js is a fast, unopinionated, minimalist web framework for Node.js. It provides a robust set of features for web and mobile applications, including routing, middleware, and template engines.
Middleware functions have access to the request object (req), response object (res), and the next middleware function. They can execute code, modify req/res, end the cycle, or call next().
app.get() is used to define a route handler for HTTP GET requests. It takes a path and a callback function that handles the request and sends a response.
app.use() is used to mount middleware functions at a specified path. If no path is specified, it applies to all routes. It's commonly used for body parsers, CORS, authentication, etc.
req.params contains route parameters. For example, in the route /user/:id, req.params.id would contain the value of the id parameter. req.query contains query string parameters.
express.json() is middleware that parses incoming requests with JSON payloads. It makes the parsed data available in req.body. Without it, req.body would be undefined for JSON requests.
res.send() sends a response of various types (string, object, Buffer, etc.) and automatically sets the Content-Type header. It also ends the response, so you can't call it multiple times.
Middleware functions are executed in the order they are defined. The order matters! For example, body parsing middleware should come before route handlers that need to access req.body.
Client-Side vs Server-Side Rendering
Understanding when to use Client-Side Rendering (CSR) with React or Server-Side Rendering (SSR) is crucial for building efficient web applications.
| Aspect | Client-Side Rendering (CSR) | Server-Side Rendering (SSR) |
|---|---|---|
| Rendering Location | Browser (Client) | Server |
| Initial Load | Slower (loads JS bundle first) | Faster (HTML ready immediately) |
| SEO | Poor (content not in initial HTML) | Excellent (content in HTML) |
| Interactivity | High (after initial load) | Requires client-side JS |
| Server Load | Low (static files) | High (renders on each request) |
| Use Cases | Dashboards, SPAs, admin panels | Blogs, e-commerce, content sites |
| Examples | React SPA, Vue.js apps | Next.js, Nuxt.js, traditional PHP |
| Data Fetching | After page load (API calls) | Before page load (server-side) |
React
React is a JavaScript library for building user interfaces, particularly single-page applications.
Concept: React Component Tree
React applications are built as a tree of components:
- Component: Reusable piece of UI
- Props: Data passed from parent to child
- State: Internal data that can change
- Virtual DOM: JavaScript representation of real DOM
- Reconciliation: Process of updating real DOM efficiently
Visualization: React Component Hierarchy
Events: Flow UP (child → parent via callbacks)
Concept: React Render Cycle
React Basics
// Function Component
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
// Class Component
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
State and Lifecycle
// Function Component with Hooks
import React, { useState, useEffect } from 'react';
function Clock() {
const [time, setTime] = useState(new Date());
useEffect(() => {
const timer = setInterval(() => {
setTime(new Date());
}, 1000);
return () => clearInterval(timer);
}, []);
return <div>{time.toLocaleTimeString()}</div>;
}
Handling Events and Forms
function Button() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
// Controlled Components (Forms)
function NameForm() {
const [value, setValue] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
alert('A name was submitted: ' + value);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
);
}
Practice Questions - React 10 Questions
React is a JavaScript library developed by Facebook for building user interfaces, particularly single-page applications. It uses a component-based architecture and a virtual DOM for efficient updates.
JSX (JavaScript XML) is a syntax extension that allows you to write HTML-like code in JavaScript. It gets transpiled to React.createElement() calls by tools like Babel.
Props (properties) are read-only data passed from parent components to child components. They allow components to be reusable and configurable. Props flow downward in the component tree.
State is internal data managed by a component. When state changes, React re-renders the component. In functional components, state is managed with the useState hook.
The Virtual DOM is a lightweight JavaScript representation of the real DOM. React uses it to efficiently update the UI by comparing the new Virtual DOM with the previous one and only updating changed elements (reconciliation).
useEffect is a hook that lets you perform side effects (data fetching, subscriptions, DOM manipulation) in functional components. It's similar to componentDidMount, componentDidUpdate, and componentWillUnmount combined.
A controlled component is a form element (input, textarea, select) whose value is controlled by React state. The value is set via props and changes are handled through onChange handlers.
Keys help React identify which items have changed, been added, or removed. They should be unique among siblings and stable across re-renders. Using keys improves reconciliation performance.
Reconciliation is React's algorithm for efficiently updating the UI. It compares the new Virtual DOM tree with the previous one and determines the minimum number of changes needed to update the real DOM.
Functional components are JavaScript functions that use hooks (useState, useEffect) for state and side effects. Class components are ES6 classes that use lifecycle methods (componentDidMount, etc.). Functional components are now preferred.
React-Redux
Redux is a predictable state container for JavaScript apps, and React-Redux connects React components to Redux store.
Concept: Redux Architecture
Redux follows three core principles:
- Single Source of Truth: Entire app state stored in one store
- State is Read-Only: Only way to change state is by dispatching actions
- Changes via Pure Functions: Reducers are pure functions that take (state, action) → new state
Visualization: Redux Data Flow
Visualization: Redux Store Structure
{ id: 1, text: "Learn Redux", completed: false },
{ id: 2, text: "Build app", completed: true }
]
Redux Basics
// Actions
const increment = () => {
return { type: 'INCREMENT' };
};
// Reducer
function counter(state = { count: 0 }, action) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
}
// Store
import { createStore } from 'redux';
const store = createStore(counter);
// Dispatch Actions
store.dispatch(increment());
React-Redux Integration
// Using Hooks (Modern Approach)
import { useSelector, useDispatch } from 'react-redux';
function Counter() {
const count = useSelector(state => state.count);
const dispatch = useDispatch();
return (
<div>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
<span>{count}</span>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
</div>
);
}
Practice Questions - React-Redux 10 Questions
Redux is a state management library that provides a predictable way to manage application state. It's commonly used with React but can be used with any JavaScript framework.
Redux principles: 1) Single source of truth (one store), 2) State is read-only (can't modify directly), 3) Changes are made through pure functions called reducers.
An action is a plain JavaScript object that describes what happened. It must have a "type" property and optionally a "payload". Actions are dispatched to update the store.
A reducer is a pure function that takes the current state and an action, and returns a new state. It must not mutate the state directly but return a new state object.
The store is a single JavaScript object that holds the entire application state. It's created using createStore() and provides methods like getState(), dispatch(), and subscribe().
dispatch() is a method of the Redux store that sends an action to the store. The store then passes the action to the reducer, which returns a new state, updating the store.
useSelector() is a React-Redux hook that allows you to extract data from the Redux store. It takes a selector function and returns the selected data, re-rendering the component when that data changes.
useDispatch() is a React-Redux hook that returns a reference to the dispatch function from the Redux store. You can use it to dispatch actions from React components.
combineReducers() is a utility function that combines multiple reducer functions into a single root reducer. This allows you to split your state management into smaller, manageable pieces.
Reducers must be pure functions (no side effects, same input = same output) to ensure predictable state updates. This enables features like time-travel debugging and makes the application easier to test and reason about.
Deployment and DevOps
Deploying your web application is the final step in bringing your project to life. Understanding deployment options and best practices is essential for modern web development.
Static Site Hosting
For static websites (HTML, CSS, JavaScript), several platforms offer free hosting with excellent performance:
Vercel
- Best for: React, Next.js, Vue, and static sites
- Features: Automatic deployments from Git, CDN, serverless functions
- Deployment:
npm install -g vercel && vercel - Free tier: Generous limits for personal projects
Netlify
- Best for: Static sites, JAMstack applications
- Features: Continuous deployment, form handling, serverless functions
- Deployment: Drag-and-drop or Git integration
- Free tier: 100GB bandwidth, 300 build minutes/month
GitHub Pages
- Best for: Simple static sites, documentation
- Features: Free hosting for public repositories
- Deployment: Automatic from GitHub repository
- Limitations: No server-side code, limited customization
Full-Stack Application Deployment
For applications with backend (Node.js, Express.js), you need platforms that support server-side code:
Heroku
# Install Heroku CLI
npm install -g heroku
# Login
heroku login
# Create app
heroku create my-app
# Deploy
git push heroku main
# View logs
heroku logs --tail
Railway
- Best for: Node.js, Python, Docker containers
- Features: Automatic deployments, PostgreSQL database included
- Pricing: Pay-as-you-go, $5 free credit monthly
Render
- Best for: Full-stack applications, databases
- Features: Free tier available, auto-deploy from Git
- Free tier: Web services sleep after 15 minutes of inactivity
Docker Basics
Docker containerizes your application, making it easy to deploy anywhere:
Creating a Dockerfile
# Dockerfile for Node.js application
FROM node:18-alpine
# Set working directory
WORKDIR /app
# Copy package files
COPY package*.json ./
# Install dependencies
RUN npm ci --only=production
# Copy application code
COPY . .
# Expose port
EXPOSE 3000
# Start application
CMD ["node", "server.js"]
Docker Commands
# Build image
docker build -t my-app .
# Run container
docker run -p 3000:3000 my-app
# View running containers
docker ps
# Stop container
docker stop <container-id>
Environment Variables
Never commit sensitive data. Use environment variables for configuration:
// .env file (never commit this!)
DATABASE_URL=postgresql://user:pass@localhost/db
API_KEY=your-secret-key
NODE_ENV=production
// In your code
require('dotenv').config();
const dbUrl = process.env.DATABASE_URL;
const apiKey = process.env.API_KEY;
.env to .gitignore. Use your hosting platform's environment variable settings for production.
CI/CD Pipeline
Continuous Integration/Continuous Deployment automates testing and deployment:
- GitHub Actions: Built into GitHub, free for public repos
- GitLab CI/CD: Integrated with GitLab
- Jenkins: Self-hosted, highly customizable
Example GitHub Actions Workflow
# .github/workflows/deploy.yml
name: Deploy
on:
push:
branches: [ main ]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup Node.js
uses: actions/setup-node@v2
with:
node-version: '18'
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
- name: Deploy
run: npm run deploy
- ✅ Set up environment variables
- ✅ Configure database connections
- ✅ Enable HTTPS/SSL
- ✅ Set up error monitoring (Sentry, LogRocket)
- ✅ Configure domain and DNS
- ✅ Set up backups
- ✅ Test production build locally
Best Practices
HTML Best Practices
- Use semantic HTML5 elements
- Always include alt text for images
- Use proper heading hierarchy (h1 → h2 → h3)
- Validate HTML using W3C validator
- Ensure accessibility with ARIA attributes
CSS Best Practices
- Use external stylesheets
- Follow BEM naming convention
- Use CSS variables for theming
- Mobile-first responsive design
- Minimize CSS specificity conflicts
JavaScript Best Practices
- Use const and let instead of var
- Write modular, reusable code
- Handle errors properly
- Use meaningful variable names
- Avoid global variables
React Best Practices
- Keep components small and focused
- Use functional components with hooks
- Lift state up when needed
- Use keys in lists
- Optimize with React.memo and useMemo
Sign up here with your email
ConversionConversion EmoticonEmoticon