Top 50 JavaScript Interview Questions & Answers
Top 50 JavaScript interview questions and answers for freshers and experienced developers: closures, hoisting, this, promises, the event loop and ES6+.
JavaScript Basics & Types
Q1. What is JavaScript?
A high-level, dynamically typed language that runs in every web browser and, through runtimes such as Node.js, on servers. It supports object-oriented, functional and event-driven styles.
Q2. What are the primitive data types in JavaScript?
string, number, bigint, boolean, undefined, null and symbol. Everything else, including arrays and functions, is an object.
Q3. What is the difference between == and ===?
== converts both values to a common type before comparing, so '5' == 5 is true. === compares value and type without conversion, so '5' === 5 is false. Prefer ===.
Q4. What is the difference between null and undefined?
undefined means a variable was declared but never assigned. null is a value you assign on purpose to mean "no value". typeof null returns 'object', a long-standing quirk.
Q5. What is the difference between var, let and const?
var is function-scoped and hoisted with the value undefined. let and const are block-scoped and cannot be used before their declaration. const cannot be reassigned, though an object it holds can still change.
Q6. What is type coercion?
JavaScript converting a value from one type to another automatically, as in '3' * 2 giving 6 or '3' + 2 giving '32'. The + operator prefers strings, while other arithmetic operators convert to numbers.
Q7. What are truthy and falsy values?
Falsy values are false, 0, -0, 0n, '', null, undefined and NaN. Every other value, including '0', [] and {}, is truthy in a boolean context.
Q8. What is NaN and how do you check for it?
NaN means "not a number" and results from invalid maths such as 0 / 0. It is not equal to itself, so use Number.isNaN(value) to test for it.
Q9. What is the difference between typeof and instanceof?
typeof returns a string naming a value's type, such as 'string' or 'object'. instanceof checks whether an object has a constructor's prototype in its prototype chain, as in arr instanceof Array.
Q10. How do you check whether a value is an array?
Use Array.isArray(value). typeof returns 'object' for arrays, so it cannot tell them apart from plain objects.
Functions, Scope & Closures
Q11. What is hoisting?
Before code runs, declarations are moved to the top of their scope. Function declarations are hoisted with their body, var with the value undefined, and let/const stay in the temporal dead zone until their line runs.
Q12. What is the temporal dead zone?
The time between the start of a block and the line where a let or const variable is declared. Reading the variable during that time throws a ReferenceError.
Q13. What is a closure?
A function that remembers the variables of the scope it was created in, even after that scope has finished running. Closures power private state, factory functions and callbacks.
Q14. Give a practical use of closures.
A counter with private state: function makeCounter() { let n = 0; return () => ++n; }. Only the returned function can read or change n.
Q15. What is lexical scope?
Scope decided by where code is written. An inner function can read the variables of the functions around it, and the lookup follows that nesting outward.
Q16. What is the difference between a function declaration and a function expression?
A declaration such as function add() {} is hoisted with its body, so it can be called before its line. A function expression assigned to a variable can only be called after that line runs.
Q17. How do arrow functions differ from regular functions?
Arrow functions have no own this, arguments or prototype, and cannot be used with new. They take this from the surrounding scope, which suits callbacks.
Q18. What is an IIFE?
An Immediately Invoked Function Expression, such as (function () { ... })(), which runs as soon as it is defined. It was used to create a private scope before modules and block scope existed.
Q19. What are higher-order functions?
Functions that take other functions as arguments or return them. map, filter, reduce and setTimeout are common examples.
Q20. What is currying?
Turning a function of several arguments into a chain of functions that each take one, so add(a, b) becomes add(a)(b). It helps create specialised functions through partial application.
Objects, `this` & Prototypes
Q21. How is the value of this decided?
It depends on how a function is called: the object before the dot for a method call, the new object with new, the given value with call, apply or bind, and undefined in strict mode for a plain call. Arrow functions use the surrounding this.
Q22. What is the difference between call, apply and bind?
call runs a function with a given this and arguments listed one by one. apply does the same with arguments in an array. bind returns a new function with this fixed, without running it.
Q23. What is prototypal inheritance?
Every object has a hidden link to another object, its prototype. When a property is not found on the object, JavaScript looks it up along this prototype chain.
Q24. What is the difference between __proto__ and prototype?
prototype is a property of constructor functions that becomes the prototype of objects created with new. __proto__ is an object's link to its own prototype; use Object.getPrototypeOf() instead.
Q25. How do ES6 classes relate to prototypes?
Classes are cleaner syntax over prototypes. Methods defined in a class live on its prototype, and extends sets up the prototype chain between the two classes.
Q26. What is the difference between a shallow copy and a deep copy?
A shallow copy, such as { ...obj }, copies only top-level properties, so nested objects are still shared. A deep copy duplicates every level; structuredClone(obj) does this in modern environments.
Q27. What does Object.freeze() do?
It makes an object's existing properties read-only and stops new ones being added. It is shallow, so nested objects can still change.
Q28. What is destructuring?
Syntax that unpacks values from arrays or properties from objects into variables, as in const { name, age } = user or const [first, second] = list. It supports defaults and renaming.
Q29. What are the spread and rest operators?
Both use .... Spread expands an array or object into elements or properties, as in [...a, ...b]. Rest collects remaining items into one array or object, as in function f(...args).
Q30. What is optional chaining?
The ?. operator reads a nested property and returns undefined instead of throwing when part of the chain is null or undefined, as in user?.address?.city.
Asynchronous JavaScript & the Event Loop
Q31. What is the event loop?
The mechanism that lets single-threaded JavaScript handle async work. When the call stack is empty, it runs all queued microtasks, then takes the next macrotask, such as a timer callback, and repeats.
Q32. What is the difference between microtasks and macrotasks?
Microtasks include promise callbacks and queueMicrotask. Macrotasks include setTimeout, setInterval and I/O events. All microtasks run before the next macrotask, so a resolved promise's then runs before a setTimeout(fn, 0).
Q33. What is a Promise?
An object that represents a value that will be available later. It is pending, then either fulfilled with a value or rejected with an error, and you react with then, catch and finally.
Q34. What is the difference between Promise.all, allSettled, race and any?
all resolves when every promise fulfils and rejects on the first failure. allSettled waits for all and reports each result. race settles with the first to settle. any resolves with the first to fulfil.
Q35. How does async/await work?
An async function always returns a promise. await pauses that function until a promise settles, then returns its value or throws its error, so async code reads like synchronous code.
Q36. How do you handle errors with async/await?
Wrap the await calls in try/catch, or call .catch() on the promise the async function returns. An unhandled rejection is reported as an error.
Q37. What is callback hell?
Deeply nested callbacks that each depend on the previous result, which makes code hard to read and handle errors in. Promises and async/await flatten this into a straight sequence.
Q38. What is the difference between debouncing and throttling?
Debouncing runs a function only after calls stop for a set time, which suits search boxes. Throttling runs it at most once per interval, which suits scroll and resize handlers.
Q39. Is JavaScript single-threaded?
The main JavaScript thread runs one piece of code at a time. Browsers and Node.js do I/O, timers and networking in the background, and Web Workers or worker threads run code in parallel.
Q40. What does setTimeout(fn, 0) do?
It queues fn as a macrotask to run after the current code and all pending microtasks finish. It never runs immediately, and browsers may delay it slightly.
ES6+ Features, Arrays & the DOM
Q41. What is the difference between map, filter and reduce?
map returns a new array with each item transformed. filter returns the items that pass a test. reduce combines all items into a single value, such as a sum or an object.
Q42. What is the difference between forEach and map?
forEach runs a function for each item and returns undefined. map returns a new array of results. Use map when you need the output.
Q43. What are template literals?
Strings written with backticks that allow embedded expressions through ${...} and span several lines without escape characters.
Q44. What are ES modules?
The standard module system using import and export. Modules have their own scope, run in strict mode, and their imports are resolved before the code runs, which enables tree shaking.
Q45. What are Map and Set?
Map stores key-value pairs with keys of any type and keeps insertion order. Set stores unique values. Both have a size property and are easy to iterate.
Q46. What is the difference between Map and a plain object?
A Map accepts any key type, keeps insertion order, has a size and has no inherited keys. A plain object only has string and symbol keys and suits fixed, known fields.
Q47. What are event bubbling and capturing?
A DOM event travels down from the window to the target in the capture phase, then back up in the bubble phase. Listeners run in the bubble phase unless added with { capture: true }.
Q48. What is event delegation?
Attaching one listener to a parent and using event.target to handle events from its children. It saves memory and works for elements added later.
Q49. What is the difference between localStorage, sessionStorage and cookies?
localStorage keeps data until it is cleared, sessionStorage until the tab closes, and both stay in the browser. Cookies are small, can expire, and are sent to the server with every request.
Q50. What does 'use strict' do?
It turns on strict mode, which throws errors for silent mistakes such as assigning to undeclared variables, and makes this undefined in plain function calls. Modules and classes are strict by default.