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
thisnahi hota. - Parent/Lexical
thisuse karta hai. - Constructors ke tor par use nahi ho sakta.
Normal Function vs Arrow Function
Normal Function
- Apna
thishota hai. - Zarurat par
bind(),call(), yaapply()use karna pad sakta hai.
Arrow Function
- Apna
thisnahi hota. - Parent ka
thisuse karta hai.
Interview Answer:
Arrow Function ka syntax short hota hai aur iska apna
thisnahi hota. Ye lexicalthisuse karta hai, yani parent scope kathis. Normal function ka apnathishota 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
thiskis 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
| Debouncing | Throttling |
|---|---|
| User stop kare, phir function chale. | Function fixed interval par chalta rahe. |
| Search Box | Scroll & 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
useMemoReact 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
useCallbackReact 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?
useCallbacktab 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
useSelectorse state read karte hain auruseDispatchse 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 UpdateRedux 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
createAsyncThunkuse 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
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
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.
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.<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
- 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
revalidateinterval 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.
Static Data → SSG
Occasionally Changing Data → ISR
Always Fresh Data → SSR
User-Specific / No SEO → CSR
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
For pages like/products/[id], usegenerateMetadata()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.
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
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.- 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
Metadata & SEO
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.
0 comments: