Top 30 JavaScript Questions with Answers
1. What is `let`, `const`, and `var`?
Solution: `let` and `const` are block-scoped, while `var` is function-scoped. `let` allows
reassignment, `const` does not, and `var` is hoisted without block scope.
2. What is hoisting in JavaScript?
Solution: Hoisting is JavaScript's default behavior of moving declarations to the top of their
containing scope. Only declarations are hoisted, not initializations.
3. Explain closures with an example.
Solution: A closure is when a function retains access to its lexical scope, even when executed
outside of that scope.
Code:
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
const increment = outer();
console.log(increment()); // 1
console.log(increment()); // 2
```
4. What is the difference between `==` and `===`?
Solution: `==` checks for value equality with type coercion, whereas `===` checks for both value and
type equality without coercion.
5. What is an Immediately Invoked Function Expression (IIFE)?
Solution: An IIFE is a function that runs as soon as it is defined.
Code:
Top 30 JavaScript Questions with Answers
(function() {
console.log("IIFE executed!");
})();
```
6. What is the `this` keyword?
Solution: `this` refers to the object that is executing the current function. It can change based on
the context: global, object method, or function.
7. Explain the concept of prototypes.
Solution: Every JavaScript object has a prototype that acts as a template object from which it
inherits properties and methods.
8. What are arrow functions and how do they differ from regular functions?
Solution: Arrow functions are a concise syntax for writing functions. They do not have their own
`this` and are not suitable for use as methods.
Code:
const add = (a, b) => a + b;
```
9. What is event delegation?
Solution: Event delegation is a technique in which you attach a single event listener to a parent
element to handle events for all its child elements.
10. What is the `call()`, `apply()`, and `bind()` methods?
Solution: These methods allow you to set the `this` context of a function. `call()` and `apply()`
invoke functions immediately, while `bind()` returns a new function.
Code:
function greet() {
console.log(`Hello, ${this.name}`);
const person = { name: "John" };
greet.call(person); // Hello, John
Top 30 JavaScript Questions with Answers
```
11. Explain `setTimeout` and `setInterval`.
Solution: `setTimeout` executes a function after a delay, while `setInterval` repeatedly executes a
function at a specified interval.
12. What are promises?
Solution: Promises represent asynchronous operations. They can be in one of three states: pending,
resolved, or rejected.
Code:
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Done!"), 1000);
});
```
13. What is async/await?
Solution: `async/await` is syntax for handling promises more cleanly. An `async` function returns a
promise, and `await` pauses execution until the promise resolves.
14. What is the difference between `map()` and `forEach()`?
Solution: `map()` returns a new array with the results of calling a function on every array element,
while `forEach()` executes the function without returning anything.
15. What are template literals?
Solution: Template literals use backticks (`` ` ``) and allow embedded expressions and multi-line
strings.
Code:
const name = "John";
console.log(`Hello, ${name}`);
```
16. Explain the concept of `null` and `undefined`.
Top 30 JavaScript Questions with Answers
Solution: `null` is an assignment value representing "no value," while `undefined` means a variable
has been declared but has not been assigned a value.
17. What is destructuring?
Solution: Destructuring is a way of unpacking values from arrays or properties from objects.
Code:
const [a, b] = [1, 2];
const { name, age } = { name: "John", age: 25 };
```
18. Explain the spread and rest operators.
Solution: The spread operator (`...`) spreads elements of an array or object, while the rest operator
collects elements into an array.
Code:
const arr = [1, 2, 3];
const newArr = [...arr, 4, 5];
```
19. What is `NaN` and how do you check if a value is `NaN`?
Solution: `NaN` stands for "Not-a-Number". You can check it using `Number.isNaN()` or `isNaN()`.
Code:
console.log(Number.isNaN(NaN)); // true
```
20. Explain what the event loop is.
Solution: The event loop is a mechanism that handles the execution of JavaScript code, allowing
non-blocking I/O operations.
21. What is a JavaScript promise chain?
Solution: A promise chain is a sequence of `.then()` calls that execute asynchronously one after the
other.
Code:
Top 30 JavaScript Questions with Answers
fetchData()
.then(processData)
.then(displayData)
.catch(handleError);
```
22. What is JSON and how do you parse it?
Solution: JSON (JavaScript Object Notation) is a format for data. You use `JSON.parse()` to convert a
JSON string to a JavaScript object and `JSON.stringify()` to convert an object to a JSON string.
23. What is the DOM?
Solution: The Document Object Model (DOM) is an interface that allows scripts to access and
manipulate the content, structure, and style of a webpage.
24. What is `typeof` and how is it used?
Solution: `typeof` is an operator that returns the type of a variable.
Code:
console.log(typeof 42); // "number"
```
25. What are higher-order functions?
Solution: Higher-order functions are functions that take other functions as arguments or return
them.
Code:
const add = (a, b) => a + b;
const operation = (fn, x, y) => fn(x, y);
console.log(operation(add, 5, 3)); // 8
```
Top 30 JavaScript Questions with Answers
26. Explain currying.
Solution: Currying transforms a function with multiple arguments into a series of functions that
each take a single argument.
Code:
const multiply = (x) => (y) => x * y;
console.log(multiply(2)(3)); // 6
```
27. What is memoization?
Solution: Memoization is an optimization technique where results of expensive function calls are
cached.
Code:
const memoizedAdd = (() => {
const cache = {};
return (n) => {
if (n in cache) return cache[n];
console.log('Computing...');
cache[n] = n + 10;
return cache[n];
};
})();
```
28. What is functional programming?
Solution: Functional programming is a paradigm where functions are first-class citizens, promoting
immutability and pure functions.
29. What are JavaScript modules?
Solution: JavaScript modules allow code to be divided into separate files and imported or exported
as needed, enabling better organization.
30. Explain `debounce` and `throttle`.
Top 30 JavaScript Questions with Answers
Solution: `Debounce` delays a function call until a certain time has passed since the last call.
`Throttle` limits a function to run at most once in a specified time period.
Code:
const debounce = (func, delay) => {
let timer;
return function () {
clearTimeout(timer);
timer = setTimeout(() => func.apply(this, arguments), delay);
};
};