Top 100 JavaScript Interview Questions and Answers for Freshers & Experienced Developers
JavaScript is one of the most widely used programming languages for modern web development. It powers interactive websites, frontend applications, backend services, and browser-based functionality. Consequently, JavaScript knowledge is important for candidates preparing for frontend, full-stack, and web developer interviews.
This comprehensive guide to JavaScript Interview Questions and Answers covers beginner, intermediate, and advanced concepts. Moreover, it includes practical coding examples, ES6 features, asynchronous programming, DOM manipulation, and commonly tested technical topics.
Infocampus presents these questions to help freshers and experienced developers strengthen their programming knowledge. Whether you are preparing for a campus placement or an experienced developer interview, this guide provides a structured revision resource.
Section 1: Basic JavaScript Interview Questions and Answers
1. What is JavaScript?
JavaScript is a high-level, dynamically typed programming language used to develop interactive web applications. Additionally, it can run outside browsers through environments such as Node.js.
2. What are the main features of JavaScript?
JavaScript supports functions as values, object-oriented programming, asynchronous operations, and dynamic typing. Moreover, it provides extensive browser APIs and a large ecosystem of libraries.
3. What is the difference between Java and JavaScript?
Java and JavaScript are different programming languages with distinct type systems and runtime environments. Java is statically typed, while JavaScript is dynamically typed and commonly used for web development.
4. What are the data types in JavaScript?
JavaScript has seven primitive types: string, number, bigint, boolean, undefined, symbol, and null. Additionally, objects form the non-primitive category and include arrays and functions.
5. What is the difference between var, let, and const?
var has function or global scope, while let and const have block scope. Furthermore, const prevents reassignment of its binding, although object properties may still change.
var a = 10;
let b = 20;
const c = 30;
6. What is the difference between null and undefined?
undefined commonly indicates that a value has not been assigned. In contrast, null is an explicit value often used to represent intentional absence.
7. What is the difference between == and ===?
== performs equality comparison with type coercion when applicable. However, === compares without converting values between types.
console.log(5 == "5"); // true
console.log(5 === "5"); // false
8. What is NaN in JavaScript?
NaN stands for Not-a-Number and represents an invalid numeric result. Interestingly, its type is number, and NaN is not equal to itself.
9. What is type coercion?
Type coercion is JavaScript’s conversion of values between types during certain operations. For example, adding a number to a string may produce string concatenation.
10. What are truthy and falsy values?
Truthy values are treated as true in Boolean contexts, while falsy values are treated as false. Common falsy values include false, 0, -0, 0n, "", null, undefined, and NaN.
11. What is the typeof operator?
The typeof operator returns a string describing a value’s type. However, typeof null returns "object", which is a longstanding JavaScript behaviour.
12. What is a template literal?
A template literal uses backticks and supports embedded expressions and multiline strings. Consequently, it is convenient for constructing dynamic text.
const name = "Rahul";
console.log(`Welcome, ${name}!`);
13. What is the difference between slice() and splice()?
slice() returns a selected portion of an array without modifying the original array. In contrast, splice() changes an array by removing, replacing, or inserting elements.
14. What is a function in JavaScript?
A function is a reusable block of code that can accept arguments and return a value. Moreover, JavaScript functions can be stored in variables and passed to other functions.
15. What is an arrow function?
An arrow function provides concise syntax for defining functions. Additionally, arrow functions do not create their own this binding.
const multiply = (a, b) => a * b;
console.log(multiply(4, 5));
16. What is an anonymous function?
An anonymous function is a function expression without an explicit function name. It is commonly used in callbacks and immediately invoked function expressions.
17. What is an IIFE?
An Immediately Invoked Function Expression executes as soon as it is defined. Traditionally, developers used IIFEs to create isolated scopes.
(function () {
console.log("Executed immediately");
})();
18. What is scope in JavaScript?
Scope determines where variables and functions can be accessed. JavaScript includes global, function, and block scopes.
19. What is hoisting?
Hoisting describes how JavaScript processes declarations before executing code. Function declarations are available before their position, while let and const remain inaccessible until initialization.
20. What is the Temporal Dead Zone?
The Temporal Dead Zone is the period between entering a block and initializing a let or const binding. Accessing the binding during this period causes a ReferenceError.
Section 2: Intermediate JavaScript Interview Questions
21. What is a closure?
A closure occurs when a function retains access to variables from its surrounding lexical environment. Consequently, the function can use those variables even after the outer function returns.
function createCounter() {
let count = 0;
return function () {
return ++count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
22. What is lexical scope?
Lexical scope means variable accessibility depends on where functions are defined in the source code. Therefore, nested functions can access variables from their surrounding scopes.
23. What is the this keyword?
this refers to a value determined by how a regular function is called. However, arrow functions capture this from their surrounding lexical context.
24. What is the difference between call(), apply(), and bind()?
call() invokes a function with a specified this and individual arguments. apply() accepts an array-like argument collection, while bind() returns a new function with a bound this.
25. What is a callback function?
A callback is a function passed to another function for later execution. For example, callbacks are used in event handlers, array methods, and asynchronous operations.
26. What is a higher-order function?
A higher-order function accepts another function as an argument or returns a function. Common examples include map(), filter(), and reduce().
27. What is the difference between map() and forEach()?
map() creates a new array containing transformed values. In contrast, forEach() executes a callback for each element and returns undefined.
28. What is the difference between filter() and find()?
filter() returns an array of all elements satisfying a condition. Meanwhile, find() returns the first matching element or undefined.
29. What does reduce() do?
reduce() processes array elements to produce a single accumulated result. For example, it can calculate totals, build objects, or group records.
const numbers = [10, 20, 30];
const total = numbers.reduce((sum, n) => sum + n, 0);
console.log(total); // 60
30. What is destructuring?
Destructuring extracts values from arrays or properties from objects into variables. Consequently, it makes many assignment operations more concise.
31. What is the spread operator?
Spread syntax expands iterable values into individual elements or copies enumerable properties into object literals. It is commonly used to create shallow copies and combine data.
32. What is the rest parameter?
Rest parameters collect remaining function arguments into an array. Unlike the older arguments object, rest parameters produce a real array.
33. What is optional chaining?
Optional chaining uses ?. to access a property or call a function when the preceding value is not null or undefined. Otherwise, it returns undefined without continuing the chain.
34. What is nullish coalescing?
The ?? operator provides a fallback when its left operand is null or undefined. Unlike ||, it preserves valid falsy values such as 0 and false.
35. What is the difference between shallow copy and deep copy?
A shallow copy duplicates only the outer structure, so nested objects may remain shared. A deep copy recursively duplicates supported nested data.
36. What is Object.freeze()?
Object.freeze() prevents adding, removing, or changing an object’s own properties. However, freezing is shallow, so nested objects may remain mutable.
37. What is Object.seal()?
Object.seal() prevents adding or removing properties and makes existing properties non-configurable. Nevertheless, writable properties may still be updated.
38. What is the difference between Map and Object?
Map is designed for key-value storage and supports keys of any type. Objects are general-purpose structures with string or symbol property keys.
39. What is a Set?
A Set stores unique values according to its equality rules. Consequently, it is useful for removing duplicates and checking membership.
40. What is a generator function?
A generator function uses function* and can pause execution with yield. It returns a generator object that produces values on demand.
Section 3: Advanced JavaScript Interview Questions
41. What is the JavaScript event loop?
The event loop coordinates execution of tasks and microtasks around the JavaScript call stack. Consequently, asynchronous callbacks can execute after the current synchronous work finishes.
42. What is the call stack?
The call stack tracks active function calls during JavaScript execution. Each function call adds a stack frame, which is removed when the function returns.
43. What is a Promise?
A Promise represents the eventual completion or failure of an asynchronous operation. Its states are pending, fulfilled, and rejected.
const promise = Promise.resolve("Success");
promise.then(result => {
console.log(result);
});
44. What is async/await?
async/await provides syntax for working with Promises in a sequential-looking style. An async function returns a Promise, while await pauses that function until the awaited value settles.
45. What is the difference between Promise.all() and Promise.allSettled()?
Promise.all() fulfills when all inputs fulfill and rejects when any input rejects. In contrast, Promise.allSettled() waits for every input to settle and returns their outcomes.
46. What is Promise.race()?
Promise.race() settles according to the first input Promise that settles. Therefore, it can resolve or reject depending on that first outcome.
47. What is Promise.any()?
Promise.any() fulfills when the first input Promise fulfills. However, if every input rejects, it rejects with an AggregateError.
48. What are microtasks and macrotasks?
Microtasks include Promise reactions and callbacks queued through queueMicrotask(). Tasks include events and timers, with scheduling details determined by the host environment.
49. What is debouncing?
Debouncing delays a function until a specified quiet period has passed. It is useful for search input handling and other frequently triggered events.
50. What is throttling?
Throttling limits how frequently a function executes within a period. Consequently, it is useful for scroll, resize, and high-frequency event handling.
51. What is currying?
Currying transforms a function with multiple arguments into a sequence of functions that each accept an argument. It can support function reuse and partial application.
52. What is memoization?
Memoization stores previously computed results so repeated calls with equivalent inputs can reuse them. However, cache design must account for memory use and argument identity.
53. What is the prototype chain?
JavaScript objects can inherit properties from other objects through their prototype relationships. Property lookup follows the prototype chain until a match is found or the chain ends.
54. What is prototypal inheritance?
Prototypal inheritance allows objects to access properties and methods through their prototypes. JavaScript classes provide syntax built on this underlying model.
55. What is the difference between a class and a constructor function?
Classes provide structured syntax for creating objects and defining methods. Constructor functions can also initialize instances, although their syntax and certain semantics differ.
56. What is a WeakMap?
A WeakMap stores key-value pairs whose keys must be objects or non-registered symbols. Its weakly held keys do not prevent eligible objects from being garbage collected.
57. What is a WeakSet?
A WeakSet stores weakly held objects and non-registered symbols without allowing iteration. It is useful for tracking membership without retaining eligible objects unnecessarily.
58. What is garbage collection?
Garbage collection automatically reclaims memory associated with values that are no longer reachable. However, developers should still avoid retaining unnecessary references.
59. What is a memory leak in JavaScript?
A memory leak occurs when an application retains memory it no longer needs. Common causes include unnecessary references, uncleared timers, and forgotten event listeners.
60. What is event delegation?
Event delegation attaches a listener to a common ancestor rather than every child element. Because many DOM events bubble, one handler can process interactions from multiple descendants.
Section 4: DOM and Browser JavaScript Interview Questions
61. What is the DOM?
The Document Object Model represents an HTML or XML document as a tree of nodes. JavaScript can use DOM APIs to inspect and modify document content.
62. What is the difference between getElementById() and querySelector()?
getElementById() retrieves an element by its ID. Meanwhile, querySelector() returns the first element matching a CSS selector.
63. What is event bubbling?
Event bubbling is the phase in which an event propagates from its target toward ancestors. Consequently, parent elements may handle events originating from descendants.
64. What is event capturing?
Event capturing is the propagation phase that moves from ancestors toward the target. Developers can register capturing listeners using the appropriate event listener options.
65. What is preventDefault()?
preventDefault() requests cancellation of an event’s default action when the event is cancelable. For example, it can prevent a form’s normal submission behaviour.
66. What is stopPropagation()?
stopPropagation() prevents an event from continuing through the propagation path. However, it does not automatically cancel the event’s default action.
67. What is the difference between localStorage and sessionStorage?
Both store string-based key-value data within browser storage scopes. localStorage generally persists across browser sessions, while sessionStorage is scoped to a page session.
68. What is the difference between cookies and local storage?
Cookies can be sent automatically with matching HTTP requests and support security attributes. In contrast, local storage is accessed through browser JavaScript APIs and is not automatically attached to requests.
69. What is the Fetch API?
The Fetch API provides an interface for making HTTP requests and processing responses. It returns a Promise that fulfills with a Response object when an HTTP response is received.
70. What is CORS?
Cross-Origin Resource Sharing is an HTTP-based mechanism that allows servers to specify which cross-origin browser requests are permitted. Browsers enforce the relevant access restrictions.
71. What is innerHTML?
innerHTML gets or sets HTML markup inside an element. However, inserting untrusted strings can create cross-site scripting risks.
72. What is the difference between innerText and textContent?
textContent returns the text content of a node and its descendants. In contrast, innerText reflects rendered text and is influenced by layout and visibility.
73. What is a Web Worker?
A Web Worker runs JavaScript in a separate execution context from the main page. Consequently, suitable computational work can be performed without blocking the main UI thread.
74. What is the Intersection Observer API?
Intersection Observer asynchronously reports when an element intersects a target viewport or ancestor. It is useful for lazy loading and visibility-related functionality.
75. What is the difference between setTimeout() and setInterval()?
setTimeout() schedules a callback once after a minimum delay. Meanwhile, setInterval() repeatedly schedules a callback, subject to host scheduling behaviour.
Section 5: JavaScript Coding Interview Questions and Answers
76. How do you reverse a string in JavaScript?
One common solution converts a string into an array, reverses it, and joins the elements. However, this basic approach operates on UTF-16 code units and may not preserve all Unicode characters correctly.
function reverseString(str) {
return str.split("").reverse().join("");
}
console.log(reverseString("JavaScript"));
// tpircSavaJ
77. How do you check whether a string is a palindrome?
A palindrome reads the same forward and backward. For simple strings, compare the original value with its reversed version.
function isPalindrome(str) {
return str === str.split("").reverse().join("");
}
console.log(isPalindrome("madam")); // true
78. How do you find the largest number in an array?
Use Math.max() with spread syntax for a reasonably sized array. For very large arrays, an iterative approach avoids argument-count limits.
const numbers = [12, 45, 8, 67, 23];
console.log(Math.max(...numbers)); // 67
79. How do you remove duplicates from an array?
A Set can remove duplicate primitive values according to its equality rules. Afterwards, convert the result back into an array.
const numbers = [1, 2, 2, 3, 4, 4];
const unique = [...new Set(numbers)];
console.log(unique); // [1, 2, 3, 4]
80. How do you find the factorial of a number?
Factorial is the product of positive integers up to a given non-negative integer. An iterative solution avoids unnecessary recursion.
function factorial(n) {
if (!Number.isInteger(n) || n < 0) {
throw new RangeError("Enter a non-negative integer");
}
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
console.log(factorial(5)); // 120
81. How do you generate a Fibonacci sequence?
A Fibonacci sequence begins with two initial values, and each subsequent value is their sum. The following example generates a specified number of terms.
function fibonacci(count) {
const result = [];
let a = 0;
let b = 1;
for (let i = 0; i < count; i++) {
result.push(a);
[a, b] = [b, a + b];
}
return result;
}
console.log(fibonacci(7));
// [0, 1, 1, 2, 3, 5, 8]
82. How do you count vowels in a string?
Use a regular expression to identify vowels in a string. The following example counts English vowels regardless of letter case.
function countVowels(str) {
return (str.match(/[aeiou]/gi) || []).length;
}
console.log(countVowels("JavaScript")); // 3
83. How do you find the second-largest distinct number?
Remove duplicate values, sort the numbers in descending order, and select the second element. However, large datasets may benefit from a single-pass solution.
function secondLargest(arr) {
const unique = [...new Set(arr)];
unique.sort((a, b) => b - a);
return unique[1];
}
console.log(secondLargest([10, 20, 30, 30, 15]));
// 20
84. How do you check whether a number is prime?
A prime number is greater than one and has exactly two positive divisors. An efficient basic approach checks potential divisors up to the square root.
function isPrime(n) {
if (!Number.isInteger(n) || n < 2) return false;
for (let i = 2; i * i <= n; i++) {
if (n % i === 0) return false;
}
return true;
}
console.log(isPrime(17)); // true
85. How do you calculate the sum of an array?
Use reduce() to accumulate numeric values. Providing an initial value also handles empty arrays.
const numbers = [10, 20, 30, 40];
const sum = numbers.reduce((total, n) => total + n, 0);
console.log(sum); // 100
86. How do you find the frequency of array elements?
Use a Map to count how often each value appears. This approach supports keys beyond strings.
function countFrequency(arr) {
const counts = new Map();
for (const value of arr) {
counts.set(value, (counts.get(value) || 0) + 1);
}
return counts;
}
console.log([...countFrequency(["a", "b", "a"])]);
// [["a", 2], ["b", 1]]
87. How do you flatten a nested array?
The flat() method reduces array nesting by a specified depth. Using Infinity flattens all levels of nested arrays.
const nested = [1, [2, [3, 4]], 5];
console.log(nested.flat(Infinity));
// [1, 2, 3, 4, 5]
88. How do you sort an array of objects by age?
Use sort() with a comparator that compares the age properties. To avoid mutating the original array, create a copy first.
const people = [
{ name: "Amit", age: 30 },
{ name: "Ravi", age: 24 }
];
const sorted = [...people].sort((a, b) => a.age - b.age);
console.log(sorted);
89. How do you find the intersection of two arrays?
Convert one array into a Set and filter the other array for matching values. This example also removes duplicates from the result.
function intersection(a, b) {
const lookup = new Set(b);
return [...new Set(a)].filter(value => lookup.has(value));
}
console.log(intersection([1, 2, 3], [2, 3, 4]));
// [2, 3]
90. How do you implement a debounce function?
A debounce function resets its timer whenever it is called again. Therefore, the wrapped function runs only after calls stop for the specified delay.
function debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
Section 6: JavaScript Scenario-Based Interview Questions
91. Why does setTimeout(fn, 0) not execute immediately?
A zero-delay timer schedules a callback for a future task. However, the current synchronous execution and pending microtasks must be handled according to the host’s scheduling rules.
92. Why does typeof null return "object"?
This is a historical JavaScript behaviour preserved for compatibility. Nevertheless, null is a primitive value, not an object.
93. What happens when a Promise rejects without a rejection handler?
The host environment may report an unhandled rejection. Therefore, applications should handle expected failures using .catch() or appropriate try/catch around awaited Promises.
94. Why does 0.1 + 0.2 not equal 0.3 exactly?
JavaScript numbers commonly use IEEE 754 double-precision floating-point representation. Consequently, some decimal fractions cannot be represented exactly in binary.
console.log(0.1 + 0.2);
// 0.30000000000000004
95. Why is [] == false true?
Loose equality applies type coercion before comparing these values. However, relying on this behaviour can make code difficult to understand, so strict equality is generally preferable.
96. Why is [] === [] false?
Arrays are objects, and object equality compares identity rather than structural contents. Therefore, two separately created arrays are not strictly equal.
97. How do you handle errors in async/await?
Use try/catch around awaited operations that may reject. Additionally, errors can be rethrown or converted into meaningful application-level responses.
async function loadData() {
try {
const response = await fetch("/api/data");
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error("Request failed:", error);
throw error;
}
}
98. Why should developers avoid using eval()?
eval() executes JavaScript code from a string and can introduce security and maintainability problems. Furthermore, it can complicate debugging and optimization.
99. How can JavaScript application performance be improved?
Performance improvements may include reducing unnecessary DOM updates, avoiding expensive repeated calculations, and using appropriate data structures. Additionally, profiling should identify actual bottlenecks before optimization.
100. How do you prepare for an experienced JavaScript developer interview?
Experienced candidates should review closures, asynchronous execution, the event loop, prototypes, browser APIs, and performance optimization. Moreover, they should practise system-level problem-solving and explaining architectural decisions from previous projects.
Important JavaScript Topics to Revise Before Interviews
| Experience Level | Important Topics | Preparation Focus |
|---|---|---|
| Freshers | Variables, Functions, Arrays, Objects | Fundamentals and Coding |
| Junior Developers | ES6, DOM, Events, Promises | Practical Web Development |
| Intermediate Developers | Closures, Async/Await, Event Loop | Debugging and Application Logic |
| Experienced Developers | Prototypes, Performance, Memory | Architecture and Optimization |
| Full Stack Developers | APIs, Async Programming, Error Handling | End-to-End Development |
JavaScript Interview Preparation Tips
Strengthen the Fundamentals
Start with variables, functions, scope, arrays, and objects. Furthermore, practise explaining concepts using small code examples.
Practise Coding Problems Regularly
Coding exercises improve logical reasoning and implementation skills. Therefore, solve problems involving strings, arrays, maps, recursion, and asynchronous operations.
Understand Asynchronous JavaScript
Promises, async/await, microtasks, and the event loop are important interview topics. Moreover, understanding execution order helps candidates solve scenario-based questions.
Build Practical Projects
Projects demonstrate how JavaScript concepts work together in applications. For example, a task manager, weather dashboard, or API-based search interface can provide useful experience.
Prepare for Code Explanation
Interviewers may ask why a particular solution was chosen. Consequently, candidates should discuss correctness, complexity, readability, and alternative approaches.
Frequently Asked Questions About JavaScript Interviews
Is JavaScript difficult for freshers?
JavaScript fundamentals are approachable for beginners with consistent practice. However, advanced concepts such as closures and asynchronous execution require additional understanding.
Are JavaScript coding questions important?
Yes. Coding questions help interviewers evaluate problem-solving and programming ability. Therefore, candidates should practise implementing solutions without relying entirely on memorized examples.
What JavaScript topics are important for frontend developers?
DOM manipulation, events, ES6 features, asynchronous programming, and browser APIs are important. Additionally, frontend framework knowledge may be required for specific positions.
What topics should experienced developers prepare?
Experienced developers should review asynchronous execution, closures, prototypes, performance, memory management, and application architecture. Furthermore, real project experience is important.
Is ES6 knowledge necessary for JavaScript interviews?
Modern JavaScript features are relevant to many development roles. Consequently, candidates should understand arrow functions, destructuring, modules, promises, and related language features.
Are JavaScript and TypeScript interview questions the same?
They overlap in runtime JavaScript concepts, but TypeScript interviews also cover static typing, interfaces, generics, and type narrowing. Therefore, TypeScript roles require additional preparation.
Should I learn React before a JavaScript interview?
React is relevant for positions that use the framework. However, strong JavaScript fundamentals remain important regardless of the frontend library.
How can I improve JavaScript problem-solving skills?
Practise small problems consistently and explain the reasoning behind each solution. Additionally, review time complexity and test edge cases.
Why Explore JavaScript Learning with Infocampus?
Infocampus provides technology education information, programming resources, and career-related guidance. Its learning content helps students explore JavaScript fundamentals, modern development practices, and technical interview preparation.
Moreover, structured revision can help learners identify areas that require additional practice. By combining conceptual understanding with coding exercises, candidates can prepare more effectively for technical assessments.
Conclusion
Preparing for JavaScript interviews requires a strong understanding of programming fundamentals, modern language features, asynchronous execution, and practical coding. However, memorizing definitions alone is not sufficient for demonstrating professional development skills.
These 100 JavaScript Interview Questions and Answers provide a structured preparation resource for freshers and experienced developers. Continue practising coding problems, building projects, and reviewing core concepts to strengthen your technical confidence.
Explore more programming tutorials, technical interview questions, and career guidance with Infocampus.