Mastering Web Development: HTML, CSS, JS, and MongoDB
Differences Between XML and HTML
| XML | HTML |
|---|---|
| Extensible Markup Language | HyperText Markup Language |
| Used to store and transport data | Used to display data in a browser |
| User-defined tags | Predefined tags |
| Case-sensitive | Not case-sensitive |
| Strict syntax; errors are not tolerated | Flexible; errors are tolerated |
| Focus: Data | Focus: Presentation |
ID vs Class in HTML
| ID | Class |
|---|---|
| Unique for one element | Can be used for many elements |
| Used for JavaScript targeting | Used mainly for styling groups |
Syntax: #id in CSS | Syntax: .class in CSS |
Example: <div id="header"> | Example: <div class="box"> |
Using Images as Hyperlinks
To use an image as a hyperlink, wrap the <img> tag inside an <a> tag.
<a href="https://example.com">
<img src="image.jpg" alt="Description">
</a>Understanding JavaScript Callback Hell
Callback Hell refers to deeply nested callbacks that make code unreadable and difficult to maintain.
doTask1(function(result1){
doTask2(result1, function(result2){
doTask3(result2, function(result3){
console.log("Done!");
});
});
});Problems: It is unreadable, hard to debug, and difficult to maintain.
Static Methods in JavaScript
Static methods belong to the class itself rather than to instances (objects) of the class.
class MathUtil {
static square(n) { return n * n; }
}
console.log(MathUtil.square(5)); // Output: 25These are typically used for utility functions.
JavaScript Callbacks Explained
A callback is a function passed as an argument to another function to be executed later.
function greet(name, callback){
callback("Hello " + name);
}
greet("Ishan", console.log);Comparing External, Internal, and Inline CSS
| Type | Location | Use Case |
|---|---|---|
| External CSS | Separate .css file | Best for full websites |
| Internal CSS | <style> tag in <head> | Styles a single page |
| Inline CSS | Inside the HTML tag | Highest priority; generally bad practice |
CSS Specificity and Priority Order
No, external CSS is not more powerful than inline CSS. Inline CSS has the highest priority because it is applied directly to the element.
Priority Order:
Inline > Internal > External
However, external CSS is considered better practice because it separates design from content.
Checking Data Types with typeof
You can use the typeof operator to determine the data type of a variable:
typeof 10; // "number"
typeof "hello"; // "string"
typeof true; // "boolean"
typeof {}; // "object"JavaScript Class Inheritance
Class inheritance allows a class to inherit properties and methods from another class using the extends keyword.
class Animal {
speak() { console.log("Sound"); }
}
class Dog extends Animal {
bark() { console.log("Bark"); }
}
let d = new Dog();
d.speak(); // Inherited from parent
d.bark(); // Defined in childThe Single-Threaded Nature of JavaScript
✔ True.
JavaScript executes one line of code at a time using a single call stack. However, asynchronous tasks (like setTimeout, fetch, and Promises) are handled by the Event Loop, which allows for non-blocking behavior.
Managing Async Tasks with Promises
Promises are used to handle asynchronous operations more cleanly than callbacks, avoiding callback hell.
let p = new Promise((resolve) => {
setTimeout(() => resolve("Done"), 1000);
});
p.then(console.log);Advantages: Cleaner syntax and chainable asynchronous code.
AJAX: Asynchronous JavaScript and XML
AJAX is used to request data from a server without reloading the entire webpage.
Example using Fetch:
fetch("data.json")
.then(res => res.json())
.then(data => console.log(data));JSON Data Exchange and Conversion
JSON (JavaScript Object Notation) is a lightweight data exchange format.
Convert Object to JSON string:
let obj = {name: "Ishan", age: 20};
let json = JSON.stringify(obj);Convert JSON to Object:
let newObj = JSON.parse(json);Sending Network Requests with Fetch API
The Fetch API is used to send network requests to servers.
Common Methods:
- GET: Retrieve data
- POST: Send new data
- PUT: Update existing data
- DELETE: Remove data
// Example POST request
fetch("/login", {
method: "POST",
body: JSON.stringify({user: "abc"})
});Node.js Features and Architecture
Node.js is a JavaScript runtime built on Chrome’s V8 engine, primarily used for backend development.
Key Features:
- Event-driven architecture
- Non-blocking I/O
- Fast execution speeds
- Single-threaded nature
- Access to npm packages
Introduction to JSX and React DOM
JSX (JavaScript XML): Allows you to write HTML-like code directly inside JavaScript.
const element = <h1>Hello</h1>;React DOM: A library that efficiently updates the real DOM by using a Virtual DOM diffing algorithm.
ReactDOM.render(element, document.getElementById("root"));React Components and Props Explained
Component: A reusable UI building block.
function Greeting() { return <h2>Hello</h2>; }Props: Short for properties, these are read-only data passed from a parent component to a child.
function Greet(props) { return <h2>Hello {props.name}</h2>; }
<Greet name="Ishan" />MySQL vs MongoDB vs PostgreSQL
| Feature | MySQL | MongoDB | PostgreSQL |
|---|---|---|---|
| Type | Relational (SQL) | NoSQL (Document) | Relational (Advanced) |
| Data Format | Tables/Rows | JSON Documents | Tables/Rows |
| Best For | Standard web apps | Big data, flexible schemas | Complex queries |
| Strength | Fast and easy | Highly scalable | Reliable and ACID compliant |
CSS Flexbox and Grid Layouts
Flexbox
A 1D layout system used to arrange items in either a row or a column.
.container {
display: flex;
gap: 10px;
}Grid
A 2D layout system used to manage both rows and columns simultaneously.
.container {
display: grid;
grid-template-columns: auto auto auto;
}ReactDOM vs the Real DOM
ReactDOM is a package that provides methods to manage the browser’s DOM efficiently.
| ReactDOM (Virtual DOM) | Real DOM |
|---|---|
| Uses a Virtual representation | The browser’s actual object model |
| Updates only changed nodes | Re-renders the entire tree |
| Faster and more efficient | Slower for large UI updates |
| Batch updates | Updates immediately |
React State and Component Lifecycle
State
State is a built-in object used to store a component’s dynamic data. When state changes, the component re-renders.
Lifecycle Phases
- Mounting: Adding the component to the DOM.
- Updating: Changing state or props.
- Unmounting: Removing the component from the DOM.
Asynchronous JavaScript with Async and Await
Async and Await allow you to write asynchronous code that looks and behaves like synchronous code.
- async: Defines a function that returns a Promise.
- await: Pauses function execution until the Promise resolves.
async function getData() {
console.log("Start");
let result = await fetchData(); // Execution pauses here
console.log(result);
console.log("End");
}MongoDB: Creating Collections and Inserting Data
Mongo Shell Commands
db.createCollection("students");
db.students.insertMany([
{id: 1, name: "A", cgpa: 8.5, address: "Delhi"},
{id: 2, name: "B", cgpa: 7.2, address: "Kolkata"},
{id: 3, name: "C", cgpa: 9.1, address: "Mumbai"},
{id: 4, name: "D", cgpa: 6.8, address: "Pune"},
{id: 5, name: "E", cgpa: 8.1, address: "Chennai"}
]);Node.js Insertion Example
const { MongoClient } = require("mongodb");
async function run() {
const client = await MongoClient.connect("mongodb://localhost:27017");
const db = client.db("college");
await db.collection("students").insertOne({
id: 6, name: "F", cgpa: 7.9, address: "Hyderabad"
});
console.log("Document Inserted");
}
run();Filtering and Sorting MongoDB Documents
Find Students with CGPA between 7 and 9
db.students.find(
{ cgpa: { $gte: 7, $lte: 9 } },
{ name: 1, id: 1, _id: 0 }
);Sort Students by CGPA in Node.js
let data = await client.db("college").collection("students")
.find({}, { projection: {id: 1, name: 1, cgpa: 1}})
.sort({ cgpa: 1 })
.toArray();
console.log(data);HTML Form Elements and Data Submission
HTML forms allow users to provide input that can be sent to a server.
Common Elements:
<input type="text"><input type="password"><textarea><button type="submit">
Posting Data
<form action="/submit" method="POST">
<input type="text" name="username">
<button type="submit">Login</button>
</form>JavaScript ES6 Modules: Import and Export
Named Exports
// math.js
export const PI = 3.14;
export function add(a, b) { return a + b; }Importing Named Exports
import { PI, add } from "./math.js";Default Exports
export default function greet() { console.log("Hello"); }
import greet from "./math.js";MongoDB Aggregation and Employee Queries
Aggregation Examples
Count employees in ‘Sales’:
db.employees.find({department: "sales"}).count();Average salary per department:
db.employees.aggregate([
{ $group: { _id: "$department", avgSalary: { $avg: "$salary" } } }
]);Find highest salary:
db.employees.find().sort({salary: -1}).limit(1);