FREE

Create Professional Invoices

Generate clean, GST-ready invoices in seconds. No signup required.

Open Invoice Generator

Web Programming Technologies 2026

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
Course Duration: 112 hours (56 theory hours + 56 lab hours) | Evaluation: 100 marks (CCEE – 40%, Lab exam – 40%, Internals – 20%)

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:

  1. Your browser sends an HTTP request to the web server
  2. The request travels through routers and switches
  3. The server processes the request and sends back an HTTP response
  4. Your browser renders the HTML, CSS, and JavaScript

Visualization: HTTP Request/Response Flow

1. User types URL
2. DNS Resolution
example.com → 192.0.2.1
3. TCP Connection
3-way handshake
4. HTTP Request Sent
GET /index.html HTTP/1.1
Host: www.example.com
5. Server Processes
6. HTTP Response
HTTP/1.1 200 OK
Content-Type: text/html
7. Browser Renders

Sequence Diagram: HTTP Request Flow

Browser → User types URL: https://example.com
DNS Query
BrowserDNS Server: Resolve example.com
DNS Response
DNS ServerBrowser: Returns IP 192.0.2.1
TCP Connection
BrowserWeb Server: TCP 3-way handshake (SYN, SYN-ACK, ACK)
TLS Handshake
BrowserWeb Server: SSL/TLS negotiation (HTTPS)
HTTP Request
BrowserWeb Server: GET /index.html HTTP/1.1
Server Processing
Web Server: Processes request, retrieves file
HTTP Response
Web ServerBrowser: HTTP/1.1 200 OK + HTML content
Rendering
Browser: Parses HTML, loads CSS/JS, renders page

Concept: OSI Model Layers

The Internet uses a layered architecture. HTTP operates at the Application layer:

Layer 7: Application - HTTP, HTTPS, FTP, SMTP
Layer 6: Presentation - SSL/TLS encryption
Layer 5: Session - Session management
Layer 4: Transport - TCP, UDP
Layer 3: Network - IP, Routing
Layer 2: Data Link - Ethernet, MAC addresses
Layer 1: Physical - Cables, Radio waves

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>
📄 Result Preview

Main Heading

Subheading

This is a paragraph with bold and italic text.

Link to Example

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.

Remember: HTML5 validation helps ensure data integrity on the client side, but server-side validation is always required for security.

Practice Questions - HTML5 8 Questions

Q1
Which HTML5 element is used to define navigation links?
02:00
<menu>
<nav>
<navigation>
<links>
Answer: B - <nav>

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.

Q2
What is the purpose of the HTML5 <canvas> element?
02:00
Display images
Embed videos
Draw graphics using JavaScript
Create forms
Answer: C - Draw graphics using JavaScript

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.

Q3
Which HTML5 input type is used for email addresses?
02:00
type="text"
type="string"
type="mail"
type="email"
Answer: D - type="email"

The type="email" input type provides built-in validation for email addresses and on mobile devices, it shows an email-optimized keyboard layout.

Q4
What does DOM stand for?
02:00
Document Object Model
Data Object Model
Document Oriented Model
Dynamic Object Management
Answer: A - Document Object Model

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.

Q5
Which HTML5 element is used for independent, self-contained content?
02:00
<section>
<article>
<div>
<content>
Answer: B - <article>

The <article> element represents independent, self-contained content that could be distributed separately, such as blog posts, news articles, or forum posts.

Q6
What is the correct HTML5 doctype declaration?
02:00
<!DOCTYPE HTML PUBLIC>
<!DOCTYPE html PUBLIC>
<!DOCTYPE html>
<DOCTYPE html>
Answer: C - <!DOCTYPE html>

HTML5 simplified the doctype declaration to just <!DOCTYPE html>. It's case-insensitive and much simpler than previous HTML versions.

Q7
Which attribute is used to make an input field required in HTML5?
02:00
mandatory
must
validate
required
Answer: D - required

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.

Q8
What is the purpose of the HTML5 <video> element?
02:00
Embed and play video content
Display images
Create animations
Play audio files
Answer: A - Embed and play video content

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

Margin
Border
Padding
CONTENT

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

