Basic JavaScript
1. What is JavaScript? How is it different from Java?
2. What are the data types in JavaScript?
3. Explain the difference between var, let, and const.
4. What is undefined vs null in JavaScript?
5. What is the purpose of isNaN function?
6. What are JavaScript's primitive data types?
7. Explain the difference between == and ===.
8. What are global variables? How are they declared?
9. What is a closure in JavaScript?
10. Explain the use of typeof operator.
11. What is an Immediately Invoked Function Expression (IIFE)?
12. What are template literals? Give an example.
13. How is JavaScript dynamically typed?
14. What is the difference between call(), apply(), and bind()?
15. What is an event in JavaScript?
16. What is event bubbling and event capturing?
17. What are arrow functions? How are they different from regular functions?
18. How does the this keyword behave in JavaScript?
19. What is the difference between undefined and not defined?
20. What is a JavaScript object?
Intermediate JavaScript
21. Explain prototypal inheritance.
22. How does JavaScript handle asynchronous operations?
23. What is the purpose of Promise in JavaScript?
24. What is the difference between for...in and for...of?
25. Explain the concept of "hoisting."
26. What is the event loop in JavaScript?
27. What are JavaScript modules, and how do you use them?
28. What is the difference between function declaration and function expression?
29. What are the different ways to clone an object in JavaScript?
30. Explain JSON.stringify() and JSON.parse().
31. What are Map and Set in JavaScript? How are they different from objects?
32. How does destructuring work in JavaScript?
33. What is the difference between shallow copy and deep copy?
34. What is the purpose of the Symbol type?
35. What is the difference between synchronous and asynchronous code?
36. How do you create and trigger custom events in JavaScript?
37. What is the purpose of the async/await syntax?
38. Explain the concept of currying in JavaScript.
39. What are default parameters in JavaScript functions?
40. How do spread and rest operators work in JavaScript?
DOM Manipulation
41. What is the DOM in JavaScript?
42. How do you select elements in the DOM?
43. What is the difference between innerHTML, innerText, and textContent?
44. How do you create, update, and remove DOM elements?
45. Explain the use of addEventListener.
46. What is the difference between stopPropagation and preventDefault?
47. How do you traverse the DOM using JavaScript?
48. What are dataset attributes in JavaScript?
49. What is the difference between classList.add and className?
50. How do you handle form events in JavaScript?
Advanced JavaScript
51. What is the difference between Object.freeze and Object.seal?
52. Explain the debounce and throttle functions.
53. What are Web Workers in JavaScript?
54. How does the reduce() function work?
55. What is a WeakMap and WeakSet in JavaScript?
56. What is the purpose of Object.create()?
57. How does the garbage collector work in JavaScript?
58. Explain the concept of memoization.
59. How do you handle exceptions in JavaScript?
60. What are dynamic imports in JavaScript?
61. What is the difference between mutable and immutable data?
62. How do JavaScript timers (setTimeout and setInterval) work?
63. Explain the concept of the "Temporal Dead Zone."
64. How does JavaScript handle recursion?
65. What are Proxy objects in JavaScript?
66. What is the use of the Reflect API?
67. What are decorators in JavaScript?
68. How do you optimize JavaScript performance?
69. Explain how event delegation works.
70. What are iterators and generators in JavaScript?
ES6+ Features
71. What is the purpose of let and const introduced in ES6?
72. Explain the concept of destructuring in ES6.
73. What are default function parameters?
74. How do template literals work?
75. What are arrow functions?
76. Explain block-scoping in ES6.
77. What is a Set in ES6?
78. How do you use for...of loop?
79. What is the difference between import and require?
80. What is the use of the Promise.all() method?
81. How do async/await improve readability of asynchronous code?
82. What is the purpose of Promise.race()?
83. Explain Object.entries() and Object.values().
84. How does the spread operator (...) work?
85. What are tagged template literals?
Asynchronous JavaScript
86. What is a callback function?
87. Explain the concept of promises in JavaScript.
88. How do you handle promise chaining?
89. What is the purpose of the fetch() API?
90. What are the differences between fetch and XMLHttpRequest?
91. How does async/await work under the hood?
92. What is the purpose of the Promise.finally() method?
93. What is a microtask in JavaScript?
94. Explain how JavaScript handles single-threaded operations.
95. How do you handle errors in asynchronous code?
JavaScript and the Browser
96. What is the window object in JavaScript?
97. How does localStorage differ from sessionStorage?
98. What is the difference between cookies and localStorage?
99. What is the navigator object?
100. How do you perform DOM manipulation in JavaScript?
101. How do you use the history API in JavaScript?
102. What is the purpose of the location object?
103. How does JavaScript handle browser events?
104. What is the fetch() API used for?
105. What is the difference between synchronous and asynchronous requests?
Interview-Focused
106. Explain the Singleton design pattern in JavaScript.
107. What is functional programming in JavaScript?
108. How would you reverse a string in JavaScript?
109. How can you remove duplicates from an array?
110. Write a function to flatten a nested array.
111. How do you check if a string is a palindrome?
112. Explain how to debounce a function.
113. Write a JavaScript function to find the factorial of a number.
114. How would you find the maximum occurring character in a string?
115. How would you deep clone an object?
116. How do you merge two arrays in JavaScript?
117. How can you shuffle the elements of an array?
118. What is the difference between .map() and .forEach()?
119. How do you implement a custom map() function?
120. Write a function to check if two strings are anagrams.
Miscellaneous
121. What are promises, and why do we need them?
122. Explain the difference between then and catch in promises.
123. What is strict mode in JavaScript?
124. What is tail call optimization?
125. Explain what a polyfill is.
126. What is a transpiler in JavaScript?
127. What are the limitations of JavaScript?
128. How is error handling done in JavaScript?
129. What is the difference between innerHTML and outerHTML?
130. How do you measure performance in JavaScript?
Extra Questions
131. What is AJAX, and how does it work?
132. Explain the concept of reflow and repaint.
133. How do you use the console API effectively?
134. What is a service worker in JavaScript?
135. How does async differ from defer in script tags?
136. What are the stages of the JavaScript parsing process?
137. What is the difference between document.ready and window.onload?
138. How do you debug JavaScript code effectively?
139. What are WebSockets in JavaScript?
140. What is the purpose of the new keyword?
141. What are named exports vs default exports?
142. How does destructuring help in function parameters?
143. What is the eval() function, and why is it discouraged?
144. How do you use Intl for formatting?
145. What is BigInt in JavaScript?
146. How do you handle dates and times in JavaScript?
147. What are JavaScript polyfills? Provide examples.
148. What are the differences between npm and yarn?
149. What is event delegation in JavaScript?
150. Explain lazy loading in JavaScript.
1. What is JavaScript? How is it different from Java?
Answer:
JavaScript is a lightweight, interpreted programming language used primarily to create interactive and
dynamic content on websites. It is often used for client-side scripting but can also be used server-side
with environments like Node.js.
Difference from Java:
• Java: A compiled, statically typed, object-oriented programming language.
• JavaScript: Interpreted, dynamically typed, and primarily used for web development.
JavaScript is not related to Java except for its name.
2. What are the data types in JavaScript?
Answer:
JavaScript has two main categories of data types:
• Primitive Data Types: String, Number, Boolean, Undefined, Null, Symbol, BigInt.
• Non-Primitive (Object) Data Types: Object (including Arrays, Functions, and other objects).
3. Explain the difference between var, let, and const.
Answer:
• var:
o Function-scoped.
o Can be re-declared and updated.
o Hoisted but initialized as undefined.
• let:
o Block-scoped.
o Cannot be re-declared in the same scope.
o Hoisted but not initialized (Temporal Dead Zone applies).
• const:
o Block-scoped.
o Must be initialized at declaration.
o Cannot be reassigned.
4. What is undefined vs null in JavaScript?
Answer:
• undefined:
A variable that has been declared but not initialized. It indicates the absence of a value.
• null:
Represents an explicitly assigned absence of value. It’s an object type.
Example:
javascript
Copy code
let x; // undefined
let y = null; // explicitly no value
5. What is the purpose of is NaN function?
Answer:
The isNaN function checks whether a value is NaN (Not-a-Number). If the value is not a number or
cannot be converted to a number, it returns true.
Example:
javascript
Copy code
isNaN('abc'); // true
isNaN(123); // false
6. What are JavaScript's primitive data types?
Answer:
JavaScript’s primitive data types are:
1. String: Represents text.
2. Number: Represents numeric values (both integers and floating-point).
3. Boolean: Represents true or false.
4. Undefined: Represents a variable without a value.
5. Null: Represents an explicitly empty value.
6. Symbol: Represents unique, immutable values.
7. BigInt: Represents integers larger than 2^53 - 1.
7. Explain the difference between == and ===.
Answer:
• == (Abstract Equality): Compares two values after type coercion.
• === (Strict Equality): Compares both value and type without type coercion.
Example:
javascript
Copy code
5 == '5'; // true (type coercion happens)
5 === '5'; // false (strict comparison, different types)
8. What are global variables? How are they declared?
Answer:
• Global Variables: Variables that are accessible throughout the program (in all scopes).
• Declaration: Declare a variable outside any function or use window object explicitly.
Example:
javascript
Copy code
var globalVar = "I am global"; // Declared globally
window.anotherGlobal = "I am also global"; // Using window
9. What is a closure in JavaScript?
Answer:
A closure is a function that retains access to its outer scope's variables, even after the outer function has
returned.
Example:
javascript
Copy code
function outerFunction() {
let outerVar = "I am outer";
return function innerFunction() {
return outerVar; // innerFunction has access to outerVar
};
const closureFunction = outerFunction();
console.log(closureFunction()); // "I am outer"
10. Explain the use of typeof operator.
Answer:
The typeof operator returns the type of a given variable or value as a string.
Example:
javascript
Copy code
console.log(typeof "Hello"); // "string"
console.log(typeof 42); // "number"
console.log(typeof {}); // "object"
console.log(typeof null); // "object" (a known JavaScript quirk)
console.log(typeof undefined); // "undefined"
11. What is an Immediately Invoked Function Expression (IIFE)?
Answer:
An IIFE is a function that is executed immediately after it is defined. It is commonly used to create a
private scope and avoid polluting the global namespace.
Example:
javascript
Copy code
(function () {
console.log("IIFE executed!");
})();
12. What are template literals? Give an example.
Answer:
Template literals are string literals enclosed in backticks (`) and allow embedded expressions using the
${expression} syntax. They support multi-line strings and string interpolation.
Example:
javascript
Copy code
const name = "John";
const greeting = `Hello, ${name}! Welcome to JavaScript.`;
console.log(greeting); // "Hello, John! Welcome to JavaScript."
13. How is JavaScript dynamically typed?
Answer:
JavaScript is dynamically typed, meaning variables are not bound to a specific data type. A variable’s type
can change at runtime based on the value assigned to it.
Example:
javascript
Copy code
let x = 10; // x is a number
x = "Hello"; // x is now a string
x = true; // x is now a boolean
14. What is the difference between call(), apply(), and bind()?
Answer:
• call(): Invokes a function, allowing you to pass arguments individually.
• apply(): Similar to call(), but arguments are passed as an array.
• bind(): Returns a new function with a specific this value and optional arguments pre-set, without
invoking it immediately.
Example:
javascript
Copy code
const obj = { name: "John" };
function greet(greeting, punctuation) {
console.log(`${greeting}, ${this.name}${punctuation}`);
greet.call(obj, "Hello", "!"); // Hello, John!
greet.apply(obj, ["Hi", "."]); // Hi, John.
const boundGreet = greet.bind(obj, "Hey");
boundGreet("?"); // Hey, John?
15. What is an event in JavaScript?
Answer:
An event is an action or occurrence detected by the browser, such as a user clicking a button, moving the
mouse, or typing on the keyboard. Events allow developers to define responses to user interactions.
Example:
javascript
Copy code
document.querySelector("button").addEventListener("click", () => {
console.log("Button clicked!");
});
16. What is event bubbling and event capturing?
Answer:
• Event Bubbling: Events propagate from the target element to its ancestors (inner to outer
elements).
• Event Capturing: Events propagate from the outermost ancestor to the target element (outer to
inner elements).
Example:
javascript
Copy code
document.querySelector("#parent").addEventListener("click", () => {
console.log("Parent clicked! (bubbling)");
}, false); // Bubbling phase
document.querySelector("#child").addEventListener("click", () => {
console.log("Child clicked! (capturing)");
}, true); // Capturing phase
17. What are arrow functions? How are they different from regular functions?
Answer:
Arrow functions are a concise syntax for writing functions introduced in ES6. They do not have their own
this context, making them useful in scenarios where this should refer to the enclosing scope.
Differences:
• No this binding.
• Cannot be used as constructors.
• Implicit return for single-expression functions.
Example:
javascript
Copy code
const regularFunction = function () {
console.log(this); // Dynamic binding of `this`
};
const arrowFunction = () => {
console.log(this); // Lexical `this`, inherits from surrounding scope
};
18. How does the this keyword behave in JavaScript?
Answer:
this refers to the object that is executing the current function.
• In the global context, this refers to the window object (in browsers).
• Inside an object method, this refers to the object.
• In an arrow function, this refers to the enclosing scope.
• In strict mode, this is undefined in the global scope.
Example:
javascript
Copy code
function globalThis() {
console.log(this); // In browsers: window object
const obj = {
method: function () {
console.log(this); // Refers to obj
},
};
obj.method();
19. What is the difference between undefined and "not defined"?
Answer:
• undefined: A variable is declared but has no assigned value.
• "Not defined": A variable has not been declared in the code.
Example:
javascript
Copy code
let x;
console.log(x); // undefined
console.log(y); // ReferenceError: y is not defined
20. What is a JavaScript object?
Answer:
An object in JavaScript is a collection of key-value pairs, where keys are strings (or Symbols) and values
can be any data type, including functions.
Example:
javascript
Copy code
const obj = {
name: "John",
age: 30,
greet: function () {
console.log("Hello, " + this.name);
},
};
console.log(obj.name); // John
obj.greet(); // Hello, John
Intermediate JavaScript Questions and Answers
21. Explain prototypal inheritance.
Answer:
Prototypal inheritance allows objects to inherit properties and methods from another object. Every
JavaScript object has an internal property called [[Prototype]], which links it to another object.
Example:
javascript
Copy code
const parent = { greet: function () { console.log("Hello!"); } };
const child = Object.create(parent);
child.greet(); // "Hello!" (inherits from parent)
22. How does JavaScript handle asynchronous operations?
Answer:
JavaScript handles asynchronous operations using:
• Callbacks: A function passed as an argument and executed after an operation.
• Promises: Represent the eventual completion or failure of an asynchronous task.
• Async/Await: Simplifies working with promises for writing asynchronous code in a synchronous
style.
• Event Loop: Ensures asynchronous code runs after the current stack of code execution
completes.
23. What is the purpose of Promise in JavaScript?
Answer:
A Promise represents a value that may be available now, in the future, or never. It is used to handle
asynchronous operations more effectively.
States of a Promise:
1. Pending: Initial state.
2. Fulfilled: Operation completed successfully.
3. Rejected: Operation failed.
Example:
javascript
Copy code
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Success"), 1000);
});
promise.then(console.log).catch(console.error);
24. What is the difference between for...in and for...of?
Answer:
• for...in: Iterates over the keys of an object (enumerable properties).
• for...of: Iterates over the values of an iterable (arrays, strings, etc.).
Example:
javascript
Copy code
const obj = { a: 1, b: 2 };
for (let key in obj) {
console.log(key); // "a", "b"
const arr = [1, 2, 3];
for (let value of arr) {
console.log(value); // 1, 2, 3
25. Explain the concept of "hoisting."
Answer:
Hoisting is JavaScript's behavior of moving variable and function declarations to the top of their scope
before code execution.
• Variables declared with var are hoisted but initialized as undefined.
• Functions are hoisted with their definition.
Example:
javascript
Copy code
console.log(a); // undefined
var a = 10;
greet(); // "Hello!"
function greet() {
console.log("Hello!");
26. What is the event loop in JavaScript?
Answer:
The event loop is a mechanism that allows JavaScript to perform non-blocking operations by offloading
tasks (like I/O operations) to the browser and executing them once the call stack is empty.
Steps:
1. JavaScript executes code in the call stack.
2. Asynchronous tasks are moved to the task queue or microtask queue.
3. The event loop checks if the call stack is empty, then executes tasks from the queues.
27. What are JavaScript modules, and how do you use them?
Answer:
JavaScript modules allow you to divide code into reusable pieces using export and import.
Usage:
1. Exporting: Define the module's public parts.
javascript
Copy code
// module.js
export const greet = () => console.log("Hello!");
export default function () { console.log("Default export"); }
2. Importing: Use the exported parts in another file.
javascript
Copy code
import { greet } from './module.js';
import defaultFunc from './module.js';
greet(); // "Hello!"
defaultFunc(); // "Default export"
28. What is the difference between function declaration and function expression?
Answer:
• Function Declaration: A named function that is hoisted.
javascript
Copy code
function greet() {
console.log("Hello!");
• Function Expression: A function assigned to a variable. Not hoisted.
javascript
Copy code
const greet = function () {
console.log("Hello!");
};
Example of the difference:
javascript
Copy code
greet(); // Works
function greet() {
console.log("Hello!");
greetExpression(); // Error: greetExpression is not defined
const greetExpression = function () {
console.log("Hi!");
};
29. What are the different ways to clone an object in JavaScript?
Answer:
1. Using Object.assign():
javascript
Copy code
const obj = { a: 1, b: 2 };
const clone = Object.assign({}, obj);
2. Using Spread Operator (...):
javascript
Copy code
const clone = { ...obj };
3. Using JSON methods (Deep Copy):
javascript
Copy code
const deepClone = JSON.parse(JSON.stringify(obj));
4. Using structured cloning (structuredClone()):
javascript
Copy code
const deepClone = structuredClone(obj);
30. Explain JSON.stringify() and JSON.parse().
Answer:
• JSON.stringify(): Converts a JavaScript object or value into a JSON string.
javascript
Copy code
const obj = { a: 1, b: 2 };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // '{"a":1,"b":2}'
• JSON.parse(): Parses a JSON string into a JavaScript object.
javascript
Copy code
const jsonObject = JSON.parse('{"a":1,"b":2}');
console.log(jsonObject); // { a: 1, b: 2 }
31. What are Map and Set in JavaScript? How are they different from objects?
Answer:
• Map: A collection of key-value pairs where keys can be any type (object, primitive, etc.).
• Set: A collection of unique values.
Differences from Objects:
1. Map:
o Keys can be any data type.
o Iterates in insertion order.
o Size can be retrieved using map.size.
2. Set:
o Stores unique values (no duplicates).
o Size can be retrieved using set.size.
o Useful for filtering unique elements.
Examples:
javascript
Copy code
// Map example
const map = new Map();
map.set('a', 1);
map.set(2, 'b');
console.log(map.get(2)); // "b"
// Set example
const set = new Set([1, 2, 2, 3]);
console.log(set); // Set { 1, 2, 3 }
32. How does destructuring work in JavaScript?
Answer:
Destructuring allows you to extract values from arrays or properties from objects and assign them to
variables.
Examples:
javascript
Copy code
// Array destructuring
const [a, b] = [1, 2];
console.log(a, b); // 1, 2
// Object destructuring
const obj = { x: 10, y: 20 };
const { x, y } = obj;
console.log(x, y); // 10, 20
// Nested destructuring
const nestedObj = { outer: { inner: 42 } };
const { outer: { inner } } = nestedObj;
console.log(inner); // 42
33. What is the difference between shallow copy and deep copy?
Answer:
• Shallow Copy: Copies the first level of properties. Nested objects or arrays are still referenced.
Example:
javascript
Copy code
const obj = { a: 1, b: { c: 2 } };
const shallow = { ...obj };
shallow.b.c = 3;
console.log(obj.b.c); // 3 (referenced)
• Deep Copy: Copies all levels, creating a fully independent copy.
Example:
javascript
Copy code
const deep = JSON.parse(JSON.stringify(obj));
deep.b.c = 4;
console.log(obj.b.c); // 2 (independent)
34. What is the purpose of the Symbol type?
Answer:
Symbol is a unique and immutable primitive data type. It’s used to create unique property keys to avoid
name collisions.
Example:
javascript
Copy code
const sym1 = Symbol('id');
const sym2 = Symbol('id');
console.log(sym1 === sym2); // false (unique symbols)
const obj = {};
obj[sym1] = 'value1';
console.log(obj[sym1]); // "value1"
35. What is the difference between synchronous and asynchronous code?
Answer:
• Synchronous Code: Executes line by line, blocking subsequent code until the current operation
completes.
• Asynchronous Code: Allows other operations to execute while waiting for a task to complete.
Example:
javascript
Copy code
// Synchronous
console.log('Start');
for (let i = 0; i < 1e6; i++); // Blocks
console.log('End');
// Asynchronous
console.log('Start');
setTimeout(() => console.log('Middle'), 1000); // Non-blocking
console.log('End');
36. How do you create and trigger custom events in JavaScript?
Answer:
Custom events are created using the CustomEvent constructor and triggered using dispatchEvent.
Example:
javascript
Copy code
const customEvent = new CustomEvent('myEvent', { detail: { message: 'Hello!' } });
document.addEventListener('myEvent', (e) => {
console.log(e.detail.message); // "Hello!"
});
document.dispatchEvent(customEvent);
37. What is the purpose of the async/await syntax?
Answer:
async/await simplifies working with Promises, making asynchronous code look and behave like
synchronous code.
• async: Marks a function as asynchronous, returning a Promise.
• await: Pauses execution until the Promise resolves.
Example:
javascript
Copy code
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
fetchData();
38. Explain the concept of currying in JavaScript.
Answer:
Currying is a technique of transforming a function with multiple arguments into a sequence of functions,
each taking a single argument.
Example:
javascript
Copy code
function add(a) {
return function (b) {
return a + b;
};
}
const add5 = add(5);
console.log(add5(3)); // 8
39. What are default parameters in JavaScript functions?
Answer:
Default parameters allow you to set default values for function arguments if no value is provided.
Example:
javascript
Copy code
function greet(name = 'Guest') {
console.log(`Hello, ${name}!`);
greet(); // "Hello, Guest!"
greet('John'); // "Hello, John!"
40. How do spread and rest operators work in JavaScript?
Answer:
• Spread Operator (...): Expands an array or object into individual elements.
Example:
javascript
Copy code
const arr = [1, 2, 3];
console.log(...arr); // 1 2 3
const obj = { a: 1, b: 2 };
const newObj = { ...obj, c: 3 };
console.log(newObj); // { a: 1, b: 2, c: 3 }
• Rest Operator (...): Gathers the rest of the values into an array or object.
Example:
javascript
Copy code
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
console.log(sum(1, 2, 3)); // 6
OM Manipulation Questions and Answers
41. What is the DOM in JavaScript?
Answer:
The Document Object Model (DOM) is a programming interface for web documents. It represents the
structure of a webpage as a tree of objects, allowing JavaScript to manipulate HTML and CSS
dynamically.
Example:
javascript
Copy code
document.title = "New Page Title"; // Updates the document title
42. How do you select elements in the DOM?
Answer:
You can use the following methods to select elements:
• getElementById: Selects an element by its ID.
javascript
Copy code
const element = document.getElementById('myId');
• querySelector: Selects the first element matching a CSS selector.
javascript
Copy code
const element = document.querySelector('.myClass');
• querySelectorAll: Selects all elements matching a CSS selector.
javascript
Copy code
const elements = document.querySelectorAll('.myClass');
• getElementsByClassName and getElementsByTagName: Select by class name or tag name.
43. What is the difference between innerHTML, innerText, and textContent?
Answer:
• innerHTML: Retrieves or sets the HTML content inside an element (including tags).
javascript
Copy code
element.innerHTML = '<strong>Bold Text</strong>';
• innerText: Retrieves or sets the visible text inside an element, considering CSS styles (e.g.,
display: none is excluded).
javascript
Copy code
element.innerText = 'Visible Text';
• textContent: Retrieves or sets the raw text inside an element (ignores CSS styling).
javascript
Copy code
element.textContent = 'Raw Text';
44. How do you create, update, and remove DOM elements?
Answer:
• Create: Use document.createElement and append it.
javascript
Copy code
const newElement = document.createElement('div');
newElement.textContent = 'Hello!';
document.body.appendChild(newElement);
• Update: Modify properties like textContent or style.
javascript
Copy code
newElement.style.color = 'blue';
• Remove: Use removeChild or remove.
javascript
Copy code
newElement.remove(); // Removes the element
45. Explain the use of addEventListener.
Answer:
addEventListener is used to attach an event listener to an element. It allows multiple listeners for the
same event and supports additional options like capture.
Syntax:
javascript
Copy code
element.addEventListener('eventType', callback, options);
Example:
javascript
Copy code
button.addEventListener('click', () => {
console.log('Button clicked!');
});
46. What is the difference between stopPropagation and preventDefault?
Answer:
• stopPropagation: Prevents the event from propagating to parent elements in the DOM
hierarchy.
javascript
Copy code
element.addEventListener('click', (event) => {
event.stopPropagation();
});
• preventDefault: Prevents the default action associated with the event (e.g., stopping form
submission or link navigation).
javascript
Copy code
element.addEventListener('click', (event) => {
event.preventDefault();
});
47. How do you traverse the DOM using JavaScript?
Answer:
You can traverse using properties like:
• parentNode: Access the parent element.
• childNodes / children: Access child elements.
• nextSibling / nextElementSibling: Access the next sibling.
• previousSibling / previousElementSibling: Access the previous sibling.
Example:
javascript
Copy code
const parent = element.parentNode;
const children = element.children;
const next = element.nextElementSibling;
48. What are dataset attributes in JavaScript?
Answer:
Dataset attributes allow you to store custom data in HTML elements using data-* attributes. Access
them using element.dataset.
Example:
html
Copy code
<div id="myDiv" data-user-id="123" data-role="admin"></div>
javascript
Copy code
const div = document.getElementById('myDiv');
console.log(div.dataset.userId); // "123"
console.log(div.dataset.role); // "admin"
49. What is the difference between classList.add and className?
Answer:
• classList.add: Adds a single class or multiple classes to an element without affecting existing
classes.
javascript
Copy code
element.classList.add('new-class');
• className: Overwrites all existing classes with the new value.
javascript
Copy code
element.className = 'new-class'; // Removes all previous classes
50. How do you handle form events in JavaScript?
Answer:
Form events like submit, change, and input can be handled using addEventListener.
Example:
javascript
Copy code
const form = document.getElementById('myForm');
// Handle form submission
form.addEventListener('submit', (event) => {
event.preventDefault(); // Prevent page refresh
console.log('Form submitted!');
});
// Handle input changes
form.addEventListener('input', (event) => {
console.log(event.target.value); // Log input value
});
51. What is the difference between Object.freeze and Object.seal?
Answer:
• Object.freeze:
o Prevents adding, removing, or modifying properties of an object.
o Makes the object immutable.
javascript
Copy code
const obj = Object.freeze({ a: 1 });
obj.a = 2; // Does nothing in strict mode
• Object.seal:
o Prevents adding or removing properties but allows modifying existing ones.
javascript
Copy code
const obj = Object.seal({ a: 1 });
obj.a = 2; // Allowed
delete obj.a; // Does nothing
52. Explain the debounce and throttle functions.
Answer:
• Debounce: Limits the rate at which a function is executed. It delays execution until after a
specified time since the last call. Useful for search input or resize events.
javascript
Copy code
function debounce(func, delay) {
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), delay);
};
• Throttle: Ensures a function is called at most once every specified interval, regardless of how
often it's triggered. Useful for scroll or mousemove events.
javascript
Copy code
function throttle(func, limit) {
let lastCall = 0;
return function (...args) {
const now = Date.now();
if (now - lastCall >= limit) {
lastCall = now;
func.apply(this, args);
};
53. What are Web Workers in JavaScript?
Answer:
Web Workers allow running JavaScript code in the background, in a separate thread, to keep the main
thread responsive.
• Created using the Worker API.
• Used for heavy computations or background tasks.
Example:
javascript
Copy code
// worker.js
self.onmessage = (e) => {
const result = e.data * 2;
self.postMessage(result);
};
// main.js
const worker = new Worker('worker.js');
worker.onmessage = (e) => console.log(e.data);
worker.postMessage(5); // Sends 5 to the worker
54. How does the reduce() function work?
Answer:
reduce() applies a function to an accumulator and each array element, reducing the array to a single
value.
Syntax:
javascript
Copy code
array.reduce(callback, initialValue);
Example:
javascript
Copy code
const nums = [1, 2, 3, 4];
const sum = nums.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 10
55. What is a WeakMap and WeakSet in JavaScript?
Answer:
• WeakMap: A map where keys are objects, and they are weakly referenced, allowing garbage
collection.
• WeakSet: A set of objects with weak references.
• They are not iterable.
Example:
javascript
Copy code
let obj = { key: 'value' };
const weakMap = new WeakMap();
weakMap.set(obj, 'info');
obj = null; // Object can be garbage collected
const weakSet = new WeakSet();
weakSet.add({ a: 1 }); // Only stores objects
56. What is the purpose of Object.create()?
Answer:
Object.create() creates a new object with the specified prototype object and optional properties.
Example:
javascript
Copy code
const parent = { greet: () => console.log('Hello') };
const child = Object.create(parent);
child.greet(); // "Hello"
console.log(Object.getPrototypeOf(child) === parent); // true
57. How does the garbage collector work in JavaScript?
Answer:
The garbage collector automatically removes objects from memory that are no longer reachable.
• Mark-and-Sweep Algorithm: Identifies objects that are not reachable from the root (e.g., global
variables) and frees their memory.
• Circular references are handled correctly as long as no external reference exists.
Example:
javascript
Copy code
let obj = { a: 1 };
obj = null; // Eligible for garbage collection
58. Explain the concept of memoization.
Answer:
Memoization is an optimization technique that caches the results of expensive function calls to avoid
redundant computations.
Example:
javascript
Copy code
function memoize(func) {
const cache = {};
return function (key) {
if (key in cache) return cache[key];
const result = func(key);
cache[key] = result;
return result;
};
}
const factorial = memoize((n) => (n <= 1 ? 1 : n * factorial(n - 1)));
console.log(factorial(5)); // Cached result for subsequent calls
59. How do you handle exceptions in JavaScript?
Answer:
Exceptions are handled using try...catch blocks.
• throw: Used to throw an error.
• finally: Executes code regardless of whether an exception occurs.
Example:
javascript
Copy code
try {
throw new Error('An error occurred');
} catch (error) {
console.error(error.message);
} finally {
console.log('Execution complete');
60. What are dynamic imports in JavaScript?
Answer:
Dynamic imports allow importing modules at runtime using the import() function. This is useful for code
splitting and lazy loading.
Example:
javascript
Copy code
import('./module.js')
.then((module) => {
module.default(); // Call the default export
})
.catch((error) => console.error(error));
61. What is the difference between mutable and immutable data?
Answer:
• Mutable Data: Can be changed after creation (e.g., arrays, objects).
javascript
Copy code
const arr = [1, 2];
arr.push(3); // Mutates the array
console.log(arr); // [1, 2, 3]
• Immutable Data: Cannot be changed after creation. Any "modification" creates a new value
(e.g., strings, numbers).
javascript
Copy code
const str = "hello";
const newStr = str + " world"; // Creates a new string
console.log(newStr); // "hello world"
62. How do JavaScript timers (setTimeout and setInterval) work?
Answer:
• setTimeout: Executes a function after a specified delay (one-time execution).
javascript
Copy code
setTimeout(() => console.log("Executed after 2 seconds"), 2000);
• setInterval: Executes a function repeatedly at specified intervals.
javascript
Copy code
const id = setInterval(() => console.log("Repeating every second"), 1000);
clearInterval(id); // Stops the interval
Timers rely on the event loop, where the callback is queued after the delay.
63. Explain the concept of the "Temporal Dead Zone."
Answer:
The Temporal Dead Zone (TDZ) refers to the time between entering a scope and declaring a variable
with let or const. During this period, accessing the variable results in a ReferenceError.
Example:
javascript
Copy code
console.log(x); // ReferenceError
let x = 10; // TDZ ends here
64. How does JavaScript handle recursion?
Answer:
Recursion is a function calling itself until a base condition is met. JavaScript uses the call stack to manage
recursive calls.
Example:
javascript
Copy code
function factorial(n) {
if (n <= 1) return 1; // Base case
return n * factorial(n - 1); // Recursive call
console.log(factorial(5)); // 120
Excessive recursion can lead to a stack overflow.
65. What are Proxy objects in JavaScript?
Answer:
A Proxy allows customization of operations on an object (e.g., property access, assignment). It is created
using the Proxy constructor.
Example:
javascript
Copy code
const handler = {
get: (target, prop) => (prop in target ? target[prop] : `No such property`),
};
const obj = new Proxy({ a: 1 }, handler);
console.log(obj.a); // 1
console.log(obj.b); // "No such property"
66. What is the use of the Reflect API?
Answer:
The Reflect API provides methods for performing operations on objects, similar to those used with Proxy
handlers.
Example:
javascript
Copy code
const obj = { a: 1 };
Reflect.set(obj, 'b', 2); // Adds a new property
console.log(Reflect.get(obj, 'b')); // 2
Benefits:
• Simplifies Proxy handlers.
• Avoids using lower-level operations like Object.defineProperty.
67. What are decorators in JavaScript?
Answer:
Decorators are special functions used to modify or enhance classes and their methods. They are part of
the proposed ES decorators feature.
Example (Using a decorator library):
javascript
Copy code
function readonly(target, key, descriptor) {
descriptor.writable = false;
return descriptor;
class Example {
@readonly
sayHello() {
return "Hello!";
Here, @readonly makes the sayHello method immutable.
68. How do you optimize JavaScript performance?
Answer:
• Reduce DOM operations: Minimize reflows and repaints.
• Debounce and throttle: Optimize event handling.
• Use Web Workers: For heavy computations.
• Code splitting: Load only required JavaScript using dynamic imports.
• Avoid memory leaks: Clear unused references and use WeakMap/WeakSet where applicable.
• Efficient loops: Use native array methods like map and reduce instead of for loops when
applicable.
69. Explain how event delegation works.
Answer:
Event delegation is a technique where a single event listener is attached to a parent element to handle
events for its child elements. It relies on event bubbling.
Example:
javascript
Copy code
document.getElementById('parent').addEventListener('click', (event) => {
if (event.target.tagName === 'BUTTON') {
console.log(`Button ${event.target.textContent} clicked`);
});
Advantages:
• Fewer event listeners.
• Dynamically added elements are handled automatically.
70. What are iterators and generators in JavaScript?
Answer:
• Iterators: Objects that implement the next() method, returning { value, done } pairs.
Example:
javascript
Copy code
const iterator = [1, 2, 3][Symbol.iterator]();
console.log(iterator.next()); // { value: 1, done: false }
• Generators: Special functions defined with function* that can pause and resume execution using
yield.
Example:
javascript
Copy code
function* generator() {
yield 1;
yield 2;
yield 3;
}
const gen = generator();
console.log(gen.next()); // { value: 1, done: false }
Generators simplify working with custom iterators.
ES6+ Features Questions and Answers
71. What is the purpose of let and const introduced in ES6?
Answer:
• let:
o Declares block-scoped variables.
o Allows reassignment.
javascript
Copy code
let x = 10;
x = 20; // Allowed
• const:
o Declares block-scoped constants.
o Reassignment is not allowed.
javascript
Copy code
const y = 10;
y = 20; // Error
72. Explain the concept of destructuring in ES6.
Answer:
Destructuring simplifies extracting values from arrays or properties from objects into variables.
Example (Array Destructuring):
javascript
Copy code
const [a, b] = [1, 2];
console.log(a, b); // 1, 2
Example (Object Destructuring):
javascript
Copy code
const obj = { x: 10, y: 20 };
const { x, y } = obj;
console.log(x, y); // 10, 20
73. What are default function parameters?
Answer:
Default parameters allow assigning default values to function arguments if no value or undefined is
provided.
Example:
javascript
Copy code
function greet(name = "Guest") {
return `Hello, ${name}`;
console.log(greet()); // "Hello, Guest"
74. How do template literals work?
Answer:
Template literals provide an easier way to create strings, supporting multi-line strings and embedding
expressions.
Syntax: Use backticks ` instead of quotes.
javascript
Copy code
const name = "John";
const greeting = `Hello, ${name}!`; // Embedding expressions
console.log(greeting); // "Hello, John!"
75. What are arrow functions?
Answer:
Arrow functions are a concise syntax for defining functions. They do not bind their own this context,
making them useful in callbacks.
Syntax:
javascript
Copy code
const add = (a, b) => a + b; // Implicit return
console.log(add(2, 3)); // 5
Key Points:
• Shorter syntax.
• Do not have their own this.
76. Explain block-scoping in ES6.
Answer:
Variables declared with let and const are block-scoped, meaning they are only accessible within the
block {} in which they are defined.
Example:
javascript
Copy code
let x = 10;
const y = 20;
console.log(x, y); // 10, 20
// console.log(x, y); // Error: x and y are not defined
77. What is a Set in ES6?
Answer:
A Set is a collection of unique values. It does not allow duplicate entries.
Example:
javascript
Copy code
const mySet = new Set([1, 2, 2, 3]);
console.log(mySet); // Set { 1, 2, 3 }
mySet.add(4);
console.log(mySet.has(4)); // true
78. How do you use for...of loop?
Answer:
for...of iterates over iterable objects like arrays, strings, maps, and sets.
Example (Array):
javascript
Copy code
const arr = [1, 2, 3];
for (const num of arr) {
console.log(num); // 1, 2, 3
Example (String):
javascript
Copy code
for (const char of "hello") {
console.log(char); // h, e, l, l, o
79. What is the difference between import and require?
Answer:
Feature import require
Syntax ES6 modules CommonJS modules
Static/Dynamic Statically loaded Can be dynamic
Usage import { a } const a = require()
Example (import):
javascript
Copy code
import { func } from './module.js';
func();
Example (require):
javascript
Copy code
const func = require('./module');
func();
80. What is the use of the Promise.all() method?
Answer:
Promise.all() runs multiple promises in parallel and resolves when all promises are resolved. If one
promise rejects, it rejects immediately.
Syntax:
javascript
Copy code
Promise.all([promise1, promise2, ...]).then((results) => {
console.log(results);
});
Example:
javascript
Copy code
const p1 = Promise.resolve(10);
const p2 = Promise.resolve(20);
Promise.all([p1, p2]).then(([result1, result2]) => {
console.log(result1, result2); // 10, 20
});
81. How do async/await improve readability of asynchronous code?
Answer:
async/await provide a more synchronous-like structure to asynchronous code, making it easier to read
and understand compared to traditional promise chains (.then(), .catch()).
• async: Declares a function that returns a promise. Inside this function, you can use await.
• await: Pauses the execution of the function until the promise resolves or rejects.
Example:
Without async/await:
javascript
Copy code
fetchData().then(data => {
console.log(data);
}).catch(error => {
console.log(error);
});
With async/await:
javascript
Copy code
async function fetchDataAsync() {
try {
const data = await fetchData();
console.log(data);
} catch (error) {
console.log(error);
}
}
Using async/await makes asynchronous code look like synchronous code, improving readability.
82. What is the purpose of Promise.race()?
Answer:
Promise.race() accepts an iterable of promises and resolves as soon as the first promise resolves or
rejects. It "races" the promises and returns the result of the first one to settle.
Example:
javascript
Copy code
const p1 = new Promise((resolve, reject) => setTimeout(resolve, 100, 'First'));
const p2 = new Promise((resolve, reject) => setTimeout(resolve, 200, 'Second'));
Promise.race([p1, p2]).then(result => console.log(result)); // "First"
In this example, Promise.race() resolves as soon as p1 resolves, even though p2 takes longer.
83. Explain Object.entries() and Object.values().
Answer:
• Object.entries(): Converts an object's properties into an array of [key, value] pairs. Example:
javascript
Copy code
const obj = { a: 1, b: 2 };
const entries = Object.entries(obj); // [['a', 1], ['b', 2]]
• Object.values(): Returns an array of the object's property values. Example:
javascript
Copy code
const obj = { a: 1, b: 2 };
const values = Object.values(obj); // [1, 2]
84. How does the spread operator (...) work?
Answer:
The spread operator (...) can be used to unpack elements from arrays or objects. It can be used in
function calls, object literals, or array literals to copy, merge, or pass individual elements.
• Array Example:
javascript
Copy code
const arr = [1, 2, 3];
const newArr = [...arr, 4, 5]; // [1, 2, 3, 4, 5]
• Object Example:
javascript
Copy code
const obj = { a: 1, b: 2 };
const newObj = { ...obj, c: 3 }; // { a: 1, b: 2, c: 3 }
The spread operator can also be used to pass individual elements of an array as arguments to a function.
85. What are tagged template literals?
Answer:
Tagged template literals allow you to customize how template literals are processed. A tag function is
used to process the template literal before returning a final result.
Example:
javascript
Copy code
function highlight(strings, ...values) {
let result = '';
strings.forEach((string, index) => {
result += string + (values[index] ? `<b>${values[index]}</b>` : '');
});
return result;
}
const name = 'Alice';
const greeting = highlight`Hello, ${name}! Welcome.`;
console.log(greeting); // "Hello, <b>Alice</b>! Welcome."
In this example, the highlight function processes the template literal and wraps the variable name with
<b> tags.
Asynchronous JavaScript Questions and Answers
86. What is a callback function?
Answer:
A callback function is a function passed as an argument to another function, which is then executed at a
later time. It is typically used for asynchronous operations to handle results once the operation
completes.
Example:
javascript
Copy code
function fetchData(callback) {
setTimeout(() => {
callback('Data received');
}, 1000);
fetchData((data) => {
console.log(data); // "Data received"
});
87. Explain the concept of promises in JavaScript.
Answer:
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation. A
promise can be in one of three states:
• Pending: The initial state, before the operation completes.
• Resolved (Fulfilled): The operation completed successfully.
• Rejected: The operation failed.
Example:
javascript
Copy code
const myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Operation succeeded");
} else {
reject("Operation failed");
});
myPromise.then(result => console.log(result)).catch(error => console.log(error));
88. How do you handle promise chaining?
Answer:
Promise chaining allows multiple asynchronous operations to be executed one after the other. Each
.then() in the chain returns a new promise.
Example:
javascript
Copy code
fetchData()
.then(data => {
console.log(data); // "Data fetched"
return processData(data);
})
.then(processedData => {
console.log(processedData); // "Data processed"
return saveData(processedData);
})
.then(() => {
console.log("Data saved");
})
.catch(error => {
console.log("Error:", error);
});
Each .then() processes the data from the previous one, and if any promise is rejected, the .catch() block
will handle the error.
89. What is the purpose of the fetch() API?
Answer:
The fetch() API is a modern way to make HTTP requests (GET, POST, etc.) in JavaScript. It returns a
Promise that resolves to the Response object representing the response to the request.
Example:
javascript
Copy code
fetch('https://api.example.com/data')
.then(response => response.json()) // Parse JSON response
.then(data => console.log(data)) // Handle the data
.catch(error => console.log(error)); // Handle errors
90. What are the differences between fetch and XMLHttpRequest?
Answer:
• fetch:
o Returns a Promise, making it easier to work with asynchronous code.
o Supports more modern features such as async/await and JSON parsing.
o More readable syntax for handling requests and responses.
• XMLHttpRequest:
o Older and more complex API.
o Does not use Promises, requiring callback functions for asynchronous handling.
o More verbose and difficult to handle multiple operations.
Example (fetch):
javascript
Copy code
fetch('/data')
.then(response => response.json())
.then(data => console.log(data));
Example (XMLHttpRequest):
javascript
Copy code
const xhr = new XMLHttpRequest();
xhr.open('GET', '/data', true);
xhr.onload = () => {
if (xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
};
xhr.send();
91. How does async/await work under the hood?
Answer:
Under the hood, async/await works with Promises. When an async function is called, it returns a
Promise. Inside an async function, when the await keyword is used, it pauses the function's execution
until the Promise resolves or rejects, and then continues with the resolved value or throws an error if
rejected.
1. The async function is essentially a wrapper around a promise.
2. await pauses the function execution and waits for the Promise to resolve.
3. The resolved value is returned and execution continues after the await.
Example:
javascript
Copy code
async function getData() {
const data = await fetch('https://api.example.com');
return data.json();
The async function is equivalent to the following with promises:
javascript
Copy code
function getData() {
return fetch('https://api.example.com').then(response => response.json());
92. What is the purpose of the Promise.finally() method?
Answer:
The finally() method is used to execute code after a promise has been resolved or rejected, regardless of
the outcome. It is useful for cleanup tasks, like closing connections or hiding loading indicators, after the
promise operation.
Example:
javascript
Copy code
fetch('https://api.example.com')
.then(response => response.json())
.catch(error => console.log(error))
.finally(() => console.log('Request completed')); // Always runs
93. What is a microtask in JavaScript?
Answer:
A microtask is a task that is queued to be executed after the currently executing script and before the
rendering phase (e.g., DOM updates). Microtasks are primarily used for promise handlers and
queueMicrotask().
Microtasks are handled in the following order:
1. The current script execution finishes.
2. All microtasks are executed (e.g., .then(), .catch(), Promise.resolve()).
3. The event loop proceeds to rendering.
94. Explain how JavaScript handles single-threaded operations.
Answer:
JavaScript operates on a single thread by using the event loop. The event loop processes events and
executes code in a queue, ensuring that only one task is processed at a time.
• JavaScript code runs synchronously in the call stack.
• Asynchronous operations (like setTimeout, fetch, and promises) are pushed into the event
queue.
• The event loop checks the call stack and moves tasks from the event queue to the stack when it's
empty.
95. How do you handle errors in asynchronous code?
Answer:
Errors in asynchronous code can be handled using:
• try...catch (with async/await):
javascript
Copy code
async function fetchData() {
try {
const response = await fetch('https://api.example.com');
const data = await response.json();
} catch (error) {
console.log('Error:', error);
}
}
• catch() (with Promises):
javascript
Copy code
fetch('https://api.example.com')
.then(response => response.json())
.catch(error => console.log('Error:', error));
Both methods ensure that errors from failed promises or rejected async functions can be handled
gracefully.
JavaScript and the Browser Questions and Answers
96. What is the window object in JavaScript?
Answer:
The window object represents the global environment in a web browser. It is the top-level object in the
browser's JavaScript execution environment and provides methods and properties for interacting with
the browser. It includes functions for manipulating the DOM, handling events, managing cookies, and
interacting with the browser's history, location, and more.
Example:
javascript
Copy code
window.alert("Hello!"); // Shows an alert
console.log(window.innerWidth); // Get the width of the window
97. How does localStorage differ from sessionStorage?
Answer:
• localStorage:
o Data stored in localStorage persists across browser sessions.
o It has no expiration time and remains until explicitly cleared by the user or via JavaScript.
o Data is stored per domain.
• sessionStorage:
o Data stored in sessionStorage is available only during the page session. Once the
browser or tab is closed, the data is cleared.
o It also stores data per domain but only for the current session.
Example:
javascript
Copy code
// localStorage
localStorage.setItem('username', 'Alice');
// sessionStorage
sessionStorage.setItem('sessionID', '12345');
98. What is the difference between cookies and localStorage?
Answer:
• Cookies:
o Cookies are small pieces of data (up to 4KB) stored by the browser and sent to the server
with every HTTP request.
o They have an expiration date and can be set with a specific domain, path, and secure
flags.
o Cookies are often used for tracking and session management.
• localStorage:
o localStorage can store larger amounts of data (5MB or more) than cookies.
o Data in localStorage is not automatically sent to the server with each request.
o It persists until explicitly deleted and is not tied to a specific expiration date.
99. What is the navigator object?
Answer:
The navigator object provides information about the browser, such as the browser name, version,
platform, language, and whether the user has enabled certain features like cookies or JavaScript.
Example:
javascript
Copy code
console.log(navigator.userAgent); // Get browser information
console.log(navigator.language); // Get the language of the browser
100. How do you perform DOM manipulation in JavaScript?
Answer:
DOM manipulation in JavaScript involves using methods and properties of the document object to
interact with and modify the structure of a webpage. Common operations include selecting elements,
changing content, adding/removing elements, and responding to user events.
Examples:
• Selecting an element:
javascript
Copy code
const element = document.getElementById('myElement');
• Changing content:
javascript
Copy code
element.textContent = 'New Content';
• Creating and appending elements:
javascript
Copy code
const newElement = document.createElement('div');
newElement.textContent = 'Hello, World!';
document.body.appendChild(newElement);
101. How do you use the history API in JavaScript?
Answer:
The history API allows you to interact with the browser's session history, enabling you to modify the URL
and navigate through the history stack without reloading the page. It includes methods like pushState(),
replaceState(), and go().
• pushState(): Adds a new state to the history.
• replaceState(): Replaces the current history state.
• go(): Moves forward or backward in the history.
Example:
javascript
Copy code
// Add a new history entry
history.pushState({ page: 1 }, "title 1", "?page=1");
// Replace the current entry
history.replaceState({ page: 2 }, "title 2", "?page=2");
// Go back in history
history.go(-1);
102. What is the purpose of the location object?
Answer:
The location object provides information about the current URL and allows you to manipulate it. You can
use it to navigate to different pages, reload the page, or get specific parts of the URL (e.g., hostname,
pathname).
Example:
javascript
Copy code
console.log(location.href); // Get the full URL
console.log(location.hostname); // Get the domain
location.assign('https://example.com'); // Navigate to a new URL
location.reload(); // Reload the current page
103. How does JavaScript handle browser events?
Answer:
JavaScript handles browser events using event listeners. An event listener waits for a specific event (e.g.,
click, input, load) and triggers a function when the event occurs.
• addEventListener(): Used to attach event handlers to DOM elements.
• Event types: Includes events like click, load, submit, etc.
Example:
javascript
Copy code
const button = document.getElementById('myButton');
button.addEventListener('click', function() {
alert('Button clicked!');
});
104. What is the fetch() API used for?
Answer:
The fetch() API is used to make HTTP requests in JavaScript. It returns a Promise that resolves to the
Response object, representing the response to the request. fetch() is often used for loading data from a
server asynchronously.
Example:
javascript
Copy code
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log('Error:', error));
105. What is the difference between synchronous and asynchronous requests?
Answer:
• Synchronous requests: The code execution waits for the request to complete before moving to
the next task. This can block the execution of other code and make the page unresponsive.
Example: (Not recommended for I/O operations)
javascript
Copy code
const data = getDataSynchronously(); // Waits for the data to return
console.log(data);
• Asynchronous requests: The code continues to run while waiting for the request to complete,
preventing the page from freezing. Asynchronous requests are commonly handled using
callbacks, promises, or async/await.
Example:
javascript
Copy code
getDataAsynchronously().then(data => {
console.log(data);
});
Interview-Focused Questions and Answers
106. Explain the Singleton design pattern in JavaScript.
Answer:
The Singleton design pattern ensures that a class has only one instance and provides a global access
point to that instance. It is commonly used for managing shared resources like configuration settings or
databases.
Example:
javascript
Copy code
const Singleton = (function () {
let instance;
function createInstance() {
return { name: "Singleton Instance" };
}
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
return instance;
};
})();
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // true
107. What is functional programming in JavaScript?
Answer:
Functional programming is a programming paradigm that treats computation as the evaluation of
mathematical functions, avoiding changing state and mutable data. Core principles include immutability,
pure functions, and higher-order functions.
Example:
Using a pure function:
javascript
Copy code
const add = (a, b) => a + b;
console.log(add(2, 3)); // 5
108. How would you reverse a string in JavaScript?
Answer:
You can reverse a string using the following approach:
javascript
Copy code
function reverseString(str) {
return str.split('').reverse().join('');
console.log(reverseString("hello")); // "olleh"
109. How can you remove duplicates from an array?
Answer:
Using the Set object:
javascript
Copy code
const uniqueArray = [...new Set([1, 2, 2, 3, 4, 4])];
console.log(uniqueArray); // [1, 2, 3, 4]
110. Write a function to flatten a nested array.
Answer:
javascript
Copy code
function flattenArray(arr) {
return arr.flat(Infinity);
console.log(flattenArray([1, [2, [3, [4]]]])); // [1, 2, 3, 4]
111. How do you check if a string is a palindrome?
Answer:
A palindrome reads the same backward as forward.
javascript
Copy code
function isPalindrome(str) {
const reversed = str.split('').reverse().join('');
return str === reversed;
console.log(isPalindrome("madam")); // true
console.log(isPalindrome("hello")); // false
112. Explain how to debounce a function.
Answer:
Debouncing ensures that a function is not called repeatedly within a short time. It delays the function
execution until after a specified wait time has elapsed.
Example:
javascript
Copy code
function debounce(func, delay) {
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), delay);
};
const log = debounce(() => console.log("Debounced!"), 300);
log();
113. Write a JavaScript function to find the factorial of a number.
Answer:
javascript
Copy code
function factorial(n) {
if (n === 0 || n === 1) return 1;
return n * factorial(n - 1);
console.log(factorial(5)); // 120
114. How would you find the maximum occurring character in a string?
Answer:
javascript
Copy code
function maxChar(str) {
const charMap = {};
let max = 0, maxChar = '';
for (let char of str) {
charMap[char] = (charMap[char] || 0) + 1;
if (charMap[char] > max) {
max = charMap[char];
maxChar = char;
return maxChar;
}
console.log(maxChar("javascript")); // "a"
115. How would you deep clone an object?
Answer:
Using JSON.parse and JSON.stringify:
javascript
Copy code
const obj = { a: 1, b: { c: 2 } };
const deepClone = JSON.parse(JSON.stringify(obj));
Using structuredClone (modern browsers):
javascript
Copy code
const deepClone = structuredClone(obj);
116. How do you merge two arrays in JavaScript?
Answer:
Using the spread operator:
javascript
Copy code
const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = [...arr1, ...arr2];
console.log(merged); // [1, 2, 3, 4]
117. How can you shuffle the elements of an array?
Answer:
javascript
Copy code
function shuffleArray(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
return arr;
console.log(shuffleArray([1, 2, 3, 4, 5]));
118. What is the difference between .map() and .forEach()?
Answer:
• .map(): Returns a new array with the results of applying a function to each element.
• .forEach(): Executes a function for each element but does not return a new array.
Example:
javascript
Copy code
const arr = [1, 2, 3];
const doubled = arr.map(x => x * 2); // [2, 4, 6]
arr.forEach(x => console.log(x * 2)); // Logs 2, 4, 6
119. How do you implement a custom map() function?
Answer:
javascript
Copy code
Array.prototype.customMap = function (callback) {
const result = [];
for (let i = 0; i < this.length; i++) {
result.push(callback(this[i], i, this));
}
return result;
};
const arr = [1, 2, 3];
console.log(arr.customMap(x => x * 2)); // [2, 4, 6]
120. Write a function to check if two strings are anagrams.
Answer:
javascript
Copy code
function areAnagrams(str1, str2) {
const format = str => str.replace(/\s+/g, '').toLowerCase().split('').sort().join('');
return format(str1) === format(str2);
console.log(areAnagrams("listen", "silent")); // true
console.log(areAnagrams("hello", "world")); // false
Miscellaneous Questions and Answers
121. What are promises, and why do we need them?
Answer:
Promises in JavaScript represent the eventual completion (or failure) of an asynchronous operation and
its resulting value. They are used to avoid callback hell and make code more readable.
Example:
javascript
Copy code
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Success!"), 1000);
});
promise.then(value => console.log(value)).catch(error => console.error(error));
122. Explain the difference between then and catch in promises.
Answer:
• .then() is used to handle the successful resolution of a promise.
• .catch() is used to handle errors or rejected promises.
javascript
Copy code
promise
.then(value => console.log("Resolved:", value))
.catch(error => console.error("Rejected:", error));
123. What is strict mode in JavaScript?
Answer:
"use strict"; enables strict mode, which helps catch common coding errors and unsafe actions (like using
undeclared variables).
Example:
javascript
Copy code
"use strict";
x = 10; // Throws an error (x is not declared)
124. What is tail call optimization?
Answer:
Tail call optimization refers to the process where the JavaScript engine optimizes a function call made in
the tail position (last action of a function) to prevent stack growth, enabling recursive functions to run
efficiently.
125. Explain what a polyfill is.
Answer:
A polyfill is code that provides modern functionality on older browsers that do not support it.
Example: Polyfill for Array.prototype.includes:
javascript
Copy code
if (!Array.prototype.includes) {
Array.prototype.includes = function (value) {
return this.indexOf(value) !== -1;
};
126. What is a transpiler in JavaScript?
Answer:
A transpiler converts modern JavaScript code (e.g., ES6+) into backward-compatible code for older
browsers. Examples include Babel and TypeScript.
127. What are the limitations of JavaScript?
Answer:
• Single-threaded nature makes it prone to blocking.
• Lack of type safety (though TypeScript mitigates this).
• Security issues like XSS (Cross-Site Scripting).
• Browser dependency for execution.
128. How is error handling done in JavaScript?
Answer:
Using try, catch, and finally blocks:
javascript
Copy code
try {
throw new Error("Something went wrong!");
} catch (error) {
console.error(error.message);
} finally {
console.log("Cleanup actions");
129. What is the difference between innerHTML and outerHTML?
Answer:
• innerHTML modifies the content inside an element.
• outerHTML replaces the element itself along with its content.
130. How do you measure performance in JavaScript?
Answer:
Using the Performance API:
javascript
Copy code
const start = performance.now();
// Perform task
const end = performance.now();
console.log(`Execution time: ${end - start} ms`);
Extra Questions and Answers
131. What is AJAX, and how does it work?
Answer:
AJAX (Asynchronous JavaScript and XML) allows web pages to update asynchronously without reloading
the entire page. It uses XMLHttpRequest or the fetch() API.
132. Explain the concept of reflow and repaint.
Answer:
• Reflow: When the layout of a web page changes (e.g., adding elements).
• Repaint: When visual properties like color change without affecting layout.
133. How do you use the console API effectively?
Answer:
Using various methods:
javascript
Copy code
console.log("Log");
console.warn("Warning");
console.error("Error");
console.table({ name: "Alice", age: 25 });
console.time("Timer");
// Code
console.timeEnd("Timer");
134. What is a service worker in JavaScript?
Answer:
A Service Worker is a script that runs in the background, independent of the web page, enabling
features like offline caching and push notifications.
135. How does async differ from defer in script tags?
Answer:
• async: Executes the script as soon as it is downloaded, potentially blocking rendering.
• defer: Executes the script after the HTML document has been parsed.
136. What are the stages of the JavaScript parsing process?
Answer:
1. Lexical analysis
2. Syntax analysis
3. Bytecode generation
4. Execution
137. What is the difference between document.ready and window.onload?
Answer:
• document.ready fires when the DOM is fully loaded.
• window.onload fires when all resources (images, scripts) are loaded.
138. How do you debug JavaScript code effectively?
Answer:
• Use browser dev tools (breakpoints, step-through debugging).
• Use console.log for quick insights.
• Employ linters like ESLint.
139. What are WebSockets in JavaScript?
Answer:
WebSockets provide full-duplex communication between the browser and server over a persistent
connection.
140. What is the purpose of the new keyword?
Answer:
It creates an instance of an object from a constructor function.
141. What are named exports vs default exports?
Answer:
• Named Exports: Export multiple values by name.
• Default Exports: Export a single default value.
142. How does destructuring help in function parameters?
Answer:
It extracts specific properties or values:
javascript
Copy code
function greet({ name, age }) {
console.log(`Hello, ${name}. Age: ${age}`);
greet({ name: "Alice", age: 25 });
143. What is the eval() function, and why is it discouraged?
Answer:
The eval() function executes strings as code. It's discouraged due to performance and security risks (e.g.,
code injection).
144. How do you use Intl for formatting?
Answer:
javascript
Copy code
const formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
console.log(formatter.format(123456)); // $123,456.00
145. What is BigInt in JavaScript?
Answer:
BigInt is a data type for integers larger than Number.MAX_SAFE_INTEGER.
javascript
Copy code
const bigInt = 123456789012345678901234567890n;
146. How do you handle dates and times in JavaScript?
Answer:
Using the Date object or libraries like moment.js and date-fns.
javascript
Copy code
const now = new Date();
console.log(now.toISOString());
147. What are JavaScript polyfills? Provide examples.
Answer:
Polyfills are fallback scripts for unsupported features. Example:
javascript
Copy code
if (!String.prototype.includes) {
String.prototype.includes = function (search) {
return this.indexOf(search) !== -1;
};
148. What are the differences between npm and yarn?
Answer:
Both are package managers for JavaScript. Differences:
• Speed: Yarn is generally faster due to parallel installation.
• Lockfiles: Yarn uses yarn.lock; npm uses package-lock.json.
149. What is event delegation in JavaScript?
Answer:
Event delegation allows a parent element to handle events for its child elements using event bubbling.
150. Explain lazy loading in JavaScript.
Answer:
Lazy loading defers the loading of resources (like images or scripts) until they are needed, improving
performance.
html
Copy code
<img src="placeholder.jpg" data-src="real-image.jpg" loading="lazy">