Wednesday, July 29, 2026

JavaScript Interview Preparation: Complete Guide for Beginners to Advanced

 

JavaScript Interview Preparation: Complete Guide for Beginners to Advanced





JavaScript Core Interview Overview

1. Execution Context

Definition:

Execution Context wo environment hota hai jahan JavaScript code execute karti hai.

Types

  • Global Execution Context (GEC)
  • Function Execution Context (FEC)

Working

  • Sab se pehle JavaScript Global Execution Context create karti hai.
  • Memory Creation Phase me variables aur functions memory me store hote hain.
  • Execution Phase me code line by line execute hota hai.
  • Jab bhi koi function call hota hai, us function ke liye naya Function Execution Context create hota hai.

Interview Answer:

Execution Context wo environment hota hai jahan JavaScript code execute karti hai. Sab se pehle Global Execution Context create hota hai. Memory phase me variables aur functions memory me store hote hain aur execution phase me code execute hota hai. Har function call ke liye naya Function Execution Context create hota hai.


2. Arrow Function

Definition

Arrow Function ES6 ka feature hai jiska syntax chhota aur clean hota hai.

Key Points

  • Short syntax
  • Apna this nahi hota.
  • Parent/Lexical this use karta hai.
  • Constructors ke tor par use nahi ho sakta.

Normal Function vs Arrow Function

Normal Function

  • Apna this hota hai.
  • Zarurat par bind(), call(), ya apply() use karna pad sakta hai.

Arrow Function

  • Apna this nahi hota.
  • Parent ka this use karta hai.

Interview Answer:

Arrow Function ka syntax short hota hai aur iska apna this nahi hota. Ye lexical this use karta hai, yani parent scope ka this. Normal function ka apna this hota hai.


3. Lexical Scope

Definition

Lexical Scope ka matlab hai kisi variable ya this ki visibility aur accessibility uski position ke according determine hona.

Interview Answer:

Lexical Scope ka matlab hai ke variable ya this kis scope me accessible hoga. JavaScript me scope code likhne ki position ke hisab se decide hota hai.


4. Promise

Definition

Promise JavaScript ka object hai jo asynchronous operations ko handle karne ke liye use hota hai.

States

  • Pending
  • Fulfilled (Resolved)
  • Rejected

Methods

  • .then() → Success
  • .catch() → Error
  • .finally() → Hamesha execute hota hai.

Interview Answer:

Promise asynchronous operations ko handle karta hai. Iski teen states hoti hain: Pending, Fulfilled aur Rejected. Success ko .then() aur error ko .catch() se handle karte hain.


5. Destructuring

Array Destructuring

  • Index ki base par values nikalte hain.
  • Kisi index ko skip karne ke liye comma , use karte hain.
  • Rest Operator (...) use kar sakte hain.

Object Destructuring

  • Position ki base par nahi.
  • Key (Property Name) ki base par value milti hai.

Interview Answer:

Destructuring ki madad se arrays aur objects ki values ko cleaner aur readable way me extract karte hain. Array destructuring index based hoti hai jab ke object destructuring key based hoti hai.


6. Call Stack

Definition

Call Stack JavaScript ka mechanism hai jo function calls ko manage aur track karta hai. It follows FIFO order.

Async Operations

  • Async operations Web APIs me jati hain.
  • Complete hone ke baad Callback Queue me aati hain.
  • Event Loop Call Stack empty hone par unhe Call Stack me bhejta hai.

Interview Answer:

Call Stack JavaScript ka execution mechanism hai jo function calls ko LIFO order me execute karta hai. Async operations Web APIs me jati hain aur Event Loop ke through Callback Queue se Call Stack me aati hain.


7. Prototype

Definition

Prototype JavaScript ka mechanism hai jis se objects common properties aur methods share karte hain.

Benefits

  • Memory optimize hoti hai.
  • Code reuse hota hai.
  • Inheritance achieve hoti hai.

Prototype Chain

Agar property object me na mile to JavaScript Prototype Chain me search karti hai.

Interview Answer:

Prototype JavaScript ka mechanism hai jis se objects common methods aur properties share karte hain. Agar koi property object me na mile to JavaScript Prototype Chain me search karti hai.


8. Higher-Order Function

Definition

Higher-Order Function wo function hota hai jo:

  • Kisi function ko argument ke tor par receive kare.
  • Ya function return kare.

Examples

  • map()
  • filter()
  • reduce()
  • forEach()
  • find()

Interview Answer:

Higher-Order Function wo function hota hai jo kisi function ko argument ke tor par receive karta hai ya function return karta hai.


9. Pure Function

Definition

Pure Function wo function hota hai jo:

  • Same input par hamesha same output de.
  • External state ya variable modify na kare.

Benefits

  • Predictable
  • Easy to Test
  • Easy to Maintain

Interview Answer:

Pure Function same input par hamesha same output return karta hai aur kisi external state ko modify nahi karta.


10. Immutability

Definition

Immutability ka matlab existing object ya array ko modify na karna, balki uski new copy bana kar changes karna.

React Me Importance

  • React changes easily detect karta hai.
  • Re-rendering improve hoti hai.
  • Bugs kam hote hain.

Interview Answer:

Immutability ka matlab existing data ko modify na karna balki uski new copy bana kar update karna hai. React state update karte waqt hum immutability follow karte hain.