Q1
What does CSS stand for?
02:00
Computer Style Sheets
Cascading Style Sheets
Creative Style Sheets
Colorful Style Sheets
Answer: B - Cascading Style Sheets

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.

Q2
Which CSS property is used to change the text color?
02:00
text-color
font-color
color
text-style
Answer: C - color

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.

Q3
What is the correct CSS syntax to select an element by its ID?
02:00
#id { }
.id { }
id { }
#id { } (correct syntax)
Answer: D - #id { }

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".

Q4
Which property is used to set the space between the content and the border of an element?
02:00
padding
margin
spacing
border-spacing
Answer: A - padding

Padding is the space between the content and the border of an element. Margin is the space outside the border, between elements.

Q5
What does the CSS property "box-sizing: border-box" do?
02:00
Includes only content in width/height
Includes padding and border in width/height
Includes margin in width/height
Excludes all spacing from width/height
Answer: B - Includes padding and border in width/height

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.

Q6
Which CSS selector targets all <p> elements inside a <div> element?
02:00
div > p
div + p
div p
div.p
Answer: C - div p

The descendant selector "div p" selects all <p> elements that are descendants (children, grandchildren, etc.) of <div> elements. "div > p" selects only direct children.

Q7
What is the default value of the CSS position property?
02:00
absolute
fixed
relative
static
Answer: D - static

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.

Q8
Which CSS property is used to make text bold?
02:00
font-weight
text-weight
font-style
text-bold
Answer: A - font-weight

The font-weight property is used to set the thickness of the text. Common values include normal, bold, or numeric values like 100-900.

Q9
What does the CSS property "display: flex" do?
02:00
Makes elements float
Creates a flexible box layout
Hides the element
Makes text flexible
Answer: B - Creates a flexible box layout

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.

Q10
Which CSS property is used to add rounded corners to an element?
02:00
border-radius
corner-radius
border-radius (correct)
rounded-corners
Answer: C - border-radius

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

Q1
Which keyword is used to declare a variable that cannot be reassigned in ES6?
02:00
var
let
const
static
Answer: C - const

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.

Q2
What is the result of: 10 == "10" in JavaScript?
02:00
false
true
undefined
Error
Answer: B - true

The == operator performs type coercion, converting "10" to 10 before comparison, so 10 == "10" is true. Use === for strict equality without type coercion.

Q3
What is the output of: typeof null in JavaScript?
02:00
"null"
"undefined"
"object"
"object" (this is a known JavaScript quirk)
Answer: D - "object"

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

Q4
Which array method adds one or more elements to the end of an array?
02:00
push()
pop()
shift()
unshift()
Answer: A - push()

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.

Q5
What does the following code return: [1, 2, 3].map(x => x * 2)?
02:00
[1, 2, 3]
[2, 4, 6]
[2, 4, 6] (correct)
undefined
Answer: C - [2, 4, 6]

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].

Q6
What is the correct way to check if a variable is an array in JavaScript?
02:00
typeof arr === "array"
Array.isArray(arr)
arr instanceof Array
Both B and C are correct
Answer: B - Array.isArray(arr)

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.

Q7
What is the result of: "5" + 3 in JavaScript?
02:00
8
53
Error
"53" (string concatenation)
Answer: D - "53"

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".

Q8
Which loop is guaranteed to execute at least once?
02:00
do...while
while
for
for...in
Answer: A - do...while

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.

Q9
What is the scope of a variable declared with "let" inside a block?
02:00
Global scope
Function scope
Block scope
Module scope
Answer: C - Block scope

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.

Q10
What does the filter() method do?
02:00
Modifies the original array
Creates a new array with elements that pass a test
Removes all elements from the array
Sorts the array
Answer: B - Creates a new array with elements that pass a test

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

Q1
What is a closure in JavaScript?
02:00
A function that returns another function
A way to close a function
A function that has access to variables in its outer scope
A method to hide variables
Answer: C - A function that has access to variables in its outer scope

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.

Q2
What is the "this" keyword in JavaScript?
02:00
A reference to the current function
A reference to the object that owns the executing code
A reference to the global object
A reserved keyword with no meaning
Answer: B - A reference to the object that owns the executing code

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.

