Web development
4.15K subscribers
425 photos
31 videos
99 files
99 links
Web development learning path

Frontend and backend resources.

HTML, CSS, JavaScript, React, APIs and project ideas.

Join πŸ‘‰ https://rebrand.ly/bigdatachannels

DMCA: @disclosure_bds
Contact: @mldatascientist
Download Telegram
Forwarded from Programming Quiz Channel
❀2
🀫 JavaScript Closures (The "Hidden" Power) 🧠

Closures are one of those JavaScript concepts that are heard everywhere but often remain a mystery.

πŸ”Ή 1. What is a Closure?

A closure is the combination of a function and the lexical environment within which that function was declared. Essentially, a closure has access to its outer function's scope, variables, and parameters, even after the outer function has finished executing.

πŸ”Ή 2. How They Work (The "Memory" of Functions)

When a function is created, it "remembers" the environment (variables, parameters) where it was created. If this function is passed around or returned from another function, it carries that remembered environment with it.

Example:
function outerFunction() {
let outerVariable = "I'm from the outer scope";

function innerFunction() { // This is the closure
print(outerVariable); // It can still access outerVariable!
}
return innerFunction;
}

const myClosure = outerFunction(); // outerFunction finishes, but its scope is remembered
myClosure(); // Calling the inner function

Output: I'm from the outer scope

πŸ”Ή 3. Common Use Cases

β€’ Data Privacy (Private Variables): You can create functions that have access to "private" variables that cannot be accessed directly from the outside.

Example:
function createCounter() {
let count = 0; // Private variable
return function() { // The closure
count++;
print(count);
};
}

const counter1 = createCounter();
counter1(); // Output: 1
counter1(); // Output: 2

const counter2 = createCounter(); // Creates a *new* closure with its own 'count'
counter2(); // Output: 1

Notice counter1 and counter2 have their own separate count.

β€’ Callback Functions: When you pass a function to another function (like setTimeout or event handlers), it often forms a closure.

β€’ Currying & Partial Application: Advanced techniques where functions are transformed to return new functions.

πŸ”Ή 4. The "Gotcha" (Loop Issue)

A classic mistake is using var inside a for loop to create functions that reference loop variables. Because var has function scope, all closures created inside the loop end up referencing the *last* value of the loop variable.

Example (The Problem):
// DON'T DO THIS with `var`
for (var i = 0; i < 3; i++) {
setTimeout(function() {
print(i); // Will print 3, 3, 3!
}, 100);
}

πŸ”Ή 5. The Fix (Using let or IIFEs)

Using let (which has block scope) or an Immediately Invoked Function Expression (IIFE) solves the loop issue by creating a new scope for each iteration.

Example (The Fix with let):
for (let i = 0; i < 3; i++) { // 'let' creates a new 'i' for each loop
setTimeout(function() {
print(i); // Will correctly print 0, 1, 2!
}, 100);
}

🎯 What you should do

βœ”οΈ Understand that functions "remember" their creation environment
βœ”οΈ See how closures enable data privacy
βœ”οΈ Recognize and fix the common loop variable "gotcha"
❀3
πŸ‘¨β€πŸ’» JavaScript Event Loop: A Complete Guide

If you’ve ever been confused why your JavaScript code runs in unexpected order, why setTimeout doesn’t always fire exactly when you want, or how async/await actually works under the hood, you’re not alone.

Most developers use promises and async code daily but still get surprised by bugs that come from not fully understanding the event loop.

This practical guide breaks it all down clearly:
βœ… How the JavaScript Event Loop really works behind the scenes
βœ… Call Stack, Web APIs, Callback Queue, and Microtask Queue explained
βœ… The difference between setTimeout, Promises, and async/await
βœ… Common mistakes that cause blocking or unexpected behavior
βœ… Real-world examples and mental models you can actually use


πŸ”— Read the Full Guide Here

@web_dev_bds
❀1πŸ‘1
Forwarded from Programming Quiz Channel
In a relational database, which normal form specifically eliminates transitive dependencies?
Anonymous Quiz
12%
1NF
39%
2NF
33%
3NF
17%
BCNF
πŸ”Authentication vs. Authorization πŸ›‚

These two terms sound almost identical, but they represent two completely different steps in web security. Mixing them up can lead to massive security holes in your application.

πŸ”Ή 1. Authentication (AuthN): "Who are you?"

Authentication is the process of verifying the identity of a user. It’s the very first step. The system checks if you are who you claim to be.

β€’ Common Methods: Entering a username/password, using Fingerprint/FaceID, or logging in via Google/GitHub.
β€’ Success means: "Yes, this is definitely John Doe."

πŸ”Ή 2. Authorization (AuthZ): "What are you allowed to do?"

Authorization happens after authentication. Once the system knows who you are, it checks your permissions to see what parts of the app you can access.

β€’ Common Examples: Can this user delete a post? Can they see the admin billing page? Are they a "Premium" member or a "Free" member?
β€’ Success means: "John Doe is logged in, but he is NOT an admin, so he cannot delete this user."

πŸ”Ή 3. The "Airport Analogy" (Easy to Remember!)

β€’ Authentication: Showing your Passport at the security desk. It proves your identity.
β€’ Authorization: Showing your Boarding Pass. It proves you have permission to sit in a specific seat or enter the VIP lounge.

πŸ”Ή 4. How they are implemented

β€’ Authentication Tools:
β€’ JWT (JSON Web Tokens): For stateless mobile/web apps.
β€’ Sessions/Cookies: Traditional server-side login.
β€’ OAuth: Letting users log in via "Sign in with Google."

β€’ Authorization Tools:
β€’ RBAC (Role-Based Access Control): Assigning roles like "Admin," "Editor," or "User."
β€’ ABAC (Attribute-Based Access Control): Permissions based on specific rules (e.g., "Only the author can edit this post").

πŸ”Ή 5. Key Takeaway

You can be Authenticated (logged in) but NOT Authorized (no permission) to see a specific page. This is why you sometimes see a 403 Forbidden error instead of a 401 Unauthorized error.

πŸ‘‰ Authentication is the door; Authorization is the floor you’re allowed to visit!

🎯 What you should do

βœ”οΈ Distinguish between identity (AuthN) and permissions (AuthZ)
βœ”οΈ Identify which error codes (401 vs 403) belong to which concept
βœ”οΈ Use roles to manage what users can do in your app
❀5
β–ŽCommon React.js Terms

1. Component: A reusable piece of UI that can manage its own state and lifecycle. Components can be functional or class-based.

2. JSX (JavaScript XML): A syntax extension for JavaScript that allows writing HTML-like code within JavaScript, commonly used to define React components.

3. Props (Properties): A mechanism for passing data from parent components to child components. Props are read-only and help in making components dynamic.

4. State: An object that determines the behavior and rendering of a component. Unlike props, state is managed within the component and can change over time.

5. Lifecycle Methods: Special methods in class components that allow developers to hook into different stages of a component's lifecycle, such as componentDidMount, componentDidUpdate, and componentWillUnmount.

6. Hooks: Functions that let you use state and other React features in functional components. Common hooks include useState, useEffect, and useContext.

7. Virtual DOM: A lightweight representation of the actual DOM that React uses to optimize rendering performance by minimizing direct manipulation of the real DOM.

8. React Router: A library for managing navigation and routing in a React application, allowing for dynamic rendering of components based on URL paths.

9. Higher-Order Component (HOC): A pattern for reusing component logic by creating a function that takes a component and returns a new component with additional props or functionality.

10. Context API: A feature that allows for sharing values (like state) between components without explicitly passing props through every level of the component tree.

11. Redux: A state management library often used with React to manage global application state through a unidirectional data flow, using actions and reducers.

12. Reducer: A pure function in Redux that takes the current state and an action as arguments and returns a new state, used to manage state transitions.

13. Action: An object that describes an event or change in the application state, typically containing a type and optional payload.

14. Thunk: A middleware for Redux that allows action creators to return functions instead of plain action objects, enabling asynchronous operations.

15. Fragment: A lightweight wrapper that allows grouping multiple elements without adding extra nodes to the DOM, used to return multiple children from a component.

16. Portal: A feature that allows rendering a component's children into a different part of the DOM tree, outside of its parent hierarchy.

17. Memoization: A performance optimization technique that involves caching the results of expensive function calls to avoid unnecessary recalculations.

18. Controlled Component: A form element whose value is controlled by React state, ensuring that the React component is the single source of truth for the input value.

19. Uncontrolled Component: A form element that maintains its own internal state and is not directly controlled by React, often using refs to access its value.