11. Debouncing

Definition

Debouncing ek optimization technique hai jisme function tab execute hota hai jab user kuch time tak action karna band kar de.

Common Use Cases

  • Search Box
  • API Calls
  • Auto Suggest
  • Input Validation

Benefit

  • Unnecessary API calls reduce hoti hain.
  • Performance improve hoti hai.

Interview Answer:

Debouncing me function user ke stop karne ke baad execute hota hai. Iska use unnecessary function calls aur API requests ko reduce karne ke liye hota hai.


12. Throttling

Definition

Throttling ek optimization technique hai jisme function fixed interval ke baad hi execute hota hai chahe event kitni bhi baar trigger ho.

Common Use Cases

  • Scroll Event
  • Resize Event
  • Mouse Move
  • Infinite Scroll

Benefit

  • Performance improve hoti hai.
  • CPU aur browser load kam hota hai.

Interview Answer:

Throttling me function fixed interval par execute hota hai chahe user continuously action karta rahe.


Debouncing vs Throttling

DebouncingThrottling
User stop kare, phir function chale.Function fixed interval par chalta rahe.
Search BoxScroll & Resize

13. Memoization

Definition

Memoization ek optimization technique hai jisme expensive function ka result cache kar liya jata hai.

Agar same input dobara aaye to cached result return hota hai.

Benefits

  • Performance improve hoti hai.
  • Repeated calculations avoid hoti hain.

React

  • React.memo
  • useMemo

Interview Answer:

Memoization function ke result ko cache karta hai taake same input dobara aaye to calculation dobara na karni pade.


14. Deep Copy vs Shallow Copy

Shallow Copy

  • Sirf first level copy hoti hai.
  • Nested objects reference share karte hain.
  • Nested object change ho to original bhi change ho sakta hai.

Deep Copy

  • Complete independent copy hoti hai.
  • Nested objects bhi copy hote hain.
  • Original object affect nahi hota.

Interview Answer:

Shallow Copy sirf first level properties copy karti hai aur nested objects reference share karte hain. Deep Copy complete independent copy banati hai isliye nested object change karne se original object affect nahi hota.


React

UseReducer 

useReducer React ka hook hai jo complex state management ke liye use hota hai. Jab state updates multiple conditions ya complex logic par depend karti hon, to useReducer useState se better option hota hai. Iske 3 main parts hote hain: Reducer, jisme business logic hoti hai; Action, jo batata hai kya operation perform karna hai; aur Dispatch, jo action ko reducer tak bhejta hai. Reducer phir updated state return karta hai.


Interview Answer – useMemo

useMemo React ka hook hai jo expensive calculations ki value ko memoize karta hai. Is se unnecessary recalculations avoid hoti hain aur performance improve hoti hai. Jab dependencies change hoti hain tabhi calculation dobara hoti hai.

Kab use karte hain?

Jab koi expensive calculation ho aur hum usay har re-render par dobara execute nahi karwana chahte.


Interview Answer – useCallback

useCallback React ka hook hai jo function ke reference ko memoize karta hai. Parent component ke re-render hone par ye function dobara create nahi karta jab tak dependencies change na hon. Is se unnecessary re-renders avoid hote hain aur performance improve hoti hai.

Kab use karte hain?

useCallback tab use karte hain jab hame function ka reference same rakhna ho, khas tor par jab function ko child component ko prop ke through pass kar rahe hon, taake unnecessary re-renders avoid ho saken.


Component Communication

1. Parent → Child

Parent component child ko props ke through data pass karta hai.

Interview Answer:

Parent component child component ko data props ke through pass karta hai. React mein data by default top-to-bottom flow karta hai.


2. Child → Parent

Child parent ko data directly nahi bhej sakta. Parent ek callback function props ke through pass karta hai aur child us function ko call karta hai.

Interview Answer:

Child component callback function ko invoke karke parent ko data bhejta hai. Ye callback parent props ke through pass karta hai.


3. Sibling Communication

Sibling components directly communicate nahi kar sakte.

Interview Answer:

Sibling components parent ke through communicate karte hain. Shared state parent mein rakhi jati hai aur props ke through dono siblings ko pass ki jati hai.


4. Context API

Context API multiple components ke darmiyan data share karne ke liye use hoti hai without passing props at every level.

Interview Answer:

Context API shared data ko multiple components tak directly pohanchane ke liye use hoti hai aur prop drilling ko reduce karti hai.


5. Prop Drilling

Ek hi data ko multiple intermediate components se pass karna.

Interview Answer:

Prop Drilling us situation ko kehte hain jab ek prop ko unnecessary multiple components ke through pass karna pade sirf kisi nested component tak pohanchane ke liye.


6. Composition

Ek component ke andar doosre components ko use karke reusable UI banana.

Interview Answer:

Composition React ka pattern hai jisme hum existing components ko combine karke naye reusable components banate hain.


7. Lifting State Up

Shared state ko common parent mein move karna.

Interview Answer:

Jab multiple child components ko same state ki zarurat ho to us state ko unke common parent mein move karna Lifting State Up kehlata hai.


8. Controlled Components

Form input jiski value React state control karti hai.

Interview Answer:

Controlled Component wo hota hai jisme form input ki value React state ke through manage hoti hai.


9. Compound Components