Q3
What is the difference between arrow functions and regular functions regarding "this"?
02:00
Arrow functions have their own "this"
There is no difference
Regular functions don't have "this"
Arrow functions inherit "this" from the enclosing scope
Answer: D - Arrow functions inherit "this" from the enclosing scope

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.

Q4
What does the "super" keyword do in ES6 classes?
02:00
Calls the parent class constructor or method
Creates a superclass
Makes a class superior
Defines a static method
Answer: A - Calls the parent class constructor or method

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".

Q5
What is the purpose of the "bind()" method?
02:00
To bind variables to functions
To create a new function
To create a new function with a specific "this" value
To prevent function execution
Answer: C - To create a new function with a specific "this" value

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.

Q6
What is a Promise in JavaScript?
02:00
A guarantee that code will execute
An object representing the eventual completion or failure of an asynchronous operation
A synchronous function
A way to store data
Answer: B - An object representing the eventual completion or failure of an asynchronous operation

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.

Q7
What is the difference between "call()" and "apply()" methods?
02:00
call() is synchronous, apply() is asynchronous
There is no difference
apply() doesn't exist
call() takes arguments individually, apply() takes an array
Answer: D - call() takes arguments individually, apply() takes an array

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.

Q8
What is destructuring in JavaScript?
02:00
A way to extract values from arrays or objects into distinct variables
A way to destroy variables
A method to delete objects
A way to structure code
Answer: A - A way to extract values from arrays or objects into distinct variables

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;

Q9
What is the spread operator (...) used for?
02:00
To multiply values
To spread errors
To expand arrays or objects into individual elements
To create loops
Answer: C - To expand arrays or objects into individual elements

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.

Q10
What is the purpose of "async/await" in JavaScript?
02:00
To make code run faster
To write asynchronous code in a synchronous style
To prevent asynchronous operations
To create synchronous functions
Answer: B - To write asynchronous code in a synchronous style

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

Q1
What does DOM stand for?
02:00
Document Object Model
Data Object Model
Document Oriented Model
Dynamic Object Management
Answer: A - Document Object Model

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.

Q2
Which method is used to select an element by its ID?
02:00
document.querySelector()
document.getElementById()
document.getElementByClass()
document.findElement()
Answer: B - document.getElementById()

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.

Q3
What does document.createElement() do?
02:00
Creates a new document
Finds an existing element
Creates a new HTML element
Deletes an element
Answer: C - Creates a new HTML element

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.

Q4
What is the difference between textContent and innerHTML?
02:00
There is no difference
textContent parses HTML, innerHTML doesn't
innerHTML is faster
textContent treats content as text, innerHTML parses HTML
Answer: D - textContent treats content as text, innerHTML parses HTML

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.

Q5
What does addEventListener() do?
02:00
Attaches an event handler to an element
Removes an event handler
Creates a new element
Modifies element styles
Answer: A - Attaches an event handler to an element

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.

Q6
What does querySelector() return if no element is found?
02:00
undefined
null
false
An empty array
Answer: B - null

querySelector() returns null if no matching element is found. querySelectorAll() returns an empty NodeList. Always check for null before using the returned element.

Q7
What is event bubbling in the DOM?
02:00
Events don't propagate
Events only affect the target element
Events propagate from child to parent elements
Events are blocked
Answer: C - Events propagate from child to parent elements

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().

Q8
What does removeChild() do?
02:00
Removes all children
Hides a child element
Creates a new child
Removes a specific child element from its parent
Answer: D - Removes a specific child element from its parent

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

Q1
What does JSON stand for?
02:00
JavaScript Object Notation
Java Script Object Network
JavaScript Oriented Notation
Java Script Object Notation
Answer: A - JavaScript Object Notation

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.

Q2
Which method is used to convert a JavaScript object to a JSON string?
02:00
JSON.parse()
JSON.stringify()
JSON.convert()
JSON.toString()
Answer: B - JSON.stringify()

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.

Q3
What is the jQuery selector syntax equivalent to document.getElementById()?
02:00
$(".id")
$("id")
$("#id")
$("getElementById")
Answer: C - $("#id")

In jQuery, $("#id") selects an element by ID, similar to getElementById(). The # symbol is used for ID selectors, just like in CSS.