20. React DevTools: A browser extension that provides debugging tools for inspecting React component hierarchies, props, state, and performance metrics.
❀2πŸ”₯2
βœ… JavaScript Advanced Concepts You Should Know πŸ”πŸ’»

These concepts separate beginner JS from production-level code. Understanding them helps with async patterns, memory, and modular apps.

1️⃣ Closures
A function that "closes over" variables from its outer scope, maintaining access even after the outer function returns. Useful for data privacy and state management.
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}
const counter = outer();
counter(); // 1
counter(); // 2


2️⃣ Promises & Async/Await
Promises handle async operations; async/await makes them read like sync code. Essential for APIs, timers, and non-blocking I/O.
// Promise chain
fetch(url).then(res => res.json()).then(data => console.log(data)).catch(err => console.error(err));

// Async/Await (cleaner)
async function getData() {
try {
const res = await fetch(url);
const data = await res.json();
console.log(data);
} catch (err) {
console.error(err);
}
}


3️⃣ Hoisting
Declarations (var, function) are moved to the top of their scope during compilation, but initializations stay put. let/const are block-hoisted but in a "temporal dead zone."
console.log(x); // undefined (hoisted, but not initialized)
var x = 5;

console.log(y); // ReferenceError (temporal dead zone)
let y = 10;


4️⃣ The Event Loop
JS is single-threaded; the event loop processes the call stack, then microtasks (Promises), then macrotasks (setTimeout). Explains why async code doesn't block.

5️⃣ this Keyword
Dynamic binding: refers to the object calling the method. Changes with call site, new, or explicit binding.
const obj = {
name: "Sam",
greet() {
console.log(`Hi, I'm ${this.name}`);
},
};
obj.greet(); // "Hi, I'm Sam"

// In arrow function, this is lexical
const arrowGreet = () => console.log(this.name); // undefined in global


6️⃣ Spread & Rest Operators
Spread (...) expands iterables; rest collects arguments into arrays.
const nums = [1, 2, 3];
const more = [...nums, 4]; // [1, 2, 3, 4]

function sum(...args) {
return args.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3); // 6


7️⃣ Destructuring
Extract values from arrays/objects into variables.
const person = { name: "John", age: 30 };
const { name, age } = person; // name = "John", age = 30

const arr = [1, 2, 3];
const [first, second] = arr; // first = 1, second = 2


8️⃣ Call, Apply, Bind
Explicitly set 'this' context. Call/apply invoke immediately; bind returns a new function.
function greet() {
console.log(`Hi, I'm ${this.name}`);
}
greet.call({ name: "Tom" }); // "Hi, I'm Tom"

const boundGreet = greet.bind({ name: "Alice" });
boundGreet(); // "Hi, I'm Alice"


9️⃣ IIFE (Immediately Invoked Function Expression)
Self-executing function to create private scope, avoiding globals.
(function() {
console.log("Runs immediately");
let privateVar = "hidden";
})();


πŸ”Ÿ Modules (import/export)
ES6 modules for code organization and dependency management.
// math.js
export const add = (a, b) => a + b;
export default function multiply(a, b) { return a * b; }

// main.js
import multiply, { add } from './math.js';
console.log(add(2, 3)); // 5


πŸ’‘ Practice these in a Node.js REPL or browser console to see how they interact.
❀3
β–ŽCommon Node.js Terms

1. Node.js: An open-source, cross-platform JavaScript runtime environment that allows developers to execute JavaScript code on the server side.

2. NPM (Node Package Manager): The default package manager for Node.js, used to install, share, and manage dependencies in Node.js applications.

3. Express.js: A minimal and flexible Node.js web application framework that provides a robust set of features for building web and mobile applications.

4. Middleware: Functions in Express.js that have access to the request and response objects, allowing developers to execute code, modify requests and responses, and end requests.

5. Asynchronous Programming: A programming paradigm in Node.js that allows operations to run concurrently without blocking the main execution thread, often using callbacks, promises, or async/await syntax.

6. Event Loop: The mechanism that allows Node.js to perform non-blocking I/O operations by offloading operations to the system kernel whenever possible.

7. Callback: A function passed as an argument to another function that is executed after a certain event or operation has completed.

8. Promise: An object representing the eventual completion (or failure) of an asynchronous operation and its resulting value, providing a cleaner alternative to callbacks.

