README
JS DEPTH EXPLORATION
- in do while loop the condition is checked after the loop so if the condition does not match still will show one output
let num = 10;
do {
console.log("This will run once");
} while (num < 5);
- slice vs splice
const a = [1,2,3,4,5]
const b = a.slice(1,3) // index one theke suru kore index 3 er age porjonto
console.log(b)
const a = [1,2,3,4,5]
const b = a.splice(1,2, 5) // here 1 means starting index 2 means from the index how many to delete and 5 means what to put in the deleted position
console.log(a)
- break in a loop (completely stops the loop )
for (let i = 1; i <= 5; i++) {
if (i === 3) {
break;
}
console.log(i);
}
let i = 1;
while (i <= 5) {
if (i === 4) {
break;
}
console.log(i);
i++;
}
- continue in a loop (continue = skips current iteration, but loop continues.)
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue;
}
console.log(i);
}
- Important: Be careful with while + continue to avoid infinite loops.
let i = 0;
while (i < 5) {
i++; // increment first
if (i === 3) {
continue;
}
console.log(i);
}
- power to a number
math.pow(height,2)
console.log(typeof(10%"10"))
console.log(!true)
console.log(!"")
console.log(!" ")
console.log(true + 3)
console.log(true + 3)
console.log(typeof isNaN)
console.log(isNaN(20))
console.log(isNaN("20"))
console.log(isNaN("ABC"))
- exploration of array
- push pop shift unshift
let fruits = ["apple", "banana", "cherry"];
console.log(fruits.slice(1,2))
fruits.push("s","a")
console.log(fruits)
console.log(fruits.indexOf("a"))
console.log(fruits[fruits.length - 1]);
console.log(fruits); // ["apple", "banana", "cherry"]
fruits.push("orange");
console.log(fruits); // ["apple", "banana", "cherry", "orange"]
let last = fruits.pop();
console.log(last); // "orange"
console.log(fruits); // ["apple", "banana", "cherry"]
fruits.unshift("mango");
console.log(fruits); // ["mango", "apple", "banana", "cherry"]
let first = fruits.shift();
console.log(first); // "mango"
console.log(fruits); // ["apple", "banana", "cherry"]
let fah = [0,1,2,3,4,5,6]
console.log(fah.slice(2))
const ah = fah.slice(0,2).concat(fah.slice(5))
let fah = [0,1,2,3,4,5,6]
const a = fah.splice(0,2,100)
console.log(fah)
console.log(fah.includes(0))
console.log(Array.isArray(fah))
let c = ["a","b","c","d"]
let d = ["e", "f", "g", "h", "i"]
console.log(c.concat(d))
console.log(c.join(" "))
console.log(null == undefined); // true
console.log(null === undefined); // false
- understanding loops
let fah = [0,1,2,3,4,5,6]
for(const num of fah){
console.log(num)
}
let num = 0
while (num < 6){
console.log("LOoping")
num = num+1
}
- pure for loop
for(let num = 0 ; num <5; num++){
console.log(num)
}
- playing with string
let st = "I am Shahnawaz Sazid"
console.log(st.split(" "))
let reverse = ""
for (const letter of st){
reverse = letter+reverse
}
console.log(reverse)
const person = {
name : "sazid",
age : 27,
profession : "developer",
salary : 25000,
married : true,
}
const income = person.salary
// console.log(income)
const keys = Object.keys(person)
console.log(keys)
const values = Object.values(person)
console.log(values)
const person = {
name : "sazid",
age : 27,
profession : "developer",
salary : 25000,
married : true,
}
delete person.age
console.log(person)
- Remove duplicate
function noDup(arr){
let noDupArray = [];
for(arrElm of arr){
if(noDupArray.includes(arrElm) === false){
noDupArray.push(arrElm)
}
}
return noDupArray
}
const array = [1,1,2,3,4,4,5]
const newArr = noDup(array)
console.log(newArr)
- some techniques of js
const array = [1,1,2,3,4,4,5]
const min = Math.min(...array)
console.log(min)
const max = Math.max(...array)
console.log(max)
console.log(Math.PI)
console.log(Math.abs(1-5))
console.log(Math.round(4.5))
console.log(Math.floor(4.5))
console.log(Math.ceil(4.5))
console.log(Math.random()*10)
console.log(new Date())
const date = new Date()
console.log(date.getDate())
- variable swap without temp and destructuring
let a = 5;
let b = 7;
console.log(a, b)
a = b;
b = a;
console.log(a, b)
let a = 5;
let b = 7;
const temp = a;
a = b;
b = temp;
console.log(a,b)
-
dom understanding
-
event bubbling and stop propagation
<!DOCTYPE html>
<html>
<head>
<title>Event Bubbling Example</title>
<style>
#parent {
padding: 40px;
background-color: lightblue;
}
#child {
padding: 20px;
background-color: coral;
border: none;
cursor: pointer;
}
</style>
</head>
<body>
<div id="parent">
Parent Div
<button id="child">Click Me</button>
</div>
<script>
document.getElementById("parent").addEventListener("click", () => {
console.log("Parent clicked");
});
document.getElementById("child").addEventListener("click", (event) => {
console.log("Child clicked");
event.stopPropagation(); // Stops bubbling
});
</script>
</body>
</html>
- ANOTHER EXAMPLE OF DOM PROPAGATION
<!-- <!DOCTYPE html>
<html>
<head>
<title>Event Bubbling Example</title>
<style>
#parent {
padding: 40px;
background-color: lightblue;
}
#child {
padding: 20px;
background-color: coral;
border: none;
cursor: pointer;
}
</style>
</head>
<body>
<div id="parent">
Parent Div
<button id="child">Click Me</button>
</div>
<script>
document.getElementById("parent").addEventListener("click", () => {
console.log("Parent clicked");
});
document.getElementById("child").addEventListener("click", (event) => {
console.log("Child clicked");
event.stopPropagation(); // Stops bubbling
});
</script>
</body>
</html> -->
<!doctype html>
<html>
<head>
<title>stopImmediatePropagation Example</title>
</head>
<body>
<div id="parent" style="padding: 40px; background: lightblue">
Parent Div
<button id="child" style="padding: 20px">Click Me</button>
</div>
<script>
const parent = document.getElementById("parent");
const child = document.getElementById("child");
parent.addEventListener("click", () => {
console.log("Parent clicked");
});
// First listener on child
child.addEventListener("click", (event) => {
console.log("First child listener");
// event.stopImmediatePropagation(); // 👈 Stops everything
// event.stopPropagation();
});
// Second listener on child
child.addEventListener("click", () => {
console.log("Second child listener");
});
</script>
</body>
</html>
- event delegation
<!DOCTYPE html>
<html>
<head>
<title>Event Delegation Example</title>
<style>
body {
font-family: Arial;
}
#list {
background-color: lightblue;
padding: 20px;
width: 200px;
}
li {
background-color: white;
margin: 5px 0;
padding: 8px;
cursor: pointer;
}
button {
margin-top: 15px;
}
</style>
</head>
<body>
<h2>Event Delegation Demo</h2>
<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<button id="addBtn">Add New Item</button>
<script>
const list = document.getElementById("list");
const button = document.getElementById("addBtn");
// 🔥 Event Delegation: One listener on parent
list.addEventListener("click", function(event) {
console.log("Current Target:", event.currentTarget);
console.log("Actual Clicked Element:", event.target);
// Make sure user clicked on LI only
if (event.target.tagName === "LI") {
alert("You clicked " + event.target.textContent);
}
});
// Add new item dynamically
button.addEventListener("click", function() {
const newItem = document.createElement("li");
newItem.textContent = "New Item";
list.appendChild(newItem);
});
</script>
</body>
</html>
- capturing vs bubling
<!DOCTYPE html>
<html>
<head>
<title>Capturing vs Bubbling</title>
<style>
#parent {
padding: 40px;
background-color: lightblue;
}
#child {
padding: 20px;
background-color: coral;
border: none;
cursor: pointer;
}
</style>
</head>
<body>
<div id="parent">
Parent Div
<button id="child">Click Me</button>
</div>
<script>
const parent = document.getElementById("parent");
const child = document.getElementById("child");
// 🔵 CAPTURING (third parameter = true)
parent.addEventListener("click", function() {
console.log("Parent - Capturing");
}, true);
child.addEventListener("click", function() {
console.log("Child - Capturing");
}, true);
// 🔴 BUBBLING (default behavior)
parent.addEventListener("click", function() {
console.log("Parent - Bubbling");
});
child.addEventListener("click", function() {
console.log("Child - Bubbling");
});
</script>
</body>
</html>
- mutable
let arr = [1, 2, 3];
arr.push(4);
console.log(arr); // [1, 2, 3, 4]
let user = { name: "Shahnawaz" };
user.name = "Sazid";
console.log(user.name); // Sazid
- immutable
let str = "Hello";
str[0] = "Y";
console.log(str); // Hello
let x = 10;
let y = x;
y = 20;
console.log(x); // 10
console.log(y); // 20
| Feature | Mutable | Immutable |
|---|---|---|
| Can change original? | ✅ Yes | ❌ No |
| Memory usage | Less | More (new copy) |
| Predictability | Lower | Higher |
| Used in React | ❌ Avoid | ✅ Preferred |
- normal function vs arrow function
| Feature | Regular Function | Arrow Function |
|---|---|---|
| Syntax | Longer | Shorter |
this | Dynamic | Lexical |
arguments | ✅ Yes | ❌ No |
| Constructor | ✅ Yes | ❌ No |
| Hoisting | ✅ Yes | ❌ No |
| Implicit return | ❌ No | ✅ Yes |
- playing with object
const person = {
name : "sazid",
age : 27,
profession : "developer",
salary : 25000,
married : true,
}
const entries = Object.entries(person)
console.log(entries)
Object.seal(person)
Object.freeze(person)
Questions
- what is es6 ? have you ever used anything from es6?
- let and const Block-scoped variables (better than var).
let age = 25; // can change
const name = "Sazid"; // cannot change
- Arrow Functions (=>) Shorter and cleaner functions.
// ES5
function add(a, b) {
return a + b;
}
// ES6
const add = (a, b) => a + b;
- Template Literals Use backticks for string interpolation.
const name = "Sazid";
console.log(`Hello ${name}`);
- Destructuring Extract values easily from objects/arrays.
const user = { name: "Sazid", age: 25 };
const { name, age } = user;
console.log(name);
- Default Parameters Set default values in functions.
const greet = (name = "Guest") => {
console.log(`Hello ${name}`);
};
greet(); // Hello Guest
- Spread Operator (...) Copy or merge arrays/objects.
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4];
- Rest Parameters Collect multiple arguments into an array.
const sum = (...numbers) => {
return numbers.reduce((a, b) => a + b, 0);
};
- Modules (Import/Export) Used in modern JavaScript apps.
// math.js
export const add = (a, b) => a + b;
// main.js
import { add } from "./math.js";
- Classes (OOP) Cleaner syntax for object-oriented programming.
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hi, I'm ${this.name}`);
}
}
- Promises (Async Programming)
const fetchData = () => {
return new Promise((resolve) => {
setTimeout(() => resolve("Done!"), 1000);
});
};
- advantages of arrow function
- Implicit Return
- shorter syntax
- No this Confusion (Lexical this)Biggest advantage Arrow functions do not have their own this. They inherit this from the parent scope.
Problem with normal function:
const obj = {
name: "Sazid",
greet: function () {
setTimeout(function () {
console.log(this.name); // undefined
}, 1000);
},
};
Arrow function fix:
const obj = {
name: "Sazid",
greet() {
setTimeout(() => {
console.log(this.name); // Sazid ✅
}, 1000);
},
};
PART 1 — What is this in JavaScript?
- Simple meaning: this = “Who is calling the function?”
const obj = {
name: "Sazid",
sayName() {
console.log(this.name);
},
};
obj.sayName();
-
obj is calling sayName(), so this = obj
-
Example 2 — Function alone
function test() {
console.log(this);
}
test();
- Output (browser): window Because no object called it. so default
this = window (browser)
this = global (Node)
PART 2 — Rule of this
✅ Rule 1
Object calls → this = object
❌ Rule 2
No object → this = global
PART 3 — The setTimeout Problem
const obj = {
name: "Sazid",
greet() {
setTimeout(function () {
console.log(this.name);
}, 1000);
},
};
Why undefined?
Because:
setTimeout runs the function
NOT the object
PART 4 — Arrow Function Difference
Normal function:
Creates new this
Arrow function:
❗ Does NOT create this
It borrows from parent.
- What is Lexical Scope? Simple meaning:
Scope based on where code is written, not how it’s called.
“Lexical” = related to text/location.
- for this Call decides this in case of normal function
- Location decides this in case of arrow function
PART 12 — When to Use Arrow Functions
✅ Use arrow when:
Callbacks
setTimeout
Promises
Array methods (map, filter)
❌ Avoid arrow when:
Object methods
Constructors
Event listeners (sometimes)
sTRICT MODE IN JS
- Strict Mode is a safer way to run JavaScript that catches common mistakes and enforces cleaner coding rules.
fOR OF VS FOR IN
- FOR IN Iterates over: Keys / Property names of an object or array
Mostly used for: Objects
Output: Index (for arrays) or key (for objects)
const user = { name: "Sazid", age: 25 };
for (let key in user) {
console.log(key); // name, age
console.log(user[key]); // Sazid, 25
}
const arr = [10, 20, 30];
for (let index in arr) {
console.log(index); // 0, 1, 2
console.log(arr[index]); // 10, 20, 30
}
- FOR OF for…of (ES6)
Iterates over: Values of iterable objects (Array, String, Map, Set, etc.)
Mostly used for: Arrays, Strings, Sets, Maps
Output: Actual value
const arr = [10, 20, 30];
for (let value of arr) {
console.log(value); // 10, 20, 30
}
| Feature | for…in | for…of |
|---|---|---|
| Iterates over | Keys / property names | Values |
| Works on | Objects, Arrays (keys) | Iterables: Array, String, Map, Set |
| Output | Index/key | Actual value |
| Syntax advantage | Good for object props | Good for array/string values |
| ES Version | ES5 | ES6 |
Difference Between map and forEach in JavaScript
forEach
Purpose: Executes a function for each element without returning anything
Returns: undefined
Use Case: When you want to perform side effects like logging or updating DOM
const numbers = [1, 2, 3];
numbers.forEach(num => {
console.log(num * 2);
});
// Output:
// 2
// 4
// 6
map
Purpose: Transforms each element and returns a new array
Returns: New array of same length
Use Case: When you want a new array based on original array
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
| Feature | forEach | map |
|---|---|---|
| Return Value | undefined | New array |
| Purpose | Side effects | Transforming data |
| Chainable | No | Yes |
| Mutates Original? | Depends (can mutate) | No (creates new array) |
| Example Use Case | Logging, updating DOM | Creating transformed array |
Playing with OOP
- To ensure the similarity of similar item class is used
class Product {
country = 'Bangladesh';
speak(talk) {
console.log(`Kotha bolo ${talk}`)
}
}
const lenovo = new Product()
lenovo.speak("kisu komu na")
Class = Blueprint / Template
A class is like a cookie cutter.
It defines what a thing has and what it can do.
class Product {
country = "Bangladesh" // every product has this
constructor(name) { // sets the product name
this.name = name
}
speak(talk) { // product can speak
console.log(`Kotha bolo ${talk}`)
}
}
const lenovo = new Product('Lebu');
Constructor = First Setup
Constructor is like filling the cookie cutter with dough.
It sets the initial values when you create an object.
constructor(name) {
this.name = name
}
this.name → what this specific object will be called
You pass the name when creating the object:
- tricks to remember
Class = Recipe
Object = Real food
Constructor = Naming the food
this = This specific food
Method = What food can do
- Understanding inheritance
class Vehicle {
constructor (name,price){
this.name = name;
this.price = price;
}
move(){
console.log('Gari Moving')
}
}
class Bus extends Vehicle{
constructor(name, price,seat,ticketPrice){
super(name,price)
this.seat = seat;
this.ticketPrice = ticketPrice;
}
}
const bus = new Bus('turag', 20000, 40, 200)
- prototypical chain
const person = {
talk() {
console.log("Talking...");
}
};
const student = {
study() {
console.log("Studying...");
}
};
// Link student → person
student.__proto__ = person;
student.study(); // Own method
student.talk(); // From prototype (person)
class Animal {
eat() {
console.log("Eating...");
}
}
class Dog extends Animal {
bark() {
console.log("Barking...");
}
}
const myDog = new Dog();
myDog.bark(); // Own method
myDog.eat(); // From Animal (prototype)
- class vs object
| Feature | Class 🧱 | Object 🎯 |
| ---------- | -------------------- | ----------------------- |
| Meaning | Blueprint / template | Instance of class |
| Real data | ❌ No | ✅ Yes |
| Memory use | Once | Multiple instances |
| Created by | `class` keyword | `new` keyword |
| Example | `class Car {}` | `const car = new Car()` |
- ternary vs optional chaining
| Feature | Optional Chaining (?.) | Ternary Operator (? :) |
|---|---|---|
| Purpose | Prevent errors | Conditional logic |
| Works on | Objects/properties | Any condition |
| Returns | undefined if missing | One of two values |
| Replaces | Null checks | if/else |
| Feature | Global Scope 🌍 | Block Scope 📦 |
|---|---|---|
| Accessible | Everywhere | Only inside {} |
| Keywords | var, let, const | let, const |
| Risk | High (conflicts) | Safer |
- pass by value
let a = 10;
function change(x) {
x = 20;
}
change(a);
console.log(a); // 10 (unchanged)
- pass by reference
let obj = { name: "Sazid" };
function change(o) {
o.name = "Ali";
}
change(obj);
console.log(obj.name); // Ali
| Feature | Pass by Value 🔢 | Pass by Reference 📦 |
|---|---|---|
| Data type | Primitives | Objects, Arrays |
| Copy or link | Copy | Memory reference |
| Affects original? | ❌ No | ✅ Yes |
| Example | number, string | object, array |
Scope → Where variables live
Global → Accessible everywhere
Block → Inside {}
Hoisting → Declarations move to top
Closure → Function remembers outer variables
Callback → Function passed to another function
Pass by value → Copy
Pass by reference → Memory link
- Check if array or not
const arr = [1, 2, 3];
console.log(Array.isArray(arr)); // true
- implicit conversion
| Operation | Conversion Type | Example |
|---|---|---|
+ with string | Number → String | 5 + "5" → "55" |
-, *, / | String → Number | "10" * 2 → 20 |
if or Boolean context | Any type → Boolean | "" → false |
Comparison (==) | JS tries to convert to same type | "5" == 5 → true |
| Variable Type | Passed As | Effect Inside Function |
|---|---|---|
| Primitive (number, string, boolean, null, undefined, symbol, bigint) | Value (copy) | Original variable unchanged |
| Non-primitive (object, array, function) | Reference (memory address) | Original variable can be changed |
- hoisting with var
console.log(a); // undefined
var a = 10;
console.log(a); // 10
var a; // declaration hoisted
console.log(a); // undefined
a = 10; // assignment happens here
console.log(a); // 10
| Feature | Hoisted? | Initialized? | Can use before declaration? |
|---|---|---|---|
var | Yes | undefined | ✅ undefined |
let | Yes | ❌ No (TDZ) | ❌ ReferenceError |
const | Yes | ❌ No (TDZ) | ❌ ReferenceError |
| Function declaration | Yes | Yes | ✅ Yes |
Function expression (var) | Yes (variable) | undefined | ❌ TypeError |
Function expression (let/const) | Yes (variable) | TDZ | ❌ ReferenceError |
| Lifecycle Phase | Class Component Method | useEffect Equivalent |
|---|---|---|
| Mounting | componentDidMount | useEffect(() => {}, []) |
| Updating | componentDidUpdate | useEffect(() => {}, [deps]) |
| Unmounting | componentWillUnmount | return () => { ... } |
-
- What is the Higher Order function & callback function in JavaScript? ANSWER WITH EXAMPLE
-
callback
function greet(name, callback) {
console.log("Hello " + name);
callback(); // calling the callback
}
function sayBye() {
console.log("Goodbye!");
}
greet("Sazid", sayBye);
- Higher order function
function calculate(a, b, operation) {
return operation(a, b);
}
function add(x, y) {
return x + y;
}
console.log(calculate(5, 3, add));
| Concept | Meaning |
|---|---|
| Callback | Function passed into another function |
| Higher-Order Function | Function that takes or returns functions |
- call bind and this
| Method | Calls function immediately? | Arguments format |
|---|---|---|
| call() | ✅ Yes | Comma separated |
| apply() | ✅ Yes | Array |
| bind() | ❌ No (returns new function) | Comma separated |
- Why do we need them?
Sometimes this points to the wrong object. call/apply/bind to manually set this
- base example
const person1 = {
name: "Sazid"
};
const person2 = {
name: "Rahim"
};
function greet(city) {
console.log(`Hi I am ${this.name} from ${city}`);
}
// 1️⃣ call()
// 👉 Calls function immediately
// 👉 Arguments passed normally
greet.call(person1, "Dhaka");
greet.call(person2, "Chittagong");
// 2️⃣ apply()
// 👉 Same as call
// 👉 But arguments in array
greet.apply(person1, ["Dhaka"]);
greet.apply(person2, ["Sylhet"]);
// 3️⃣ bind()
// 👉 Does NOT call immediately
// 👉 Returns a new function
const newFunc = greet.bind(person1, "Dhaka");
newFunc(); // called later
| Use Case | Method |
|---|---|
| Immediate execution | call/apply |
| Arguments already in array | apply |
| Reusable function | bind |
| React event handlers | bind |
| Feature | Callback Hell | Promise Hell |
|---|---|---|
| Based on | Callbacks | Promises |
| Shape | Pyramid nesting | Long chains |
| Error handling | Very hard | Slightly better |
| Readability | Worst | Better but still messy |
- promise
const myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Task completed!");
} else {
reject("Task failed!");
}
});
myPromise
.then(result => console.log(result))
.catch(error => console.log(error));
- SHALLOW COPY AND DEEP COPY
const original = {
name: "Sazid",
address: {
city: "Dhaka"
}
};
const copy = { ...original }; // shallow copy
copy.name = "Rahim";
copy.address.city = "Sylhet";
console.log(original.name); // Sazid ✅
console.log(original.address.city); // Sylhet ❌ changed!
original.address ─┐
├── same object
copy.address ───┘
const original = {
name: "Sazid",
address: {
city: "Dhaka"
}
};
const deepCopy = structuredClone(original);
deepCopy.address.city = "Sylhet";
console.log(original.address.city); // Dhaka ✅ unchanged
| Feature | Shallow Copy | Deep Copy |
|---|---|---|
| Nested objects | Shared | Fully copied |
| Memory | Less | More |
| Speed | Faster | Slower |
| Safe for nested data | ❌ No | ✅ Yes |
| Feature | relative | absolute | fixed | sticky |
|---|---|---|---|---|
| In normal flow | ✅ Yes | ❌ No | ❌ No | ✅ Initially |
| Reference point | Itself | Nearest positioned parent | Viewport | Scroll position |
| Moves on scroll | Yes | Yes | ❌ No | Sticks after scroll |
| Space reserved | ✅ Yes | ❌ No | ❌ No | ✅ Yes |
| Feature | Class Component | Functional Component with Hooks |
|---|---|---|
| Syntax | ES6 class | JavaScript function |
| State | this.state + this.setState | useState hook |
| Lifecycle | componentDidMount, componentDidUpdate | useEffect hook |
this | Required (binding) | Not needed |
| Readability | Verbose | Cleaner, concise |
| Performance | Slightly slower (older React versions) | Slightly faster (modern React) |
| Reusability | Harder to share logic | Hooks allow custom reusable logic |
| Type | Meaning | Example |
|---|---|---|
| Pseudo-class | Element state | :hover, :first-child |
| Pseudo-element | Part of element or insert content | ::before, ::first-letter |
| Method | Horizontal | Vertical | Notes |
|---|---|---|---|
| Flexbox | justify-content: center | align-items: center | Good for 1D layout (row or column) |
| Grid | justify-items: center | align-items: center | Works for 2D layout; shorthand → place-items: center |
| Dependency Array | When effect runs |
|---|---|
[] | Only once, after first render (componentDidMount) |
[dep1, dep2] | Runs after first render and whenever dep1 or dep2 changes |
| omitted | Runs after every render (componentDidMount + componentDidUpdate) |
| Feature | useState | useReducer |
|---|---|---|
| Complexity | Simple state | Complex state logic |
| Update | Direct setter function | Reducer function + action |
| Multiple state values | Multiple useState calls | One state object handled by reducer |
| Readability | Simple for few values | Better for many interdependent states |
| Debugging | Easy for small apps | Easier with predictable reducer pattern |
| Technique | Use Case |
|---|---|
React.memo | Memoize component to prevent re-render if props unchanged |
useCallback | Memoize functions passed as props to children |
| Both together | Optimize parent → child re-render chains |
| Feature | Local Storage | Session Storage | Cookies |
|---|---|---|---|
| Storage size | ~5–10 MB | ~5 MB | ~4 KB |
| Expiration | No expiration; persists until manually cleared | Expires when browser/tab closes | Set via Expires or Max-Age; can persist across sessions |
| Scope | Shared across all tabs/windows of same origin | Only accessible in the tab/window that created it | Sent to server with every request (optional) |
| Access | JavaScript only | JavaScript only | JavaScript (document.cookie) + server |
| Use case | Store long-term data (e.g., theme, preferences, tokens) | Temporary data for current session (e.g., form data) | Authentication, session tracking, server-side reading |
- express life cycle
Client Request
↓
Application-Level Middleware
↓
Router-Level Middleware
↓
Route Handler
↓
Response Sent
↓
Error-Handling Middleware (if any)
- handling error
Route or Middleware throws error
↓
Call next(err)
↓
Error-handling middleware (err, req, res, next)
↓
Send response to client
- child thread vs worker thread
| Feature | Child Process | Worker Thread |
|---|---|---|
| Separate process? | Yes | No, same process |
| Communication | IPC messages | parentPort messages |
| Use case | Running separate scripts, external apps | CPU-heavy JS tasks |
| Overhead | Higher (separate process) | Lower (threads) |
| Memory | Separate memory | Shared memory with transferable objects |
- advantage of express over node
| Reason | Explanation |
|---|---|
| Simplified Routing | Define routes easily with app.get/post/put/delete |
| Middleware Support | Add logging, auth, parsing, error handling easily |
| Cleaner Code | Less boilerplate than plain Node HTTP module |
| Scalability | Organize routes with Router objects for large apps |
| Extensible | Integrates with many npm packages |
| Faster Development | Less code, more productivity for APIs and web apps |
-
advantages of react | Advantage | Explanation | | -------------------------------- | ----------------------------------------------------------------- | | Reusable Components | Components can be reused across the app, saving development time. | | Virtual DOM | Improves performance by updating only changed parts of the UI. | | Fast Rendering | Efficient updates using diffing algorithm; good for large apps. | | Unidirectional Data Flow | Predictable data flow makes debugging easier. | | Strong Community & Ecosystem | Many libraries, tutorials, and tools available. | | SEO Friendly | React can render on the server (Server-Side Rendering). | | JSX Syntax | Combines HTML and JS, making code more readable. | | Easy Integration | Can integrate with other frameworks or libraries. |
-
Building blocks of react
| Building Block | Purpose |
|---|---|
| Components | Reusable UI building blocks |
| JSX | HTML-like syntax inside JS |
| Props | Read-only input for components |
| State | Component’s dynamic data |
| Event Handling | Respond to user actions |
| Lifecycle / Hooks | Manage side effects and updates |
| Virtual DOM | Efficient rendering |
| Conditional Rendering | Render based on conditions |
| Lists & Keys | Render dynamic lists efficiently |
- React Router React Router: A library to handle routing in React SPAs.Need for React Router: Enables multiple views, dynamic URLs, and navigation without full page reloads.
| Advantage | Explanation |
|---|---|
| SPA Routing | Navigate between views without refreshing the page |
| Dynamic Routes | Pass parameters in URL like /users/:id |
| Nested Routes | Render child components inside parent routes |
| Browser History | Supports forward/back navigation |
| Conditional & Protected Routes | Render routes based on user roles or login status |
- API Routes: Server endpoints that handle requests and send responses to the frontend.
Purpose: Fetch or manipulate data, separate frontend and backend logic, enable SPAs, and handle authentication/authorization.
- advantages of next.js
| Feature | Benefit |
|---|---|
| SSR & SSG | Fast, SEO-friendly pages |
| API Routes | Build backend endpoints without separate server |
| File-based Routing | Easy to manage routes |
| Automatic Code Splitting | Faster page load |
| Image & Performance Optimization | Built-in <Image> component and optimizations |
| Feature | SSR | SSG | ISR |
|---|---|---|---|
| When HTML is generated | On every request | At build time | At build + revalidated periodically |
| Speed | Slower (server work per request) | Fast (static) | Fast (static with updates) |
| Freshness | Always fresh | Stale until rebuild | Semi-fresh (depends on revalidate) |
| Use Case | Dynamic dashboards | Blogs, docs | News sites, blogs with occasional updates |
- csr vs ssr
| Feature | CSR | SSR |
|---|---|---|
| Where HTML is generated | Browser (client) | Server |
| Initial page load | Slower (JS must execute) | Faster (pre-rendered HTML) |
| SEO | Poor (unless pre-rendered) | Excellent |
| Interactivity | Full SPA experience | Needs hydration for interactivity |
| Server load | Lower | Higher (server renders per request) |
| Use Case | SPAs, dashboards | Blogs, e-commerce, SEO-critical pages |
- template vs layout
| Feature | Layout | Template |
|---|---|---|
| Mount behavior | Persistent (doesn’t unmount across page navigation) | Re-renders on every navigation |
| State preservation | ✅ Keeps state | ❌ Resets state |
| Use case | Navbars, sidebars, consistent UI | Pages requiring fresh render (forms, wizards) |
| Example file | layout.js | template.js |
| Feature | getStaticProps (SSG) | getServerSideProps (SSR) |
|---|---|---|
| When HTML is generated | Build time | On every request |
| Performance | Fast (served as static HTML) | Slower (server rendering per request) |
| Freshness | Static, can use ISR | Always fresh |
| Use Case | Blogs, docs, landing pages | Dashboards, dynamic user pages |
| Revalidation | Optional (revalidate) | Not needed, always fresh |
| Option | Scope | Pros | Cons |
|---|---|---|---|
| Global CSS | Whole app | Simple | Can conflict |
| CSS Modules | Component | Scoped, safe | Requires import |
| Styled JSX | Component | Scoped, dynamic | Inline syntax |
| CSS-in-JS | Component | Theming, dynamic | Adds JS bundle |
| Tailwind CSS | Utility classes | Fast, responsive | Class-heavy JSX |
| Sass/SCSS | Global / Module | Variables, nesting | Needs compilation |
| UI Framework | Component | Pre-built, consistent | Learning curve, bundle size |
| Optimization | How it helps |
|---|---|
SSG (getStaticProps) | Fastest page load |
| ISR | Static pages + updated content |
| Image Optimization | Smaller images → faster load |
| Dynamic Imports | Smaller JS bundle |
| Prefetch Links | Instant navigation |
| CDN & Caching | Global fast delivery |
| Fonts Optimization | Prevent layout shifts |
| Reduce JS payload | Smaller bundles, faster |
| React memo/hooks | Prevent unnecessary re-renders |