Multiple related components jo mil kar ek component ki tarah kaam karein.

Interview Answer:

Compound Components ek design pattern hai jisme multiple related components mil kar ek flexible aur reusable component create karte hain, aur apni state share karte hain.



Redux Toolkit

Redux Toolkit Redux ka official state management library hai jo Redux ko simple aur less boilerplate banati hai. Ye global state ko manage karne ke liye use hoti hai. Iske main parts Store, Slice, Action aur Reducer hain. Components useSelector se state read karte hain aur useDispatch se actions dispatch karke state update karte hain.


One-line Memory Trick

  • useSelector → Store se data get karta hai.
  • useDispatch → Store ko action send karta hai.
  • Slice → State + Reducers.
  • Store → Global State.

Architecuture

Component > Dispatch > Reducer (Slice) > Store > useSelector > UI Update

Redux Toolkit mein jab user koi action perform karta hai to component dispatch ke through action bhejta hai. Reducer ya Slice us action ke basis par state update karta hai. Updated state Redux Store mein save hoti hai, aur useSelector ke through components latest state read karte hain. State update hote hi React automatically affected components ko re-render kar deta hai.


Interview Answer (Redux Thunk + Redux Saga + createAsyncThunk)

Redux Thunk aur Redux Saga dono Redux middlewares hain jo asynchronous operations, jaise API calls aur side effects, handle karne ke liye use hote hain. Redux Thunk simple async operations ke liye suitable hai, jabke Redux Saga complex workflows, multiple API calls aur background tasks ke liye use hota hai. Agar hum Redux Toolkit use kar rahe hon, to asynchronous operations ke liye createAsyncThunk use karte hain. Ye Redux Toolkit ka built-in feature hai jo internally Redux Thunk middleware use karta hai, is liye hame manually Redux Thunk configure karne ki zarurat nahi hoti.

One-line Memory Trick

  • Redux Thunk → Simple async operations
  • Redux Saga → Complex async workflows

Rendering Cycle

Component Render > Virtual DOM > Diffing > Reconciliation > Real DOM Update 

Rendering Cycle React ka process hai jisme component render ya re-render hota hai. Jab state ya props change hote hain, React naya Virtual DOM create karta hai, usay purane Virtual DOM se compare karta hai (Diffing), phir Reconciliation ke through sirf changed part ko Real DOM mein update karta hai. Is se performance improve hoti hai


Fiber

Fiber React ka rendering engine hai jo rendering ko small tasks mein divide karta hai. Is se React rendering ko pause, resume ya prioritize kar sakta hai, jis se performance aur user experience improve hota hai.

Example: Agar kisi e-commerce website par 5000 products render karne hon, to Fiber un sab ko ek hi baar render nahi karta. Pehle kuch products render karta hai, phir browser ko response dene ka moka deta hai, aur uske baad baqi products render karta hai. Is se UI freeze nahi hoti aur application smooth rehti hai.


React. memo

React.memo ek Higher Order Component hai jo unnecessary component re-renders ko prevent karta hai. Agar component ki props change na hon to React us component ko dobara render nahi karta, jis se performance improve hoti hai.


Batching 

Batch Updates React ki optimization technique hai jisme multiple state updates ko combine karke sirf ek re-render kiya jata hai. Is se unnecessary renders avoid hote hain aur performance improve hoti hai. ye react 18 main introduce hova hy es say pehly manull batching ki jati thi as per need.


Code Splitting (Lazy and suspense)

Maan lijiye meri application mein Dashboard, Reports aur Admin modules hain. Agar initial load par in sab ka code aur data ek sath load kar doon, to application ka first load slow ho jayega aur user ko unnecessary JavaScript aur data download karna padega. Is problem ko solve karne ke liye hum Lazy Loading use karte hain. React mein components ke liye React.lazy() use karte hain, images ke liye loading="lazy" aur APIs ke liye on-demand fetching karte hain. Is tarah sirf wahi component, image ya data load hota hai jiski us waqt zarurat hoti hai, jis se initial load fast hota hai aur performance improve hoti hai. susspese ko os time use krty ja while downliading koi dumny UI ya koi loader ya spinner show krna ho

Bundle Optimization (global term es k under sab aata ahy )

     Code Splitting |  Lazy Loading | Tree Shaking | Image Optimization | Compression


Virtualization ya Windowing 

Virtualization ya Windowing ek performance optimization technique hai jisme large lists ke sirf visible items render kiye jate hain. Jaise agar 10,000 records hon to React sirf screen par nazar aane wale items render karta hai aur scroll ke sath naye items render karta rehta hai. Is se rendering fast hoti hai, memory kam use hoti hai aur scrolling smooth rehti hai.

Agar screen par 30 products visible hain, to Virtualization ki wajah se React sirf un 30 products ko render karega. Phir Fiber un 30 products ki rendering ko efficiently schedule karega aur zarurat par rendering ko pause, resume ya prioritize kar sakta hai taake UI responsive rahe. Jab user scroll karega, Virtualization agle 30 products render karegi aur Fiber unki rendering ko efficiently handle karega.


Tree Shaking

Tree Shaking ek production optimization technique hai jo unused JavaScript code ko final bundle se remove kar deti hai. Is se bundle size reduce hota hai aur application faster load hoti hai. Ye modern bundlers jaise Webpack, Vite aur Rollup ES Modules ke sath support karte hain.

