[go: up one dir, main page]

0% found this document useful (0 votes)
2 views14 pages

Untitled Document

This document contains a comprehensive set of JavaScript interview questions and answers tailored for developers with 6 years of experience. Key topics include differences between equality operators, closures, the event loop, variable declarations, and various advanced concepts like async/await, memory leaks, and prototypal inheritance. Each question is accompanied by explanations and real-world examples to illustrate the concepts effectively.

Uploaded by

Raja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views14 pages

Untitled Document

This document contains a comprehensive set of JavaScript interview questions and answers tailored for developers with 6 years of experience. Key topics include differences between equality operators, closures, the event loop, variable declarations, and various advanced concepts like async/await, memory leaks, and prototypal inheritance. Each question is accompanied by explanations and real-world examples to illustrate the concepts effectively.

Uploaded by

Raja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

JavaScript Interview Q&A for 6 Years Experienced

Developers
✅ Q1. What is the difference between == and === in JavaScript?
Why is === preferred in modern codebases?
🔹 Explanation:

== is the loose equality operator, which performs type coercion before comparison. === is the
strict equality operator, which checks both value and type without coercion.

🔹 Real-World Example:

Form validation in a React app:

const userAgeInput = '18'; // string from input


const allowedAge = 18;

if (userAgeInput == allowedAge) { // ✅ true due to coercion }


if (userAgeInput === allowedAge) { // ❌ false, types don't match }

Using == may cause bugs:

false == 0 // true
[] == false // true

✅ Interview Pro Tip:

Always use === for predictable behavior. Convert types explicitly if needed.

✅ Q2. What are closures in JavaScript? Explain with real-world


use case.
🔹 Explanation:

A closure is when a function remembers variables from its lexical scope even after the outer
function has finished executing.

🔹 Real-World Example:

Rate Limiting:
function createRateLimiter() {
let lastClicked = 0;
const limit = 3000;

return function () {
const now = Date.now();
if (now - lastClicked > limit) {
console.log('Action allowed ✅');
lastClicked = now;
} else {
console.log('Action blocked ❌');
}
};
}

const handleClick = createRateLimiter();

The handleClick remembers lastClicked even after createRateLimiter() has run —


that’s a closure.

✅ Interview Pro Tip:

Closures are crucial for private state, debouncing, and custom React hooks.

✅ Q3. Explain the Event Loop in JavaScript.


🔹 Explanation:

The Event Loop is what allows JavaScript to be non-blocking and handle asynchronous
operations using a single thread. It manages the call stack, microtask queue, and callback/task
queue.

🔹 Real-World Example:
console.log('Start');

setTimeout(() => console.log('Timeout'), 0);


Promise.resolve().then(() => console.log('Promise'));

console.log('End');

Output:

Start
End
Promise
Timeout

● The promise’s .then() goes into the microtask queue and is processed before
setTimeout, which goes into the callback queue.

✅ Interview Pro Tip:

"Understanding the event loop helps prevent UI blocking and design responsive,
async-heavy frontend apps. I’ve debugged performance issues by analyzing task
prioritization between microtasks and macrotasks."

✅ Q4. What is the difference between let, const, and var?


Keyword Scope Hoisting Reassignabl
e

var Function Yes ✅ Yes


(undefined)

let Block Yes (TDZ) ✅ Yes

const Block Yes (TDZ) ❌ No

🔹 Real-World Example:

Avoid var in modern code. It creates bugs in loops and closures:

for (var i = 0; i < 3; i++) {


setTimeout(() => console.log(i), 0); // prints 3, 3, 3 ❌
}

Use let:

for (let i = 0; i < 3; i++) {


setTimeout(() => console.log(i), 0); // 0, 1, 2 ✅
}
✅ Q5. What is this in JavaScript? How does it behave differently in
arrow functions?
🔹 Explanation:

this refers to the execution context. Its behavior depends on how a function is called.

🔹 Arrow Function Behavior:

Arrow functions don’t have their own this. They inherit this from the enclosing context.

🔹 Real-World Example:
const user = {
name: 'Raja',
greet: function () {
setTimeout(() => {
console.log(`Hello, ${this.name}`); // ✅ Raja
}, 100);
},
};
user.greet();

Using regular function inside setTimeout would print undefined.

✅ Q6. What are higher-order functions? Give a real-world use


case.
🔹 Explanation:

A higher-order function is one that takes another function as argument or returns a function.

🔹 Real-World Use Case: Dynamic Filter


function filterUsers(users, conditionFn) {
return users.filter(conditionFn);
}

const isActive = (user) => user.active;


filterUsers(userList, isActive);

This allows reusable, composable filters in large apps.


✅ Q7. What is hoisting? How does it affect var, let, and const?
🔹 Explanation:

Hoisting moves declarations to the top of their scope, but not initializations.

● var is hoisted and initialized as undefined.

● let and const are hoisted but not initialized (TDZ).

console.log(a); // undefined
var a = 10;

console.log(b); // ReferenceError
let b = 10;

✅ Q8. Explain the difference between call, apply, and bind.


Method Immediate Execution Argument
Passing

call Yes Individual args

apply Yes Array of args

bind No (returns function) Individual args

🔹 Real-World Example:
function greet(lang) {
console.log(`${lang}: Hello, ${this.name}`);
}

const user = { name: 'Raja' };


const greeter = greet.bind(user);
greeter('EN'); // EN: Hello, Raja

✅ Q9. What is a deep copy vs shallow copy in JavaScript?


🔹 Shallow Copy:

Copies references of nested objects.


const original = { user: { name: 'Raja' } };
const copy = { ...original };
copy.user.name = 'Kumar';
console.log(original.user.name); // 'Kumar' ❌

🔹 Deep Copy:
const deep = JSON.parse(JSON.stringify(original));

Or use structuredClone() for modern deep copies.

✅ Q10. Explain prototypal inheritance in JavaScript.


🔹 Explanation:

JavaScript uses prototype chains instead of classical inheritance.


Each object has an internal link to another object — its prototype.

const animal = {
speak() { console.log('Animal speaks'); }
};

const dog = Object.create(animal);


dog.speak(); // 'Animal speaks'

Used in component design and reusability in frameworks.

(To be continued with Q11 to Q30 in same depth: async/await, memory leaks, module systems,
performance optimizations, currying, tail recursion, pub/sub, maps vs objects, etc.)

JavaScript Interview Q&A for 6 Years Experienced


Developers
...[Q1 to Q10 already added above]...

✅ Q11. What is the difference between async/await and


Promises?
🔹 Explanation:

Both async/await and Promises handle asynchronous code. Async/await is syntactic sugar
over Promises, making the code more readable and linear.

🔹 Real-World Example:
// Promise style
fetch('/api/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err));

// async/await style
async function loadData() {
try {
const response = await fetch('/api/data');
const data = await response.json();
console.log(data);
} catch (err) {
console.error(err);
}
}

Use async/await to avoid "callback hell" in complex async flows.

✅ Q12. What causes memory leaks in JavaScript applications?


🔹 Explanation:

Common causes:

● Unremoved event listeners

● Detached DOM elements still referenced

● Forgotten timers or intervals

● Closures holding unnecessary references

🔹 Real-World Example:
function setup() {
const element = document.getElementById('myBtn');
element.addEventListener('click', () => {
console.log('Clicked');
});
}

If this listener is not removed when the DOM node is destroyed, it stays in memory.

✅ Q13. What are ES Modules and how do they differ from


CommonJS?
Feature CommonJS ES Modules (import)
(require)

Loading Synchronous Asynchronous

Used In Node.js Browsers + Node (modern)

Exports module.exports export

🔹 Example:
// ESM
import { func } from './util.js';

// CJS
const func = require('./util');

✅ Q14. What is the difference between map(), filter(), and


reduce()?
🔹 Explanation:

● map: transforms elements

● filter: selects elements

● reduce: accumulates elements

🔹 Real-World Example:
const nums = [1, 2, 3];
nums.map(n => n * 2); // [2, 4, 6]
nums.filter(n => n > 1); // [2, 3]
nums.reduce((acc, val) => acc + val, 0); // 6

Used heavily in form processing, analytics, and transformation logic.

✅ Q15. Explain currying and give a use case.


🔹 Explanation:

Currying transforms a function that takes multiple arguments into a series of functions that each
take one argument.

function multiply(a) {
return function (b) {
return a * b;
};
}
const double = multiply(2);
console.log(double(5)); // 10

Used in reusable functional utilities or React event abstraction.

✅ Q16. What are Generators and how are they used?


🔹 Explanation:

Generators (function*) are functions that can pause using yield, then resume later.

🔹 Example:
function* idGen() {
let id = 0;
while (true) yield ++id;
}
const gen = idGen();
gen.next().value; // 1
gen.next().value; // 2

Used in pagination, async control flow, infinite sequences.


✅ Q17. How do you debounce a function in JavaScript?
🔹 Explanation:

Debouncing limits how often a function is executed. Useful in search, resize, and scroll events.

🔹 Implementation:
function debounce(fn, delay) {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => fn(...args), delay);
};
}

✅ Q18. Difference between Object.keys(), Object.values(), and


Object.entries()

● Object.keys(obj): returns array of keys

● Object.values(obj): array of values

● Object.entries(obj): key-value pairs

const user = { name: 'Raja', age: 30 };


Object.keys(user); // ['name', 'age']
Object.entries(user); // [['name', 'Raja'], ['age', 30]]

✅ Q19. What is the difference between for...in and for...of?


Loop Type Iterates Over Use Case

for...in Keys Objects

for...of Values Arrays, Iterables


const arr = ['a', 'b'];
for (const i in arr) console.log(i); // 0,1
for (const v of arr) console.log(v); // a,b
✅ Q20. Explain the concept of the call stack.
The call stack keeps track of function calls in a LIFO (last-in-first-out) order.

function a() { b(); }


function b() { c(); }
function c() { console.log('done'); }
a();

Stack: a → b → c → log → pop all

✅ Q21. What is a Polyfill?


A polyfill is code that provides modern JS feature support for older environments.

🔹 Example:
if (!Array.prototype.includes) {
Array.prototype.includes = function (val) {
return this.indexOf(val) !== -1;
};
}

✅ Q22. What is tail call optimization (TCO)?


A recursive function is optimized when the final action is the recursive call. Saves stack frames.

Note: Not supported in all JS engines.

function factorial(n, acc = 1) {


if (n <= 1) return acc;
return factorial(n - 1, n * acc);
}

✅ Q23. What is the use of WeakMap and WeakSet?

● WeakMap: key must be an object. Keys are weakly referenced — prevents memory
leaks.

● WeakSet: holds weakly referenced objects.


Used in caching DOM or private data.

✅ Q24. How do you deeply compare two objects?


🔹 Naive Approach:
function deepEqual(a, b) {
return JSON.stringify(a) === JSON.stringify(b);
}

For complex structures, use recursion or libraries like Lodash’s _.isEqual().

✅ Q25. How do you design a Pub/Sub system in JavaScript?


class PubSub {
constructor() {
this.events = {};
}
subscribe(event, cb) {
(this.events[event] ||= []).push(cb);
}
publish(event, data) {
(this.events[event] || []).forEach(fn => fn(data));
}
}

Used in modular apps for decoupled communication.

✅ Q26. Difference between setTimeout and setInterval?

● setTimeout(fn, delay): runs once after delay

● setInterval(fn, delay): runs repeatedly every delay

Use clearTimeout() / clearInterval() to cancel.

✅ Q27. What’s the difference between Object and Map?


Feature Object Map

Key Types Strings/Symbols Any

Ordered No Yes

Performance Slower Faster (large


data)

✅ Q28. What are service workers?


Service workers are scripts that run in the background, enabling offline support and caching.

Used in PWAs (Progressive Web Apps) to cache assets, handle fetch, push notifications.

✅ Q29. What is optional chaining in JavaScript?

Optional chaining ?. allows safe access to deeply nested properties.

const user = { profile: { name: 'Raja' } };


console.log(user?.profile?.name); // 'Raja'
console.log(user?.account?.email); // undefined, no error

✅ Q30. What are template literals and tagged templates?


Template literals use backticks (`) to embed expressions and multiline strings.

const name = 'Raja';


console.log(`Hello, ${name}`);

Tagged templates let you preprocess templates:

function tag(strings, ...values) {


return strings[0] + values[0].toUpperCase();
}
tag`Hello, ${name}`; // "Hello, RAJA"

✅ This completes the 30 JavaScript interview Q&A tailored for 6+ years experienced
developers in Indian tech interviews.

You might also like