WebNest
Team/Shahnawaz Sazid/JS-PROBLEM-SOLVING

Repository

JS-PROBLEM-SOLVING

View on GitHub ↗
JavaScript0 stars0 forks

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

FeatureMutableImmutable
Can change original?✅ Yes❌ No
Memory usageLessMore (new copy)
PredictabilityLowerHigher
Used in React❌ Avoid✅ Preferred
  • normal function vs arrow function
FeatureRegular FunctionArrow Function
SyntaxLongerShorter
thisDynamicLexical
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

  1. 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
    1. Implicit Return
    2. shorter syntax
    3. 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
}

Featurefor…infor…of
Iterates overKeys / property namesValues
Works onObjects, Arrays (keys)Iterables: Array, String, Map, Set
OutputIndex/keyActual value
Syntax advantageGood for object propsGood for array/string values
ES VersionES5ES6

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]

FeatureforEachmap
Return ValueundefinedNew array
PurposeSide effectsTransforming data
ChainableNoYes
Mutates Original?Depends (can mutate)No (creates new array)
Example Use CaseLogging, updating DOMCreating 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
FeatureOptional Chaining (?.)Ternary Operator (? :)
PurposePrevent errorsConditional logic
Works onObjects/propertiesAny condition
Returnsundefined if missingOne of two values
ReplacesNull checksif/else
FeatureGlobal Scope 🌍Block Scope 📦
AccessibleEverywhereOnly inside {}
Keywordsvar, let, constlet, const
RiskHigh (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

FeaturePass by Value 🔢Pass by Reference 📦
Data typePrimitivesObjects, Arrays
Copy or linkCopyMemory reference
Affects original?❌ No✅ Yes
Examplenumber, stringobject, 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
OperationConversion TypeExample
+ with stringNumber → String5 + "5" → "55"
-, *, /String → Number"10" * 2 → 20
if or Boolean contextAny type → Boolean"" → false
Comparison (==)JS tries to convert to same type"5" == 5 → true
Variable TypePassed AsEffect 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
FeatureHoisted?Initialized?Can use before declaration?
varYesundefined✅ undefined
letYes❌ No (TDZ)❌ ReferenceError
constYes❌ No (TDZ)❌ ReferenceError
Function declarationYesYes✅ Yes
Function expression (var)Yes (variable)undefined❌ TypeError
Function expression (let/const)Yes (variable)TDZ❌ ReferenceError
Lifecycle PhaseClass Component MethoduseEffect Equivalent
MountingcomponentDidMountuseEffect(() => {}, [])
UpdatingcomponentDidUpdateuseEffect(() => {}, [deps])
UnmountingcomponentWillUnmountreturn () => { ... }
    1. 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));

ConceptMeaning
CallbackFunction passed into another function
Higher-Order FunctionFunction that takes or returns functions
  • call bind and this
MethodCalls function immediately?Arguments format
call()✅ YesComma separated
apply()✅ YesArray
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 CaseMethod
Immediate executioncall/apply
Arguments already in arrayapply
Reusable functionbind
React event handlersbind
FeatureCallback HellPromise Hell
Based onCallbacksPromises
ShapePyramid nestingLong chains
Error handlingVery hardSlightly better
ReadabilityWorstBetter 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

FeatureShallow CopyDeep Copy
Nested objectsSharedFully copied
MemoryLessMore
SpeedFasterSlower
Safe for nested data❌ No✅ Yes
Featurerelativeabsolutefixedsticky
In normal flow✅ Yes❌ No❌ No✅ Initially
Reference pointItselfNearest positioned parentViewportScroll position
Moves on scrollYesYes❌ NoSticks after scroll
Space reserved✅ Yes❌ No❌ No✅ Yes
FeatureClass ComponentFunctional Component with Hooks
SyntaxES6 classJavaScript function
Statethis.state + this.setStateuseState hook
LifecyclecomponentDidMount, componentDidUpdateuseEffect hook
thisRequired (binding)Not needed
ReadabilityVerboseCleaner, concise
PerformanceSlightly slower (older React versions)Slightly faster (modern React)
ReusabilityHarder to share logicHooks allow custom reusable logic
TypeMeaningExample
Pseudo-classElement state:hover, :first-child
Pseudo-elementPart of element or insert content::before, ::first-letter
MethodHorizontalVerticalNotes
Flexboxjustify-content: centeralign-items: centerGood for 1D layout (row or column)
Gridjustify-items: centeralign-items: centerWorks for 2D layout; shorthand → place-items: center
Dependency ArrayWhen effect runs
[]Only once, after first render (componentDidMount)
[dep1, dep2]Runs after first render and whenever dep1 or dep2 changes
omittedRuns after every render (componentDidMount + componentDidUpdate)
FeatureuseStateuseReducer
ComplexitySimple stateComplex state logic
UpdateDirect setter functionReducer function + action
Multiple state valuesMultiple useState callsOne state object handled by reducer
ReadabilitySimple for few valuesBetter for many interdependent states
DebuggingEasy for small appsEasier with predictable reducer pattern
TechniqueUse Case
React.memoMemoize component to prevent re-render if props unchanged
useCallbackMemoize functions passed as props to children
Both togetherOptimize parent → child re-render chains
FeatureLocal StorageSession StorageCookies
Storage size~5–10 MB~5 MB~4 KB
ExpirationNo expiration; persists until manually clearedExpires when browser/tab closesSet via Expires or Max-Age; can persist across sessions
ScopeShared across all tabs/windows of same originOnly accessible in the tab/window that created itSent to server with every request (optional)
AccessJavaScript onlyJavaScript onlyJavaScript (document.cookie) + server
Use caseStore 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
FeatureChild ProcessWorker Thread
Separate process?YesNo, same process
CommunicationIPC messagesparentPort messages
Use caseRunning separate scripts, external appsCPU-heavy JS tasks
OverheadHigher (separate process)Lower (threads)
MemorySeparate memoryShared memory with transferable objects
  • advantage of express over node
