Top 20 JavaScript Interview Questions with Code Examples
Thank you for providing your email. Here's your comprehensive guide to JavaScript interview questions:
1. Explain Closures in JavaScript
A closure is a function that has access to variables in its outer (enclosing) lexical scope, even after the outer function has returned.
function createCounter() { let count = 0; return { increment: function() { count++; return count; }, getCount: function() { return count; } } } const counter = createCounter(); console.log(counter.increment()); // 1 console.log(counter.increment()); // 2 console.log(counter.getCount()); // 2
2. What is Event Delegation?
Event delegation is a technique where you attach an event listener to a parent element to handle events on its children, even those added dynamically.
document.getElementById('parent').addEventListener('click', function(e) { if (e.target.className === 'child') { console.log('Child element clicked'); } });
3. Explain Promise and Async/Await
Promises handle asynchronous operations, and async/await provides a cleaner syntax for working with promises.
// Promise example const promise = new Promise((resolve, reject) => { setTimeout(() => resolve("Success!"), 1000); }); // Async/Await example async function fetchData() { try { const result = await promise; console.log(result); } catch (error) { console.error(error); } }
4. What is Prototypal Inheritance?
JavaScript uses prototypal inheritance - objects can inherit properties and methods from other objects.
function Animal(name) { this.name = name; } Animal.prototype.speak = function() { return `${this.name} makes a sound.`; } function Dog(name) { Animal.call(this, name); } Dog.prototype = Object.create(Animal.prototype); Dog.prototype.constructor = Dog;
5. Explain 'this' Keyword
The value of 'this' depends on how and where a function is called, not where it's defined.
const obj = { name: 'Object', greet: function() { console.log(`Hello, ${this.name}!`); } }; obj.greet(); // Hello, Object! const greet = obj.greet; greet(); // Hello, undefined! (in non-strict mode)
6. Explain let, const, and var
Different ways to declare variables with different scoping rules.
{ var x = 1; // function-scoped let y = 2; // block-scoped const z = 3; // block-scoped and cannot be reassigned } console.log(x); // 1 console.log(y); // ReferenceError console.log(z); // ReferenceError
7. What is Event Loop?
The event loop handles asynchronous callbacks and manages execution order.
console.log('Start'); setTimeout(() => { console.log('Timeout'); }, 0); Promise.resolve().then(() => { console.log('Promise'); }); console.log('End'); // Output: // Start // End // Promise // Timeout
8. Explain Map vs WeakMap
Map and WeakMap are collections of key-value pairs with different memory management characteristics.
const map = new Map(); const weakMap = new WeakMap(); let obj = { id: 1 }; map.set(obj, 'value'); weakMap.set(obj, 'value'); obj = null; // WeakMap entry will be garbage collected
9. What are Arrow Functions?
Arrow functions provide a shorter syntax and lexically bind 'this'.
const traditional = function(x) { return x * 2; }; const arrow = x => x * 2; // 'this' binding const obj = { value: 42, getValue: () => this.value, // 'this' is inherited getValueTraditional: function() { return this.value; // 'this' is bound to obj } };
10. Explain Debouncing
Debouncing limits the rate at which a function is called.
function debounce(func, delay) { let timeoutId; return function(...args) { clearTimeout(timeoutId); timeoutId = setTimeout(() => { func.apply(this, args); }, delay); }; }
11. What is Function Currying?
Currying transforms a function with multiple arguments into a sequence of functions with single arguments.
const add = x => y => z => x + y + z; console.log(add(1)(2)(3)); // 6 // Alternative currying function multiply(a) { return function(b) { return a * b; } } console.log(multiply(2)(3)); // 6
12. Explain Memoization
Memoization is an optimization technique that stores function results for reuse.
function memoize(fn) { const cache = new Map(); return function(...args) { const key = JSON.stringify(args); if (cache.has(key)) return cache.get(key); const result = fn.apply(this, args); cache.set(key, result); return result; }; }
13. What is the Temporal Dead Zone?
The TDZ is the period between entering scope and variable declaration where let and const cannot be accessed.
console.log(x); // undefined console.log(y); // ReferenceError var x = 1; let y = 2;
14. Explain Generator Functions
Generator functions can pause execution and resume later, yielding multiple values.
function* numberGenerator() { yield 1; yield 2; yield 3; } const gen = numberGenerator(); console.log(gen.next().value); // 1 console.log(gen.next().value); // 2 console.log(gen.next().value); // 3
15. What are Pure Functions?
Pure functions always produce the same output for the same input and have no side effects.
// Pure function function add(a, b) { return a + b; } // Impure function let total = 0; function addToTotal(value) { total += value; return total; }
16. Explain call(), apply(), and bind()
Methods to control 'this' context in function execution.
const person = { name: 'John' }; function greet(greeting) { return `${greeting}, ${this.name}!`; } console.log(greet.call(person, 'Hello')); // Hello, John! console.log(greet.apply(person, ['Hi'])); // Hi, John! const boundGreet = greet.bind(person); console.log(boundGreet('Hey')); // Hey, John!
17. What is the Module Pattern?
The module pattern uses closures to create private and public encapsulation.
const calculator = (function() { let total = 0; return { add: function(x) { total += x; return total; }, getTotal: function() { return total; } }; })();
18. Explain Event Bubbling and Capturing
Events in the DOM bubble up through ancestors and can be captured during the capture phase.
parent.addEventListener('click', function() { console.log('Parent'); }, true); // Capture phase child.addEventListener('click', function() { console.log('Child'); event.stopPropagation(); // Stop bubbling });
19. What is the Proxy Object?
Proxies define custom behavior for basic operations like property lookup and assignment.
const handler = { get: function(target, prop) { return prop in target ? target[prop] : 'Property not found'; } }; const object = { name: 'Test' }; const proxy = new Proxy(object, handler); console.log(proxy.name); // "Test" console.log(proxy.age); // "Property not found"
20. Explain Symbol Type
Symbols are unique and immutable primitive values used as object property keys.
const symbol1 = Symbol('description'); const symbol2 = Symbol('description'); console.log(symbol1 === symbol2); // false const obj = { [symbol1]: 'Value 1', [symbol2]: 'Value 2' }; console.log(obj[symbol1]); // "Value 1"