9. Async/Await: Syntactic sugar built on top of promises that allows developers to write asynchronous code in a more synchronous manner, improving readability.

10. RESTful API: An architectural style for designing networked applications that rely on stateless communication and standard HTTP methods (GET, POST, PUT, DELETE) to interact with resources.

11. Socket.io: A library for real-time web applications that enables bi-directional communication between clients and servers over WebSockets.

12. Mongoose: An Object Data Modeling (ODM) library for MongoDB and Node.js, providing a schema-based solution for modeling application data.

13. Cluster Module: A built-in Node.js module that enables the creation of child processes that share the same server port, allowing for better utilization of multi-core systems.

14. Environment Variables: Key-value pairs used to configure applications at runtime, often containing sensitive information like API keys and database connection strings.

15. Stream: An abstract interface for working with streaming data in Node.js, allowing for efficient processing of large amounts of data without loading everything into memory at once.

16. File System (fs) Module: A built-in Node.js module that provides an API for interacting with the file system, allowing developers to read, write, and manipulate files and directories.

17. Package.json: A JSON file that contains metadata about a Node.js project, including its dependencies, scripts, and configuration settings.

18. Debugging: The process of identifying and resolving issues or bugs in a Node.js application, often using tools like the built-in debugger or external libraries like debug.

19. Web Framework: A framework built on top of Node.js that simplifies web application development by providing tools and libraries for routing, middleware, and templating. Examples include Express.js and Koa.js.

20. Deployment: The process of making a Node.js application available on a server or cloud platform so that it can be accessed by users over the internet. Common platforms include Heroku, AWS, and DigitalOcean.
❀2πŸ‘1
Forwarded from Programming Quiz Channel
What is the primary trade-off of using an event-driven, single-threaded architecture (like Node.js) compared to multi-threaded servers?
Anonymous Quiz
50%
Handles I/O-bound concurrency efficiently but struggles with CPU-bound tasks
24%
Cannot handle multiple requests simultaneously
11%
Cannot use TLS/SSL
16%
Uses more memory per connection
❀3
❓Ever wondered how YouTube manages such a massive codebase?

When we think about building something like , the first question that comes is:

πŸ‘‰ β€œDo they keep everything in one project or split it into many?”

The answer is interesting.


🧠 Monorepo Concept (Simple Understanding)

A monorepo means keeping multiple projects or services inside a single repository.

So instead of having:

- one repo for frontend
- one repo for backend
- one repo for ML

Everything lives in one place.


πŸ—οΈ How It Looks (Simplified)

Imagine a structure like this:

youtube-monorepo/
β”‚
β”œβ”€β”€ frontend/
β”œβ”€β”€ backend/
β”œβ”€β”€ services/
β”‚   β”œβ”€β”€ auth-service/
β”‚   β”œβ”€β”€ video-service/
β”‚   β”œβ”€β”€ recommendation-service/
β”‚
β”œβ”€β”€ shared/
β”œβ”€β”€ infra/

Each folder is like its own mini project, but all are connected under one repo.


βš™οΈ Why Companies Use Monorepo

βœ… 1. Easy Collaboration
All teams work in the same codebase.
No confusion about versions or dependencies.

βœ… 2. Shared Code
Common utilities (like authentication logic, validation, configs) can be reused easily.

βœ… 3. Consistency
Same coding standards, same tools, same structure across all services.

βœ… 4. Easier Refactoring
If you change something globally, you can update everything in one place.


πŸ”— How Things Work Together

Even though everything is in one repo:

- Frontend still talks to backend via APIs
- Backend is still split into multiple services
- Each service can use different languages

πŸ‘‰ Monorepo is about code organization, not about merging everything into one app.


⚠️ But Is It Always Good?

Not always.

❌ Challenges:

- Repo can become very large
- Build times can increase
- Requires strong tooling and discipline

That’s why companies use advanced tools like:


πŸ’‘ Reality Check

Companies like YouTube use a modified version of monorepo with strong tooling, not a simple GitHub repo.

πŸ‘‰ It’s not just about storing code together
πŸ‘‰ It’s about managing complexity at scale


πŸš€ Final Thought

Monorepo is not about making things simple.
It’s about making large systems manageable.

If you're building small projects, you don’t need this yet.
But understanding it early gives you a big advantage.
❀1