ReasonExplanation
Simplified RoutingDefine routes easily with app.get/post/put/delete
Middleware SupportAdd logging, auth, parsing, error handling easily
Cleaner CodeLess boilerplate than plain Node HTTP module
ScalabilityOrganize routes with Router objects for large apps
ExtensibleIntegrates with many npm packages
Faster DevelopmentLess 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 BlockPurpose
ComponentsReusable UI building blocks
JSXHTML-like syntax inside JS
PropsRead-only input for components
StateComponent’s dynamic data
Event HandlingRespond to user actions
Lifecycle / HooksManage side effects and updates
Virtual DOMEfficient rendering
Conditional RenderingRender based on conditions
Lists & KeysRender 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.
AdvantageExplanation
SPA RoutingNavigate between views without refreshing the page
Dynamic RoutesPass parameters in URL like /users/:id
Nested RoutesRender child components inside parent routes
Browser HistorySupports forward/back navigation
Conditional & Protected RoutesRender 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
FeatureBenefit
SSR & SSGFast, SEO-friendly pages
API RoutesBuild backend endpoints without separate server
File-based RoutingEasy to manage routes
Automatic Code SplittingFaster page load
Image & Performance OptimizationBuilt-in <Image> component and optimizations
FeatureSSRSSGISR
When HTML is generatedOn every requestAt build timeAt build + revalidated periodically
SpeedSlower (server work per request)Fast (static)Fast (static with updates)
FreshnessAlways freshStale until rebuildSemi-fresh (depends on revalidate)
Use CaseDynamic dashboardsBlogs, docsNews sites, blogs with occasional updates
  • csr vs ssr
FeatureCSRSSR
Where HTML is generatedBrowser (client)Server
Initial page loadSlower (JS must execute)Faster (pre-rendered HTML)
SEOPoor (unless pre-rendered)Excellent
InteractivityFull SPA experienceNeeds hydration for interactivity
Server loadLowerHigher (server renders per request)
Use CaseSPAs, dashboardsBlogs, e-commerce, SEO-critical pages
  • template vs layout
FeatureLayoutTemplate
Mount behaviorPersistent (doesn’t unmount across page navigation)Re-renders on every navigation
State preservation✅ Keeps state❌ Resets state
Use caseNavbars, sidebars, consistent UIPages requiring fresh render (forms, wizards)
Example filelayout.jstemplate.js
FeaturegetStaticProps (SSG)getServerSideProps (SSR)
When HTML is generatedBuild timeOn every request
PerformanceFast (served as static HTML)Slower (server rendering per request)
FreshnessStatic, can use ISRAlways fresh
Use CaseBlogs, docs, landing pagesDashboards, dynamic user pages
RevalidationOptional (revalidate)Not needed, always fresh
OptionScopeProsCons
Global CSSWhole appSimpleCan conflict
CSS ModulesComponentScoped, safeRequires import
Styled JSXComponentScoped, dynamicInline syntax
CSS-in-JSComponentTheming, dynamicAdds JS bundle
Tailwind CSSUtility classesFast, responsiveClass-heavy JSX
Sass/SCSSGlobal / ModuleVariables, nestingNeeds compilation
UI FrameworkComponentPre-built, consistentLearning curve, bundle size
OptimizationHow it helps
SSG (getStaticProps)Fastest page load
ISRStatic pages + updated content
Image OptimizationSmaller images → faster load
Dynamic ImportsSmaller JS bundle
Prefetch LinksInstant navigation
CDN & CachingGlobal fast delivery
Fonts OptimizationPrevent layout shifts
Reduce JS payloadSmaller bundles, faster
React memo/hooksPrevent unnecessary re-renders
← Back to profile