Q4
What does the jQuery method .ready() do?
02:00
Makes elements ready for styling
Prepares data for AJAX
Readies the browser
Executes code when DOM is fully loaded
Answer: D - Executes code when DOM is fully loaded

$(document).ready() ensures that code executes only after the DOM is fully loaded and ready for manipulation. It's similar to DOMContentLoaded event.

Q5
Which jQuery method is used to add a CSS class to an element?
02:00
addClass()
appendClass()
setClass()
class()
Answer: A - addClass()

The addClass() method adds one or more CSS classes to selected elements. removeClass() removes classes, and toggleClass() toggles them.

Q6
What is the correct JSON syntax for an array of objects?
02:00
[{name: "John"}, {name: "Jane"}]
[{"name": "John"}, {"name": "Jane"}]
[{name: 'John'}, {name: 'Jane'}]
[{'name': 'John'}, {'name': 'Jane'}]
Answer: B - [{"name": "John"}, {"name": "Jane"}]

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.

Q7
What does the jQuery .click() method do?
02:00
Clicks an element programmatically
Removes click events
Attaches a click event handler or triggers click
Prevents clicking
Answer: C - Attaches a click event handler or triggers click

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).

Q8
What does JSON.parse() return if the JSON string is invalid?
02:00
null
undefined
false
Throws a SyntaxError
Answer: D - Throws a SyntaxError

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

Q1
What does AJAX stand for?
02:00
Asynchronous JavaScript and XML
Advanced JavaScript and XML
Asynchronous JavaScript and XHTML
Application JavaScript and XML
Answer: A - Asynchronous JavaScript and XML

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.

Q2
What is the readyState value when an XMLHttpRequest is completed?
02:00
1
4
3
2
Answer: B - 4

readyState 4 means the request is complete. The states are: 0=UNSENT, 1=OPENED, 2=HEADERS_RECEIVED, 3=LOADING, 4=DONE.

Q3
What is Axios?
02:00
A JavaScript framework
A CSS library
A promise-based HTTP client
A database
Answer: C - A promise-based HTTP client

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.

Q4
What HTTP status code indicates a successful request?
02:00
400
300
500
200
Answer: D - 200

HTTP status code 200 means "OK" - the request was successful. 400 is Bad Request, 300 is Redirection, and 500 is Internal Server Error.

Q5
What is the main advantage of using Axios over XMLHttpRequest?
02:00
Promise-based API and better error handling
It's faster
It doesn't need a server
It only works in browsers
Answer: A - Promise-based API and better error handling

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.

Q6
What does the .catch() method handle in an Axios request?
02:00
Successful responses
Errors and rejected promises
Pending requests
All responses
Answer: B - Errors and rejected promises

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.).

Q7
What HTTP method is typically used to retrieve data from a server?
02:00
POST
PUT
GET
DELETE
Answer: C - GET

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.

Q8
What does CORS stand for and why is it important for AJAX requests?
02:00
Cross-Origin Resource Sharing - prevents all requests
Common Origin Resource Sharing - allows same-origin requests
Cross-Origin Resource Sharing - only for localhost
Cross-Origin Resource Sharing - allows cross-origin requests
Answer: D - Cross-Origin Resource Sharing - allows cross-origin requests

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

Q1
What is Node.js?
02:00
A JavaScript framework
A JavaScript runtime built on Chrome's V8 engine
A database
A CSS library
Answer: B - A JavaScript runtime built on Chrome's V8 engine

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.

Q2
What is the correct way to import the 'fs' module in Node.js?
02:00
import fs from 'fs'
const fs = require('fs')
const fs = require('fs') (CommonJS)
include fs
Answer: C - const fs = require('fs')

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.

Q3
What is the purpose of the package.json file?
02:00
Defines project metadata and dependencies
Stores application code
Configures the database
Defines CSS styles
Answer: A - Defines project metadata and dependencies

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.

Q4
What is the difference between fs.readFile() and fs.readFileSync()?
02:00
There is no difference
readFile() is faster
readFileSync() doesn't exist
readFile() is asynchronous, readFileSync() is synchronous
Answer: D - readFile() is asynchronous, readFileSync() is synchronous

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.

Q5
What is npm?
02:00
Node Package Manager
Node Package Manager (npm)
New Package Manager
Node Program Manager
Answer: B - Node Package Manager

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.

