JavaScript Interview Questions & Answers — Complete Guide
Bhai, CSS wale guide ki tarah yeh bhi Beginner → Intermediate → Experienced level mein
structured hai, code examples ke saath.
👨💻 Basic Level (Freshers)
1. What is JavaScript and its common uses?
JavaScript ek high-level, interpreted programming language hai jo originally browsers ko
interactive banane ke liye bani thi. Aaj yeh sirf frontend tak limited nahi hai:
Frontend — DOM manipulation, interactivity (React, Vue, Angular)
Backend — [Link] se server-side apps
Mobile — React Native
Desktop — Electron
2. Template literals kya hain?
Backticks ( ` ) se banaye gaye strings jo variable interpolation aur multi-line strings allow
karte hain — string concatenation ( + ) ki jagah cleaner syntax.
javascript
const name = "Devanshu";
const greeting = `Hello, ${name}! Aaj ${new Date().getDate()} tareekh hai.`;
3. Hoisting kya hai?
JavaScript execution se pehle variable aur function declarations ko unke scope ke top pe
"move" kar deta hai (memory allocation phase mein). var aur function declarations hoist
hoti hain, but let / const bhi hoist hoti hain — bas woh "Temporal Dead Zone" mein rehti
hain, access karne pe error dete hain.
javascript
[Link](a); // undefined (hoisted, not initialized)
var a = 5;
[Link](b); // ReferenceError (TDZ)
let b = 10;
4. let , var , aur const mein difference?
var let const
Scope Function-scoped Block-scoped Block-scoped
Re-declare Allowed Not allowed Not allowed
Re-assign Allowed Allowed Not allowed
Hoisting undefined se initialize TDZ mein rehta hai TDZ mein rehta hai
const ka matlab value reassign nahi ho sakti, but agar wo object/array hai to uske andar ke
properties/elements change kar sakte ho.
5. JavaScript mein data types?
Primitive: string , number , boolean , null , undefined , symbol , bigint Non-primitive
(reference): object (arrays, functions, objects sab isi ke andar aate hain)
6. Array kya hai, elements kaise access karte hain?
Array ordered values ka collection hai, zero-indexed.
javascript
const fruits = ["apple", "banana", "mango"];
[Link](fruits[0]); // "apple"
[Link]([Link]); // 3
7. == vs === ?
== (loose equality) — comparison se pehle type coercion karta hai.
=== (strict equality) — type aur value dono check karta hai, coercion nahi karta.
javascript
"5" == 5 // true (coercion)
"5" === 5 // false (different types)
Best practice: hamesha === use karo predictable behavior ke liye.
8. isNaN function ka purpose?
Check karta hai ki value "Not a Number" hai ya nahi. Note: isNaN() pehle value ko number
mein convert karne ki koshish karta hai, isliye kabhi-kabhi unexpected results deta hai
( isNaN("hello") → true , isNaN("123") → false ). [Link]() zyada strict hai (bina
coercion ke).
9. null vs undefined ?
undefined — variable declare hua hai but value assign nahi hui, ya function ka koi
return statement nahi (implicitly JS deta hai).
null — developer explicitly "no value" assign karta hai — intentional emptiness.
javascript
let a;
[Link](a); // undefined
let b = null;
[Link](b); // null
10. typeof operator ka use?
Kisi value ka data type (string form mein) return karta hai.
javascript
typeof "hello" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" (famous JS quirk/bug, historical reason)
typeof {} // "object"
typeof function(){} // "function"
👨💻 Intermediate Level
11. map method ka purpose?
Array ke har element pe ek function apply karke naya array return karta hai (original array
untouched rehta hai).
javascript
const nums = [1, 2, 3];
const doubled = [Link](n => n * 2); // [2, 4, 6]
12. Event bubbling aur event capturing?
Jab kisi nested element pe event trigger hota hai, toh usse handle karne ke 2 phases hote
hain:
Capturing — event document se target element tak "top-down" travel karta hai.
Bubbling — event target se document tak "bottom-up" travel karta hai (default
behavior).
javascript
[Link]('click', handler, true); // capturing phase
[Link]('click', handler, false); // bubbling phase (default)
13. Higher-order functions kya hain?
Function jo (a) ek ya zyada functions ko argument ke roop mein leta hai, aur/ya (b) ek
function return karta hai. map , filter , reduce iske common examples hain.
javascript
function greet(name) {
return function(message) {
return `${message}, ${name}!`;
};
}
14. IIFE (Immediately Invoked Function Expression) kya hai?
Ek function jo define hote hi turant execute ho jaata hai — variables ko global scope se
pollute hone se bachata hai.
javascript
(function() {
[Link]("Runs immediately");
})();
15. Closures kya hain?
Closure tab banta hai jab ek inner function apne outer function ki variables ko "remember"
karta hai, chahe outer function execution khatam ho chuka ho.
javascript
function counter() {
let count = 0;
return function() {
count++;
return count;
};
}
const increment = counter();
increment(); // 1
increment(); // 2
count variable "close over" ho gaya hai — private state banane, data hiding, module
patterns ke liye use hota hai.
16. setTimeout aur setInterval kaise kaam karte hain?
setTimeout(fn, delay) — fn ko delay ms baad ek baar run karta hai.
setInterval(fn, delay) — fn ko har delay ms mein repeatedly run karta hai jab
tak clearInterval() na ho.
javascript
const timer = setTimeout(() => [Link]("Once"), 1000);
const interval = setInterval(() => [Link]("Repeats"), 1000);
clearInterval(interval); // stop karne ke liye
Dono asynchronous hain — event loop ke through call stack khaali hone ke baad hi execute
hote hain, delay guaranteed nahi hota, minimum wait time hota hai.
17. Promises kya hain?
Promise ek object hai jo future mein complete hone waale asynchronous operation ka result
represent karta hai. Teen states: pending , fulfilled , rejected .
javascript
const fetchData = new Promise((resolve, reject) => {
const success = true;
if (success) resolve("Data received");
else reject("Error occurred");
});
fetchData
.then(data => [Link](data))
.catch(err => [Link](err));
18. async / await ka use?
Promises ke upar syntactic sugar hai jo asynchronous code ko synchronous jaisa
dikhne/likhne deta hai — readability improve karta hai, especially multiple chained async
calls mein.
javascript
async function getData() {
try {
const response = await fetch('[Link]
const data = await [Link]();
[Link](data);
} catch (error) {
[Link](error);
}
}
19. call , apply , aur bind mein difference?
Teeno this ki value manually set karne ke liye use hote hain:
call — function ko turant invoke karta hai, arguments comma-separated pass hote
hain.
apply — function ko turant invoke karta hai, arguments array ke form mein pass hote
hain.
bind — turant invoke nahi karta, ek naya function return karta hai jisme this
permanently bound ho chuka hota hai.
javascript
const person = { name: "Devanshu" };
function greet(greeting) { [Link](`${greeting}, ${[Link]}`); }
[Link](person, "Hi"); // Hi, Devanshu
[Link](person, ["Hello"]); // Hello, Devanshu
const boundGreet = [Link](person);
boundGreet("Hey"); // Hey, Devanshu
20. Event delegation kya hai?
Ek single event listener ko parent element pe attach karna, jo apne child elements ke events
ko bubbling ke through handle karta hai — dynamically added elements ke liye bhi kaam
karta hai bina alag-alag listener attach kiye.
javascript
[Link]('list').addEventListener('click', function(e) {
if ([Link] === 'LI') {
[Link]('Clicked:', [Link]);
}
});
👨💻 Experienced Level
21. Event loop kya hai?
JavaScript single-threaded hai, but event loop ke through asynchronous operations handle
karta hai:
1. Call stack — synchronous code yahan execute hoti hai.
2. Web APIs — async operations (setTimeout, fetch, DOM events) yahan background
mein handle hote hain.
3. Callback/Task queue — completed async operations ke callbacks yahan wait karte
hain.
4. Microtask queue — Promises ke callbacks yahan queue hote hain (task queue se
higher priority).
Event loop continuously check karta hai — jab call stack empty ho, toh pehle saari
microtasks run karta hai, phir ek macrotask (task queue se) le kar aata hai.
javascript
[Link]("1");
setTimeout(() => [Link]("2"), 0);
[Link]().then(() => [Link]("3"));
[Link]("4");
// Output: 1, 4, 3, 2
22. Promises vs async/await?
Dono same underlying mechanism (Promises) use karte hain — async/await sirf cleaner
syntax hai:
Promises → .then() / .catch() chaining, deeply nested calls readability kharab kar
sakti hain.
async/await → try/catch ke saath linear, synchronous-looking code; debugging aur
error handling easier.
23. reduce method ka purpose?
Array ke saare elements ko ek single value mein "reduce" karta hai, ek accumulator
function ke through.
javascript
const nums = [1, 2, 3, 4];
const sum = [Link]((acc, curr) => acc + curr, 0); // 10
Sum, max/min find karna, arrays ko objects mein group karna — bohot versatile method
hai.
24. Currying kya hai?
Ek function jo multiple arguments lene ki jagah, ek time pe ek argument leta hai aur har
baar ek naya function return karta hai jab tak saare arguments na mil jaayein.
javascript
function multiply(a) {
return function(b) {
return function(c) {
return a * b * c;
};
};
}
multiply(2)(3)(4); // 24
Reusable, configurable functions banane ke liye useful (jaise partial application).
25. Generator function kya hai aur uska usage?
function*syntax se define hota hai, yield keyword se execution pause/resume kar sakte
ho — normal function ki tarah ek baar mein poora run nahi hota.
javascript
function* idGenerator() {
let id = 1;
while (true) {
yield id++;
}
}
const gen = idGenerator();
[Link]().value; // 1
[Link]().value; // 2
Custom iterators banane, infinite sequences, aur lazy evaluation ke liye use hota hai.
26. WeakMap aur WeakSet kya hain?
Map / Set ki tarah hi hain, but sirf objects ko keys/values ke roop mein le sakte hain
(primitives nahi), aur weakly referenced hote hain — matlab agar object kahin aur
reference nahi ho raha, toh garbage collector use memory se hata sakta hai. Yeh memory
leaks avoid karne mein help karta hai, especially private data ya metadata objects se
associate karte waqt.
javascript
const wm = new WeakMap();
let obj = {};
[Link](obj, "some data");
obj = null; // ab garbage collected ho sakta hai, WeakMap use force nahi karta
27. JavaScript memory management kaise handle karta hai?
JS automatic memory management use karta hai via Garbage Collection:
1. Memory allocate hoti hai jab variables/objects create hote hain.
2. Garbage collector periodically check karta hai kaunse objects ab "reachable" nahi
hain (koi reference nahi bacha).
3. Unreachable objects ko memory se free kar deta hai — mostly Mark-and-Sweep
algorithm use hota hai.
Developer ko manually memory free nahi karni padti, but unnecessary references
(closures, global variables, event listeners na hataana) memory leaks cause kar sakte hain.
28. Shallow copy vs deep copy?
Shallow copy — sirf top-level properties copy hoti hain; nested objects/arrays same
reference share karte hain (ek change dono jagah reflect hoga).
javascript
const original = { a: 1, nested: { b: 2 } };
const shallow = { ...original };
[Link].b = 99; // [Link].b bhi 99 ho jaayega
Deep copy — nested levels tak sab kuch independently copy hota hai, references
share nahi hote.
javascript
const deep = structuredClone(original); // modern way
// ya: [Link]([Link](original)) — but functions/undefined lose ho j
29. Strict mode kya hai, kaise enable karte hain?
"use strict" directive JS ko stricter parsing/error-handling mode mein daal deta hai —
silent errors ko throw errors mein convert karta hai, kuch unsafe actions (jaise undeclared
variables create karna) ko block karta hai, aur this ko undefined rakhta hai (global object
ki jagah) plain function calls mein.
javascript
"use strict";
x = 10; // ReferenceError: x is not defined (strict mode ke bina silently globa
File ke top pe ya function ke andar likh sakte ho. ES6 modules aur classes automatically
strict mode mein hote hain.
30. Observer pattern aur uska JavaScript se relation?
Observer pattern ek design pattern hai jisme ek "subject" apne "observers/subscribers" ki
list maintain karta hai aur state change hone pe unhe notify karta hai. JavaScript mein yeh
pattern bohot common hai:
DOM events ( addEventListener ) khud observer pattern ka example hain.
RxJS Observables, [Link] EventEmitter, aur React state management libraries
(Redux) isi principle pe based hain.
javascript
class EventEmitter {
constructor() { [Link] = {}; }
on(event, callback) {
([Link][event] ??= []).push(callback);
}
emit(event, data) {
([Link][event] || []).forEach(cb => cb(data));
}
}
const emitter = new EventEmitter();
[Link]('greet', name => [Link](`Hello, ${name}`));
[Link]('greet', 'Devanshu'); // Hello, Devanshu
Quick Revision Tips
Closures, event loop, aur promises vs async/await — yeh sabse zyada pooche jaate
hain, especially MERN roles ke liye.
Coding round mein map / reduce / filter aur currying se related practical questions
expect karo.
this binding (call/apply/bind) aur hoisting ke tricky examples interview mein
whiteboard pe likhwaye jaate hain — practice kar lena.