How do you identify performance issues in React?

Main React Developer Tools ke Profiler tab ko use karta hoon. Ye batata hai ke kaun se components unnecessary re-render ho rahe hain aur unhe optimize karne ke liye React.memo, useMemo ya useCallback apply karta hoon."


Nested Routes 

Nested Routes ka use tab karte hain jab multiple pages ka common layout ho, jaise Dashboard, Sidebar ya Header. Parent route common layout provide karta hai aur child routes <Outlet /> ke through us layout ke andar render hote hain. Is se code reusable aur maintainable ho jata hai.


Polling and websocket

Polling ek technique hai jisme frontend fixed interval par repeatedly API call karta hai taake latest data receive ho sake. Iska use order tracking, live notifications ya dashboard updates jaisi situations mein hota hai. React mein isay aam tor par setInterval aur useEffect ke sath implement kiya jata hai.

Question: Is polling the best technique 


Nahi. Agar real-time updates ki zarurat ho, to WebSockets ya Server-Sent Events zyada efficient hote hain. Polling mein har interval par unnecessary API requests bhi ja sakti hain, chahe data change na hua ho.

  • Polling → Client baar baar poochta hai: "Kuch naya hai?"
  • WebSocket → Server khud batata hai: "Naya data aa gaya."

Polling mein hum setInterval ke through regular interval par API call karte hain aur latest data fetch karte hain. WebSocket mein ek persistent connection establish hota hai aur server data available hote hi automatically client ko push kar deta hai, is liye repeated API calls ki zarurat nahi padti.


Headless component:

Headless Components wo components hote hain jo sirf functionality aur state management provide karte hain, lekin UI define nahi karte. Is se same logic ko different designs ke sath reuse kiya ja sakta hai, jis se flexibility aur reusability improve hoti hai.

Suppose meri application ko same dropdown functionality teen different pages par chahiye, lekin har page ka design alag hai. Main logic ko Headless Component mein rakhunga aur har page apni UI bana lega. Is se logic duplicate nahi hogi aur maintenance easy ho jayegi.

Profiler and Testing library

React Profiler aur React Testing Library ka purpose different hai. React Profiler performance analyze karta hai aur batata hai ke kaun se components unnecessary re-render ho rahe hain. React Testing Library components ki functionality test karti hai, jaise rendering, button clicks aur form submission, taake ensure ho ke application user ke perspective se sahi kaam kar rahi hai.


Yup

Yup ek schema validation library hai jo forms ke input ko validate karne ke liye use hoti hai. Iska use React Hook Form ya Formik ke sath commonly kiya jata hai taake email, password aur required fields ki validation easily manage ho sake.


Zod

Zod bhi ek schema validation library hai, lekin ye TypeScript-first approach follow karti hai. Ye validation ke sath automatic TypeScript types bhi generate karti hai, is liye modern React aur Next.js projects mein kaafi popular hai.

Yup aur Zod use karne se manual validation logic likhne ki zarurat bohot kam ho jati hai. Hum validation rules ek schema mein define karte hain aur React Hook Form ya Formik us schema ke basis par form validate kar leta hai. Is se code cleaner, reusable aur maintainable ho jata hai. 


Micro Frontend architecture | Federation

Micro Frontend architecture mein large frontend application ko multiple independently developed aur deployed applications mein divide kiya jata hai. Webpack 5 ka Module Federation feature runtime par remote applications ke components ko share aur consume karne ki facility deta hai. Ek Host application shell ki tarah kaam karti hai aur Products, Cart ya Profile jese remote micro frontends ko dynamically load karti hai. Is approach se different teams independently deploy kar sakti hain, release cycles fast ho jate hain aur code ownership clear rehti hai. Lekin dependency versioning, routing aur shared state management ko carefully handle karna padta hai. 🎯 


Communication between MicroFrontend 

Micro Frontend architecture mein main communication ko minimum rakhta hoon. Agar remote ek React component hai to props aur callback use karta hoon. Agar remote independent application hai to custom events ya shared contracts use karta hoon. Global state sirf cross-cutting concerns jese authentication, theme aur user preferences ke liye share karta hoon, kyun ke zyada shared state micro frontends ko tightly coupled bana deti hai.



TypeScript

TypeScript JavaScript ka statically typed superset hai jo Microsoft ne develop kiya hai. Iska main purpose compile time pe errors ko detect karna, code ko maintainable banana aur large scale applications ko easy banana hai. TypeScript browser mein directly run nahi hoti, pehle JavaScript mein compile hoti hai aur phir browser JavaScript ko execute karta hai.


Kya TypeScript Performance Improve karti hai?
TypeScript ja performance improve nahi hoti, bas compile time help krti hai fastly error ko find krny main taaky product pay kam say kaam issue aain.
browser nay kabhi types jo type script main aati han dekhi hi nahi, kiyon k ye broswer pay jany say pehly hi js main convert ho jati han.

TypeScript compiler pehle code ki static type checking karta hai aur compile-time errors detect karta hai. Agar code valid ho to woh TypeScript ke type annotations remove karke plain JavaScript generate karta hai, jo browser execute karta hai.

Diff between interface and type?
React components ke Props aur API response models ke liye main generally interface use karta hoon. future mein extends karna easy hota hai aur declaration merging bhi support karti hai. Agar mujhe union types, intersection ya primitive alias banana ho to main type use karta hoon.  
Type khud bhi union ho sakta hai aur uske andar bhi union properties ho sakti hain. Interface khud union nahi ho sakta, but uske andar union properties ho sakti hain.

Generics
Generics hame reusable aur type-safe code likhne ki facility dete hain. Jab function ya component banate waqt hame actual type ka pata nahi hota, to hum Generic type parameter (<T>) use karte hain. Jab us function ko call karte hain, TypeScript us Generic ko actual type se replace kar deta hai, jis se type safety bhi maintain rehti hai aur code bhi reusable hota hai.





Any Vs Unknown

any

any ka matlab hai TypeScript ki type checking off ho jati hai. Is mein aap kisi bhi type ki value assign kar sakte ho, aur us variable par bina kisi restriction ke koi bhi operation perform kar sakte ho. Compiler koi error nahi dega, lekin agar actual value us operation ko support na karti ho to runtime par application crash ho sakti hai ya unexpected result aa sakta hai.

unknown

unknown mein bhi aap kisi bhi type ki value assign kar sakte ho. Lekin farq ye hai ke aap us variable par directly koi operation perform nahi kar sakte. Pehle aapko TypeScript ko prove karna hota hai ke actual type kya hai. Jab type confirm ho jaye, tab hi operation allow hota hai. Is wajah se unknown, any se zyada type-safe hota hai.


NEXTJS


CSR | SSR | SSG | ISR
  • SSR (Server-Side Rendering): Generate HTML on every request. Best for dynamic SEO pages where data must always be fresh (e.g., weather, stock, real-time product details).
  • SSG (Static Site Generation): Generate HTML at build time. Best for static SEO pages whose content rarely changes (e.g., About, Contact, Documentation).
  • ISR (Incremental Static Regeneration): Generate HTML at build time, then regenerate in the background after the revalidate interval when the next request arrives. Best for pages that change occasionally (e.g., product listings, homepage, blogs).
  • CSR (Client-Side Rendering): HTML is rendered in the browser using JavaScript. Best for authenticated or highly interactive pages (Dashboard, Admin, Profile). Not the preferred choice for SEO-critical pages.
Golden Rule (Remember This)
Static Data → SSG
Occasionally Changing Data → ISR
Always Fresh Data → SSR
User-Specific / No SEO → CSR

SEO Rule
SEO depends on the initial HTML.
SSR, SSG, and ISR all provide fully rendered HTML on the first response, so they are SEO-friendly.
CSR renders content after JavaScript loads, so it's generally less suitable for SEO-critical pages
Product Detail SEO
For pages like /products/[id], use generateMetadata() to generate a dynamic title and description for each product. Choose ISR for most e-commerce sites, or SSR if the product data must always be up to date.



App Router vs Pages Router
Page Router Next.js ka old routing system hai. Main App Router prefer karta hoon kyun ke ye latest routing system hai. Isme Server Components by default hote hain, layouts better handle hote hain, loading aur error handling built-in hoti hai aur performance bhi better hoti hai.

Server Component vs Client Component
Server Components server par render hote hain aur by default App Router mein use hote hain. Ye better performance aur SEO provide karte hain, lekin useState, useEffect aur browser APIs support nahi karte. Client Components browser mein run hote hain, "use client" directive se enable kiye jate hain aur React Hooks, event handlers aur user interaction support karte hain. "use client" ek directive hai jo Next.js ko batata hai ke is file ko Client Component ki tarah browser mein render aur hydrate karna hai.  SSC k k child CSC ho skty han CSC componet k child SSC nahi ho skty 

Data Fetching

Next.js mein data fetching do tarah se hoti hai: Server Component aur Client Component. Agar data page load hote hi chahiye ho aur SEO important ho, to main Server Component mein data fetch karta hoon kyun ke data server par fetch hota hai aur browser ko ready HTML milti hai. Agar data user interaction ke baad load hona ho, jaise search, filters ya button click, to Client Component mein useEffect, React Query ya SWR use karta hoon. Performance improve karne ke liye Next.js caching provide karta hai aur agar data ko specific interval ke baad automatically refresh karna ho to revalidation use karte hain.

Main Features of App Router

  • layout.tsx: provide shared UI jo route change hony pay preserve rehti hai,
  • template.tsx: same as layout lekin route change hone par har baar dobara render hota hai.
  • loading.tsx : Data load hone tak loading UI show karta hai.
  • error.tsx : Agar component render ya data fetching ke dauran error aaye to custom error page show karta hai.
  • not-found.tsx : 404 page ko customize karne ke liye use hota hai.


 Navigation

Next.js mein navigation ke liye Link use hota hai jo client-side navigation provide karta hai aur full page reload nahi karta. useRouter() programmatically navigation ke liye use hota hai, jisme push() new route par navigate karta hai, replace() current history entry ko replace karta hai (back button previous page par nahi le jata), back() previous page par le jata hai aur refresh() current route ka data dobara fetch karke page refresh karta hai bina browser reload ke. usePathname() current route ka pathname return karta hai jo active menu ya route checking ke liye use hota hai. useSearchParams() URL ke query parameters read karne ke liye use hota hai, jaise search, filters, sorting aur pagination.


 Dynamic Routing

Next.js mein Dynamic Routes variable URL segments handle karne ke liye use hote hain, jaise product details ya user profiles. Catch-all Routes multiple dynamic URL segments ko handle karte hain, jabke Route Groups project structure ko organize karne ke liye use hote hain aur ye URL ka hissa nahi bante. Dynamic Route sirf ek dynamic segment handle karta hai, jabke Catch-all Route multiple dynamic URL segments handle karta hai.

Metadata & SEO

Next.js mein Metadata webpage ki SEO information provide karti hai, jaise title aur description. generateMetadata() dynamic pages ke liye runtime par metadata generate karta hai. Dynamic Metadata ki wajah se har page apna unique title aur description rakh sakta hai. Open Graph metadata social media platforms par page ka preview, image aur description show karne ke liye use hota hai.









Thursday, July 9, 2026

Redis Basic Concept

 Redis Quick Overview







What is Redis?

  • Redis ka full form Remote Dictionary Server hai.
  • Ye ek In-Memory NoSQL Database hai.
  • Data RAM (Memory) me store karta hai, is liye bohot fast hota hai.
  • Mostly Caching, Session Management, and Real-time Applications me use hota hai.

Features

  • In-Memory Database
  • Extremely Fast
  • Key-Value Store
  • Open Source
  • NoSQL Database
  • Supports Persistence (Disk par bhi save kar sakta hai)
  • Supports Pub/Sub Messaging

Why Redis fast

  • Data RAM me store hota hai.
  • Disk read/write nahi hoti.
  • Simple Key-Value architecture. 

Use case of Redis

  • Caching
  • Session Storage
  • OTP Store
  • Shopping Cart
  • Leaderboards (Games)
  • Rate Limiting
  • Queue
  • Real-time Chat
  • Pub/Sub Messaging

Redis vs Database

DatabaseRedis
Data Disk meData RAM me
SlowVery Fast
PermanentMostly Temporary
Complex QueriesKey-Value Access



Redis Cache Kya Hai?

Frequently use hone wala data Redis me store kar dete hain taake har baar database hit na ho.

User
|
Application
|
Redis Cache
|
Hit ---> Return Data

Miss
|
Database
|
Store in Redis
|
Return Data

Redis Data Types

  • String
  • List
  • Set
  • Hash
  • Sorted Set
  • Stream

Redis Persistence

Normally RAM me hota hai.

Lekin disk par save bhi kar sakta hai.

Methods:

  • RDB Snapshot
  • AOF (Append Only File)

In Spring Boot, where we can use Redis

  • API Response Cache
  • User Session
  • OTP Verification
  • Rate Limiter
  • JWT Blacklist
  • Frequently Used Data 

Overview
Hum Redis ko API caching aur session management ke liye use karte the. Frequently accessed data pehle Redis se fetch hota tha (Cache Hit). Agar data Redis me available na hota (Cache Miss), to database se fetch karke Redis me cache kar dete the. Is se database load kam hota tha aur application response time kaafi improve ho jata tha.

Thursday, June 25, 2026

Prompt Engineering Explained: Complete Beginner Guide to Writing Better AI Prompts

Prompt Engineering Explained: Complete Beginner Guide to Writing Better AI Prompts




You have probably noticed that two people asking an AI the same question can get very different answers. One gets a sharp, useful response. The other gets something vague and generic. The difference is rarely the AI it is the prompt.

Prompt engineering is the skill of designing and refining the instructions you give to AI models to consistently get high-quality, accurate, and useful results. Whether you are using ChatGPT, Claude, Gemini, or any other AI, the core principle stays the same: better prompts = better AI results.

This guide covers the building blocks, tools, and 10 techniques you need to know — with real examples.


The 4 Building Blocks of Any Good Prompt

Every effective prompt has four parts. Miss even one, and the AI has to start guessing — and guessing leads to generic output.

  1. Context — The background. Who are you? What is the situation?
  2. Input Data — Any relevant facts, findings, or data you already have
  3. Instruction — What exactly you want the AI to do
  4. Output Indication — What kind of response you expect (format, length, tone)

Example:

Context: "I am a backend developer building a REST API in Spring Boot."
Input Data: "The API crashes when more than 500 users connect simultaneously."
Instruction: "Identify the most likely causes and suggest fixes."
Output: "Return a numbered list with code examples in Kotlin."

With all four in place, the AI has full context and clear direction — and the output quality jumps noticeably compared to a vague one-liner prompt.


Top Prompt Engineering Tools

Before using a prompt in a real workflow, experienced engineers test and refine them. Here are the most popular tools for that:

  • IBM watsonx Prompt Lab — Enterprise-grade prompt testing, evaluation, and comparison
  • Spellbook — Designed for legal teams; refine and test contract-focused prompts
  • Dust — Chain and orchestrate prompts across multiple AI models
  • PromptPerfect — Automatically optimizes your prompts for clearer, better results
  • PromptBase — A marketplace to buy and sell high-performing, ready-to-use prompts
  • OpenAI Playground — Test and tweak prompts directly with GPT models in real time

These tools help with prompt suggestions, bias reduction, context management, and building reusable prompt libraries your team can standardize around.


10 Prompt Engineering Techniques That Actually Work

1. Task Specification

Be explicit. Do not assume the AI knows what you mean. Include every detail that matters to the output.