Q6
What is the purpose of module.exports in Node.js?
02:00
To import modules
To delete modules
To export functions, objects, or values from a module
To create new modules
Answer: C - To export functions, objects, or values from a module

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.

Q7
What is the event loop in Node.js?
02:00
A mechanism that handles asynchronous callbacks
A type of loop in JavaScript
A database query
A file system operation
Answer: A - A mechanism that handles asynchronous callbacks

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.

Q8
What does __dirname represent in Node.js?
02:00
The current file name
The root directory
The home directory
The directory of the current module
Answer: D - The directory of the current module

__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.

Q9
What is a Promise in Node.js used for?
02:00
To create synchronous operations
To handle asynchronous operations
To store data
To import modules
Answer: B - To handle asynchronous operations

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.

Q10
What is the purpose of the http module in Node.js?
02:00
To make HTTP requests only
To handle file operations
To create HTTP servers and make HTTP requests
To manage databases
Answer: C - To create HTTP servers and make HTTP requests

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

Q1
What is Express.js?
02:00
A minimal web application framework for Node.js
A database
A frontend framework
A CSS library
Answer: A - A minimal web application framework for Node.js

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.

Q2
What is middleware in Express.js?
02:00
A database
Functions that execute during the request-response cycle
A type of route
A template engine
Answer: B - Functions that execute during the request-response cycle

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().

Q3
What does app.get() do in Express?
02:00
Gets data from database
Retrieves configuration
Defines a route handler for GET requests
Imports modules
Answer: C - Defines a route handler for GET requests

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.

Q4
What is the purpose of app.use() in Express?
02:00
To use a database
To import modules
To define routes only
To mount middleware functions
Answer: D - To mount middleware functions

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.

Q5
What does req.params contain in Express?
02:00
Route parameters (e.g., /user/:id)
Query string parameters
Request body
Headers
Answer: A - Route parameters (e.g., /user/:id)

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.

Q6
What is the purpose of express.json() middleware?
02:00
To send JSON responses
To parse JSON request bodies
To convert responses to JSON
To validate JSON
Answer: B - To parse JSON request bodies

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.

Q7
What does res.send() do in Express?
02:00
Sends a file
Sends only JSON
Sends a response and ends the response process
Sends headers only
Answer: C - Sends a response and ends the response process

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.

Q8
What is the correct order of middleware execution in Express?
02:00
Random order
Reverse order
Parallel execution
Sequential order as defined
Answer: D - Sequential order as defined

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)
Hybrid Approach: Many modern frameworks like Next.js support both CSR and SSR, allowing you to choose the best rendering strategy for each page.

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

App Component
Header Component
Logo Component
Navigation Component
NavItem (props: "Home")
NavItem (props: "About")
NavItem (props: "Contact")
Main Component
Article Component (state: articleData)
Title Component
Content Component
Comments Component
CommentItem (props: comment)
Sidebar Component
Widget Component
Footer Component
Copyright Component
Data Flow: Props flow DOWN (parent → child)
Events: Flow UP (child → parent via callbacks)

Concept: React Render Cycle

1. Initial Render: Component renders for the first time
2. State/Props Change: User interaction or data update
3. Re-render: Component function called again
4. Virtual DOM Diff: Compare new Virtual DOM with previous
5. Reconciliation: Update only changed DOM nodes

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

Q1
What is React?
02:00
A programming language
A JavaScript library for building user interfaces
A database
A CSS framework
Answer: B - A JavaScript library for building user interfaces

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.

Q2
What is JSX?
02:00
A programming language
A database
A syntax extension that looks like HTML
A CSS preprocessor
Answer: C - A syntax extension that looks like HTML

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.

Q3
What are props in React?
02:00
Data passed from parent to child components
Internal component state
Functions only
CSS properties
Answer: A - Data passed from parent to child components

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.

Q4
What is state in React?
02:00
Data passed from parent
Global variables
CSS styles
Internal data that can change and trigger re-renders
Answer: D - Internal data that can change and trigger re-renders

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.

Q5
What is the Virtual DOM?
02:00
A real DOM element
A JavaScript representation of the real DOM
A database
A CSS framework
Answer: B - A JavaScript representation of the real DOM

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).

Q6
What does the useEffect hook do?
02:00
Manages component state
Creates new components
Performs side effects in functional components
Handles events
Answer: C - Performs side effects in functional components

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.

Q7
What is a controlled component in React?
02:00
A form element whose value is controlled by React state
A component that controls other components
A parent component
A component with no state
Answer: A - A form element whose value is controlled by React state

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.

Q8
What is the purpose of keys in React lists?
02:00
To style elements
To add CSS classes
To make elements clickable
To help React identify which items changed
Answer: D - To help React identify which items changed

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.

Q9
What is reconciliation in React?
02:00
Merging components
The process of updating the DOM efficiently
Resolving conflicts
Error handling
Answer: B - The process of updating the DOM efficiently

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.

Q10
What is the difference between functional and class components?
02:00
Functional components can't use state
Class components are faster
Functional components use hooks, class components use lifecycle methods
There is no difference
Answer: C - Functional components use hooks, class components use lifecycle methods

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

1. User Interaction: User clicks button in React component
2. Dispatch Action: Component dispatches action object
{ type: 'INCREMENT', payload: 1 }
3. Reducer Processes: Reducer receives (currentState, action)
function counter(state = 0, action) { switch(action.type) { case 'INCREMENT': return state + action.payload; default: return state; } }
4. Store Updates: Store replaces old state with new state
5. Components Re-render: Connected components receive new state via props

Visualization: Redux Store Structure

Redux Store
State Tree:
user: { name: "John", id: 1 }
counter: { count: 0 }
todos: [
  { id: 1, text: "Learn Redux", completed: false },
  { id: 2, text: "Build app", completed: true }
]
ui: { theme: "dark", sidebarOpen: false }
Actions:
{ type: "INCREMENT" }
{ type: "ADD_TODO", payload: "..." }
{ type: "SET_THEME", payload: "light" }
Reducers:
userReducer(state.user, action)
counterReducer(state.counter, action)
todosReducer(state.todos, action)
uiReducer(state.ui, action)
Note: combineReducers() merges all reducers into rootReducer

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

Q1
What is Redux?
02:00
A predictable state container for JavaScript apps
A React component
A database
A CSS framework
Answer: A - A predictable state container for JavaScript apps

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.

Q2
What are the three core principles of Redux?
02:00
Speed, efficiency, simplicity
Single source of truth, state is read-only, changes via pure functions
Components, props, state
Actions, reducers, store
Answer: B - Single source of truth, state is read-only, changes via pure functions

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.

Q3
What is an action in Redux?
02:00
A function that modifies state
A React component
A plain object describing what happened
A database query
Answer: C - A plain object describing what happened

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.

Q4
What is a reducer in Redux?
02:00
A function that dispatches actions
A React component
A database query
A pure function that takes state and action, returns new state
Answer: D - A pure function that takes state and action, returns new state

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.

Q5
What is the Redux store?
02:00
An object that holds the application state
A database
A React component
A CSS file
Answer: A - An object that holds the application state

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().

Q6
What does dispatch() do in Redux?
02:00
Creates a new state
Sends an action to the store
Updates components
Fetches data
Answer: B - Sends an action to the store

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.

Q7
What is useSelector() in React-Redux?
02:00
A function to dispatch actions
A reducer
A hook to extract data from the Redux store
An action creator
Answer: C - A hook to extract data from the Redux 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.

Q8
What is useDispatch() in React-Redux?
02:00
A hook to get state
A reducer
An action
A hook that returns the dispatch function
Answer: D - A hook that returns the dispatch function

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.

Q9
What is combineReducers() used for?
02:00
To combine multiple reducers into a single root reducer
To merge actions
To combine components
To combine stores
Answer: A - To combine multiple reducers into a single root reducer

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.

Q10
Why should reducers be pure functions?
02:00
To make them faster
To ensure predictability and enable time-travel debugging
To reduce file size
To prevent errors
Answer: B - To ensure predictability and enable time-travel debugging

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;
Security Note: Always add .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
Deployment Checklist:
  • ✅ 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
Remember: Practice building projects to reinforce your learning. Start with simple projects and gradually increase complexity.
Previous
Next Post »

BOOK OF THE DAY