"Write something about databases."
"Write a 600-word comparison of SQL vs NoSQL for mid-level backend developers, focusing on when to choose each one."

2. Contextual Guidance

Tell the AI why you are asking. Background changes the quality of the answer.

"I am preparing for a senior Android developer interview at a fintech company. Explain ViewModel vs AndroidViewModel the way I would explain it to a junior developer."

3. Domain Expertise

Use the correct terminology of your field. The more domain-specific your language, the more precise the response.

A developer asking Explain React async data handling with hooks, component lifecycle, race-condition prevention, and request cancellation"

4. Bias Mitigation

For balanced answers, especially on comparisons or sensitive topics, clearly tell AI that you want multiple viewpoints. Otherwise, AI may give an answer based on the most common patterns from its training data.

"Compare REST and GraphQL. Do not favor either. Give honest answer for both, including scenarios where each one fails."

5. Framing (Adding Constraints)

Set clear boundaries to keep the output focused. Word limits, tone restrictions, and format requirements all help.

"Explain microservices architecture in under 200 words. No buzzwords, no jargon, assume the reader is a frontend developer."

6. Interview Pattern

Tell the AI to ask you clarifying questions before it starts working. This is powerful for complex tasks where wrong assumptions ruin the output.

"I want you to help me design a multi-tenant SaaS architecture. Before you start, ask me everything you need to give the best result."

This turns a one-way prompt into a two-way collaboration. The AI fills its gaps, and the output becomes far more accurate.

7. Chain of Thought (CoT) Prompting

Chain of Thought is about asking the AI to show its reasoning step by step before giving a final answer. This is the core idea — and it dramatically improves accuracy for logic, math, and any multi-step problem.

There are two ways to apply it:

Zero-shot CoT — No examples needed. Just tell the AI to think step by step.

"A train leaves at 9 AM at 60 km/h. Another leaves at 10 AM at 90 km/h in the same direction. When does the second one catch up? Think step by step."

Few-shot CoT — Provide one or two examples with their reasoning shown first, then ask your actual question. The AI learns your expected thinking style.

"Q: 15% of 200? A: 10% of 200 = 20. 5% = 10. So 15% = 30.
Now apply the same method: What is 18% of 450?"

Key point: CoT is not just about whether you give examples or not. It is specifically about getting the AI to reason through the problem rather than jump straight to an answer. Zero-shot and Few-shot are just delivery methods — the step-by-step reasoning is the actual technique.

8. Multi-Model Prompting

Multi-model prompting means using different AI models together, where each one handles the part it does best — like a specialized team, not a single generalist trying to do everything.

Real-world analogy — building a house:

  • 🏛️ Architect (ChatGPT) — Creates the system design and overall plan
  • 🔨 Builder (GitHub Copilot) — Writes and implements the actual code
  • 🔍 Inspector (Claude) — Reviews for quality, bugs, and edge cases

Instead of forcing one model to design, build, and review — you get the best from each. This is especially effective in software development workflows where planning, code generation, and review require different strengths.

9. Tree of Thoughts (ToT)

Tree of Thoughts goes beyond linear reasoning. Instead of one straight path to an answer, the AI explores multiple reasoning paths at each decision point — like branches of a tree — before committing to the best one.

Example prompt:

"Try three different database designs for a social media app. For each one, explore how it handles scalability, security, and performance. Then recommend the best design and explain why."

🌳 Easy way to remember it: "Take three roads, see where each leads, then pick the best one."

10. Playoff Method

Similar to Tree of Thoughts, but structured more like a tournament. The AI generates multiple solutions, compares them head-to-head, and selects a winner based on your criteria.

Example prompt:

"Create three different architectures for a real-time notification system. Compare them on performance, cost, and complexity. Recommend the best one."

🏆 Easy way to remember it: "Make solutions compete in a bracket until one wins."

ToT vs Playoff — Quick Comparison

Tree of Thoughts 🌳Playoff Method 🏆
StyleExplore multiple reasoning pathsGenerate options, compare, eliminate
ProcessBranches through a problem step by stepTournament-style comparison of outputs
Best forMulti-step reasoning and explorationComparing and selecting final solutions

Key Takeaways

  • A prompt is an instruction to AI. A better prompt always means a better result
  • Every good prompt needs: Context + Input Data + Instruction + Output Format
  • Test prompts using tools like watsonx, PromptPerfect, or OpenAI Playground before deploying them
  • Use Chain of Thought when you need reasoning, not just a quick answer
  • Use Multi-model prompting to get specialized performance from different AI models
  • Use Tree of Thoughts or Playoff when you want the AI to evaluate multiple paths or options
  • Always be specific, add constraints, and remove any room for guesswork

Final Thoughts

Prompt engineering is becoming a core skill not just for AI researchers, but for developers, product managers, and anyone who works with AI tools regularly. The good news is that you do not need a machine learning background to get good at it. You just need to communicate clearly, think about what you actually want, and keep refining based on results.

Start with the 4 building blocks. Add one technique at a time. Test, observe, adjust.

The AI does not read minds  but with a well-engineered prompt, it does not need to.

Tuesday, June 23, 2026

 Generative AI Explained: From Discriminative AI to Agentic AI

 Generative AI Explained: From Discriminative AI to Agentic AI




Introduction

Artificial Intelligence (AI) has changed a lot over time. In the beginning, AI was mainly used to follow rules and make predictions. Later, Machine Learning and Deep Learning helped computers learn from data. Today, Generative AI can create new content like text, images, audio, videos, and code.

This blog explains the journey from Discriminative AI to Generative AI and Agentic AI.


What is Discriminative AI?

Before Generative AI, we mainly used Discriminative AI models.

Discriminative AI focuses on finding the difference between classes of data. It learns patterns from existing data and predicts the correct result.

The main idea is:

P(Class | Data)

It means:

"What is the probability of a class when we have given data?"

Examples:

  • Is this email spam or not?
  • Is this image a cat or a dog?
  • Is a transaction fraud or normal?


Limitations of Discriminative AI

Discriminative AI is good at classification and prediction, but it cannot create new content.

It can answer:

"Is this a cat?"

But it cannot create:

"Generate a new image of a cat."

To solve this limitation, Generative AI was introduced.


What is Generative AI?

Generative AI is a type of AI that can create new content based on the data it has learned from.

It can dynamically generate:

  • Text (articles, code, answers)
  • Images (art, product photos, designs)
  • Audio (voice, music)
  • Video (animations, synthetic video)

This was a big shift. Instead of just predicting a label, the AI now had to understand and produce content.

The Four Core Architectures of Generative AI

Generative AI is not built on a single model. There are four main architectures, and each one is good at different things.

1. GANs (Generative Adversarial Networks)

GANs are mainly used for image generation.

They have two parts:

  • Generator: Creates new content
  • Discriminator: Checks if content looks real

The generator improves by trying to fool the discriminator.

Example:

  • Creating realistic human faces
  • Image generation
Known models: StyleGAN, BigGAN

Note: Earlier versions of DALL-E were associated with GAN research, but modern DALL-E (2 and 3) is built on Transformer + Diffusion architecture.


2. VAEs — Variational Autoencoders

VAEs work by compressing data into a small representation and then reconstructing it. They are good at learning the structure of data.

Best for: Data compression, reconstruction, and generating variations of existing data

Known models: Beta-VAE, VQ-VAE


3. Transformers

This is the architecture that changed everything. Transformers use a mechanism called attention — they figure out which parts of the input matter most when producing an output.

Best for: Text, audio, video, and image generation. Known LLMs built on this:

  • GPT series (OpenAI)
  • Claude (Anthropic)
  • Gemini (Google)
  • LLaMA (Meta)
  • DALL-E 3 (OpenAI) — multimodal Transformer

4. Diffusion Models

Diffusion models work by learning to remove noise from an image step by step. They start with pure noise and slowly clean it into a final image.

Best for: High-quality, detailed image generation

Known models: Stable Diffusion, Midjourney, DALL-E 3

Today, Diffusion Models have largely replaced GANs for image generation tasks because they produce more stable and higher-quality results.


How Did AI Evolve Over Time?


Stage                                     : What it did

Early / Rule-Based AI     = Followed fixed, hand-written rules

Machine Learning (ML)     =    Learned patterns from data to make predictions

Deep Learning (DL)    =    Understood complex patterns using neural networks

Generative Models     =    Created new content (GANs, VAEs, Diffusion)

Foundation Models    =     Large pre-trained models used for many tasks (GPT, Claude, Gemini) 


Popular LLMs and What They Are Best At

There are many LLMs available today. Each one is built for a specific use case.

Model

Best For

ChatGPT    Dynamic conversations and general-purpose responses
Gemini    Research-heavy tasks and Google ecosystem integration
Claude    Long-context tasks, safe and natural long-form writing
Jasper    Marketing content and brand copywriting
Rytr    Blog posts, emails, and SEO content
Resoomer    Text summarization
DeepL / Google Translate    High-quality language translation
NOLEJ    Education-focused AI content
Watson AIOps    Analyzing system logs, data streams, and detecting anomalies
Midjourney    Artistic, high-detail, and visually aesthetic image generation


Generative AI vs Agentic AI

Generative AI and Agentic AI are related but different.

Generative AIAgentic AI
Creates content                                     Takes actions
Generates text, images, and code                 Makes decisions and completes tasks
Reactive                 More proactive
Example: Writing an email                Example: Booking a flight



How They Work Together

Agentic AI does not replace Generative AI — it uses it.

Think of it this way:

  • Generative AI is the brain — it understands the goal and creates a plan
  • Agentic AI is the hands — it executes that plan step by step in the real world



Popular AI tools for architecture Diagram

  • Lucidchart AI — AI-powered diagram creation, templates, team collaboration
  • Eraser AI — Fast technical diagrams, system designs, developer workflows
  • Google Gemini — Architecture ideas, documentation help, diagram assistance


Few Other AI tools

  • Qodo — AI code quality tool that helps generate and review tests
  • LambdaTest — Cloud platform for cross-browser and device testing
  • KaneAI — AI-powered tool for creating and managing test cases
  • TestRegister — Test management tool for organising QA activities
  • Snyk — Security tool that finds vulnerabilities in code and dependencies
  • Checkmarx — Application security platform for code scanning and risk detection
  • Courser — Learning platform/tool for courses and skill development
  • Windsurf — AI coding editor that helps developers write and modify code
  • Bolt AI — AI tool for quickly building applications from prompts
  • Vibe AI — AI development assistant for creating and improving software projects