JavaScript Interview Questions & Answers

JavaScript Interview Questions & Answers (2026) – Top 30 Questions for Freshers & Experienced

Table of Contents

⚡ AI Overview (Quick Answer)

To crack a JavaScript interview in 2026, you must master closures, hoisting, the event loop, promises, async/await, ES6+ features, prototypal inheritance, and DOM manipulation. Interviewers at companies like TCS, Infosys, Accenture, and product startups test both conceptual depth and live coding skills. This guide covers 30+ real JavaScript interview questions with model answers for freshers and experienced developers, plus preparation tips, salary insights for India (2026), and an FAQ section.


Introduction: Why JavaScript Is Still the King of Interviews in 2026

Picture this: you walk into your dream front-end interview, confident after weeks of practice. The interviewer smiles and asks, “What will console.log(typeof null) print, and why?” Suddenly your palms sweat. JavaScript looks friendly on the surface, but its interview questions are famous for hidden traps — hoisting, coercion, closures inside loops, and the mysterious this keyword.

JavaScript remains the most widely used programming language on the planet in 2026. It powers the front end (React, Angular, Vue), the back end (Node.js, Deno, Bun), mobile apps (React Native), desktop apps (Electron), and even AI-powered web tools. Every web developer role — front-end, back-end, or full-stack — includes at least one dedicated JavaScript round. Service companies like TCS, Infosys, Wipro, and Cognizant test fundamentals, while product companies like Flipkart, Razorpay, and Zoho go deep into the event loop and performance.

Here is what a typical JavaScript interview process looks like:

Interview StageWhat Is TestedTypical Duration
Round 1 – Online Test / MCQOutput prediction, syntax, basic logic30–60 minutes
Round 2 – Core JavaScriptClosures, hoisting, scope, this, ES645–60 minutes
Round 3 – Async & CodingEvent loop, promises, polyfills, DSA problems60–90 minutes
Round 4 – Framework / ProjectReact/Angular, APIs, project architecture45–60 minutes
HR RoundCommunication, salary, culture fit20–30 minutes

If your role involves React, revise our complete guide on React JS Interview Questions, and for the final round see HR Interview Questions for Freshers.


Basic JavaScript Interview Questions for Freshers (Q1–Q12)

Q1. What is JavaScript, and how is it different from Java?

Answer: JavaScript is a high-level, interpreted, dynamically-typed scripting language originally created by Brendan Eich in 1995 to make web pages interactive. Despite the name, it has no relation to Java. Java is a statically-typed, compiled, class-based language that runs on the JVM, while JavaScript is dynamically typed, prototype-based, and runs inside browsers and Node.js. A memorable interview line: “Java and JavaScript are as related as car and carpet.” JavaScript today follows the ECMAScript specification, with new features released every year.

Q2. What are the data types in JavaScript?

Answer: JavaScript has 8 data types — 7 primitives and 1 reference type. Primitives: string, number, bigint, boolean, undefined, null, and symbol. The reference type is object (which includes arrays, functions, dates, and plain objects). A classic follow-up trap: typeof null returns “object” — this is a 30-year-old bug kept for backward compatibility. Mentioning it shows you understand JavaScript’s quirks, not just its syntax.

Q3. What is the difference between var, let, and const?

Answer: This is the most asked JavaScript question for freshers.

Featurevarletconst
ScopeFunction scopeBlock scopeBlock scope
HoistingHoisted (initialized as undefined)Hoisted (Temporal Dead Zone)Hoisted (Temporal Dead Zone)
Re-declarationAllowedNot allowedNot allowed
Re-assignmentAllowedAllowedNot allowed
Use in 2026AvoidWhen value changesDefault choice

A strong closing line: “I use const by default, let only when the value must change, and never var in modern code.”

Q4. What is hoisting in JavaScript?

Answer: Hoisting is JavaScript’s behavior of moving variable and function declarations to the top of their scope during the compilation phase, before code execution. Function declarations are fully hoisted (you can call them before they appear in code), while var variables are hoisted but initialized as undefined. Variables declared with let and const are hoisted too, but stay in the Temporal Dead Zone (TDZ) until execution reaches their declaration — accessing them earlier throws a ReferenceError. Mentioning the TDZ separates strong candidates from average ones.

Q5. What is the difference between == and ===?

Answer: == (loose equality) compares values after type coercion, while === (strict equality) compares both value and type with no coercion. For example, “5” == 5 is true because the string is converted to a number, but “5” === 5 is false. Famous gotchas: null == undefined is true, NaN == NaN is false, and [] == false is true. Best practice in 2026: always use === unless you intentionally need coercion.

Q6. What is a closure in JavaScript?

Answer: A closure is created when an inner function “remembers” and continues to access variables from its outer function’s scope, even after the outer function has finished executing. Example: a counter function that returns an inner function which increments a private count variable. Real-world uses include data privacy (private variables), function factories, memoization, and event handlers. Closures are the #1 most asked conceptual JavaScript question — be ready to write one on a whiteboard and explain the classic “closures inside a for-loop with var” trap.

Q7. What is the difference between undefined and null?

Answer: undefined means a variable has been declared but not assigned a value — it is JavaScript’s default “no value yet” state. null is an intentional assignment that represents “no value on purpose,” set explicitly by the developer. Their types differ too: typeof undefined is “undefined” while typeof null is “object”. In interviews, add: “I use null to deliberately clear an object reference, and I treat undefined as a signal that something was never initialized.”

Q8. What are template literals in ES6?

Answer: Template literals use backticks (`) instead of quotes and allow embedded expressions with ${} syntax, multi-line strings without \n, and tagged templates for advanced string processing. Example: `Hello ${name}, you scored ${marks * 2}`. They replaced messy string concatenation with + and are now the standard way to build strings in modern JavaScript.

Q9. What are arrow functions, and how do they differ from regular functions?

Answer: Arrow functions (=>), introduced in ES6, provide shorter syntax and — most importantly — do not have their own this. They inherit this from the enclosing lexical scope. They also lack their own arguments object, cannot be used as constructors with new, and have no prototype property. Rule of thumb for interviews: use arrow functions for callbacks and array methods, but regular functions for object methods where this must refer to the object.

Q10. What is the DOM, and how does JavaScript interact with it?

Answer: The DOM (Document Object Model) is a tree-like programming interface that represents an HTML page as objects, where every tag becomes a node. JavaScript reads and manipulates the DOM using methods like document.querySelector(), getElementById(), createElement(), and properties like innerHTML and textContent. Frequent DOM manipulation is expensive, which is why frameworks like React introduced the Virtual DOM to batch updates efficiently.

Q11. What is event bubbling and event capturing?

Answer: When an event occurs on a nested element, it travels through the DOM in two phases. Capturing goes from the root down to the target element, and bubbling goes from the target back up to the root. By default, event listeners fire in the bubbling phase. This enables event delegation — attaching one listener on a parent to handle events from many children — which is both a performance optimization and a very common interview question. event.stopPropagation() halts the journey.

Q12. What is the difference between localStorage, sessionStorage, and cookies?

Answer:

FeaturelocalStoragesessionStorageCookies
Capacity~5–10 MB~5 MB~4 KB
ExpiryNever (until cleared)On tab closeManually set
Sent to serverNoNoYes, with every request
Use caseTheme, preferencesPer-tab stateAuthentication, tracking

Bonus point: mention that sensitive tokens should ideally live in httpOnly cookies to protect against XSS attacks.


Intermediate JavaScript Interview Questions (Q13–Q22)

Q13. Explain the JavaScript event loop.

Answer: JavaScript is single-threaded, yet it handles asynchronous operations through the event loop. Synchronous code runs on the call stack. Async operations (timers, fetch, I/O) are delegated to browser/Node APIs. When they finish, their callbacks wait in queues: the microtask queue (promises, queueMicrotask) and the macrotask queue (setTimeout, setInterval, I/O). The event loop continuously checks: when the call stack is empty, it first drains ALL microtasks, then takes one macrotask. This is why a resolved promise’s .then() always runs before a setTimeout(fn, 0). Expect a code-output question on this in almost every interview.

Q14. What are promises, and what states can they have?

Answer: A Promise is an object representing the eventual completion or failure of an asynchronous operation. It has three states: pending (initial), fulfilled (resolved with a value), and rejected (failed with a reason). Once settled, a promise’s state never changes. Consumers use .then() for success, .catch() for errors, and .finally() for cleanup. Promises solved “callback hell” by enabling flat, chainable async code.

Q15. What is async/await, and how does it relate to promises?

Answer: async/await (ES2017) is syntactic sugar over promises that lets you write asynchronous code that reads like synchronous code. An async function always returns a promise; await pauses the function’s execution until the promise settles, without blocking the main thread. Errors are handled with familiar try…catch blocks. Interview tip: mention that multiple independent awaits should be parallelized with Promise.all() instead of awaiting them sequentially — this shows performance awareness.

Q16. What is the difference between Promise.all, Promise.allSettled, Promise.race, and Promise.any?

Answer: Promise.all() resolves when all promises resolve, but rejects immediately if any one rejects (fail-fast). Promise.allSettled() waits for all promises regardless of outcome and returns an array of status objects — perfect for batch API calls where partial failure is acceptable. Promise.race() settles with whichever promise settles first, win or lose — useful for timeouts. Promise.any() resolves with the first fulfilled promise and only rejects if all reject. Knowing all four is a strong intermediate signal.

Q17. Explain the this keyword in JavaScript.

Answer: The value of this depends on how a function is called, not where it is defined. In a regular function call, this is the global object (or undefined in strict mode). In a method call (obj.method()), this is the object before the dot. In a constructor with new, this is the newly created object. With call, apply, or bind, this is explicitly set. Arrow functions ignore all these rules and inherit this lexically from their surrounding scope. Be ready for tricky output-prediction questions mixing these scenarios.

Q18. What are call(), apply(), and bind()?

Answer: All three explicitly set the value of this for a function. call(thisArg, a, b) invokes the function immediately with arguments listed individually. apply(thisArg, [a, b]) invokes immediately with arguments as an array. bind(thisArg) does not invoke — it returns a new permanently-bound function for later use. Memory trick: Call = Commas, Apply = Array, Bind = Bound for later. Writing a polyfill for bind() is a popular coding round task.

Q19. What is prototypal inheritance?

Answer: Every JavaScript object has a hidden internal link ([[Prototype]], accessible via __proto__ or Object.getPrototypeOf()) to another object called its prototype. When you access a property that doesn’t exist on the object, JavaScript walks up this prototype chain until it finds the property or reaches null. ES6 class syntax is syntactic sugar over this mechanism — under the hood, methods live on ClassName.prototype. Explaining that JavaScript classes are “prototypes in a suit” earns credibility.

Q20. What is debouncing and throttling?

Answer: Both are performance optimization techniques for high-frequency events. Debouncing delays function execution until a pause occurs — the function runs only after the user stops triggering the event for N milliseconds (classic use: search box API calls). Throttling guarantees the function runs at most once every N milliseconds, regardless of how often the event fires (classic use: scroll handlers, window resize). Implementing debounce from scratch using closures and setTimeout is one of the top 5 live-coding questions in front-end interviews.

Q21. What are higher-order functions? Explain map, filter, and reduce.

Answer: A higher-order function either takes a function as an argument or returns one. The famous array trio: map() transforms every element and returns a new array of the same length; filter() returns a new array containing only elements that pass a test; reduce() accumulates all elements into a single value (sum, object, grouped data). None of them mutate the original array. Interviewers often ask you to chain them — e.g., “find the total salary of all employees in the IT department” — or to implement a polyfill for map().

Q22. What is destructuring, and what are the spread and rest operators?

Answer: Destructuring extracts values from arrays or objects into variables in one line: const { name, age } = user or const [first, second] = list. The spread operator (…) expands an iterable into individual elements — used for copying arrays/objects, merging, and passing arguments. The rest operator (same … syntax, opposite job) collects remaining elements into an array, as in function parameters function sum(…nums). These ES6 features appear constantly in React code, so front-end interviewers expect fluency.


Advanced & Scenario-Based JavaScript Interview Questions (Q23–Q30)

Q23. What is currying in JavaScript?

Answer: Currying transforms a function with multiple arguments into a sequence of functions each taking one argument: sum(a, b, c) becomes sum(a)(b)(c). It is implemented using closures and enables partial application — pre-filling some arguments to create specialized functions, like const addGST = multiply(1.18). A favorite coding question: “Write an infinite currying function so that add(1)(2)(3)() returns 6.”

Q24. What is memoization, and when would you use it?

Answer: Memoization caches the results of expensive function calls and returns the cached result when the same inputs occur again. It is implemented with a closure holding a cache object (often a Map), keyed by the function arguments. Classic use cases: recursive Fibonacci, expensive API computations, and React’s useMemo/React.memo. Trade-off to mention: memoization exchanges memory for speed, so it suits pure functions with repeated inputs.

Q25. Explain shallow copy vs deep copy in JavaScript.

Answer: A shallow copy (Object.assign({}, obj) or spread {…obj}) copies only the first level — nested objects are still shared references, so mutating them affects both copies. A deep copy duplicates every level. The modern standard is structuredClone(obj) (supported in all browsers and Node 17+), which handles nested objects, dates, maps, and sets. The old JSON.parse(JSON.stringify(obj)) trick fails on functions, undefined, dates, and circular references — pointing out these limitations is an instant credibility boost.

Q26. What are JavaScript modules (ES Modules vs CommonJS)?

Answer: Modules split code into reusable files with their own scope. CommonJS (require/module.exports) is the older Node.js system — synchronous and dynamic. ES Modules (import/export) are the official standard — static, asynchronous-friendly, and tree-shakable (bundlers can remove unused exports, shrinking bundle size). In 2026, ESM is the default for new projects in both browsers and Node.js. If your back-end round goes deep into Node, revise our Node.js Interview Questions guide.

Q27. What is the difference between setTimeout, setInterval, and requestAnimationFrame?

Answer: setTimeout(fn, delay) runs a function once after a minimum delay; setInterval(fn, delay) runs it repeatedly. Both are macrotasks with no guarantee of exact timing — a famous question: setTimeout(fn, 0) does not run immediately; it waits for the call stack and microtasks to clear. requestAnimationFrame(fn) schedules a callback before the browser’s next repaint (~60fps), making it the correct choice for smooth animations because it pauses in background tabs and syncs with the display refresh.

Q28. Scenario: Your web page is loading slowly. How would you optimize JavaScript performance?

Answer: Structure your answer in layers. Loading: code-splitting and lazy loading with dynamic import(), defer/async script attributes, tree-shaking, and minification. Execution: debounce/throttle event handlers, avoid layout thrashing (batch DOM reads/writes), use event delegation, and move heavy computation to Web Workers. Network: cache API responses, use CDN, compress assets. Measurement: profile with Chrome DevTools Performance tab and Lighthouse before and after. Ending with “measure first, optimize second” demonstrates senior-level thinking.

Q29. Scenario: How would you handle errors in a large async JavaScript application?

Answer: Use try…catch around await calls with meaningful error messages, attach .catch() to promise chains, and add a global safety net: window.addEventListener(‘unhandledrejection’, handler) in browsers or process.on(‘unhandledRejection’) in Node.js. Centralize error handling in an API wrapper so every fetch call logs failures consistently, implement retry logic with exponential backoff for transient network errors, and report errors to monitoring tools like Sentry. This question tests production experience, not syntax.

Q30. What new JavaScript features should developers know in 2026?

Answer: Highlight recent ECMAScript additions: optional chaining (?.) and nullish coalescing (??) for safe property access; structuredClone() for deep copies; top-level await in modules; array methods like at(), findLast(), and immutable versions toSorted(), toReversed(), toSpliced(); Object.groupBy() for grouping data; and the using declaration for resource management. Showing awareness of the language’s evolution signals you are a developer who keeps learning — exactly what interviewers want to hire.


JavaScript Developer Salary in India (2026)

Experience LevelRoleAverage Salary (per annum)
0–2 years (Fresher)Junior Front-End / JS Developer₹3.5 – ₹6 LPA
2–5 yearsFront-End / Full-Stack Developer₹7 – ₹15 LPA
5–8 yearsSenior JavaScript Developer₹16 – ₹28 LPA
8+ yearsLead / Architect₹30 – ₹50+ LPA

Salaries vary by city (Bengaluru, Hyderabad, and Pune pay highest), company type (product companies pay 30–50% more than service companies), and framework expertise (React/Node skills command a premium).


7 Proven Tips to Crack Your JavaScript Interview

  1. Master the “big four” concepts first — closures, hoisting, event loop, and this. They appear in 90% of interviews.
  2. Practice output-prediction questions daily — JavaScript interviews love “what does this code print?” traps involving coercion and async ordering.
  3. Write polyfills by hand — implement map, filter, reduce, bind, debounce, and Promise.all from scratch at least twice each.
  4. Verbalize your thinking during coding rounds — interviewers grade your reasoning, not just the final answer.
  5. Build and explain one real project — be ready to discuss why you chose your architecture, how you handled errors, and what you would improve.
  6. Know your framework’s JavaScript underpinnings — React hooks rely on closures; Angular relies on RxJS observables. Connect the dots.
  7. Revise ES6+ features the night before — destructuring, spread/rest, template literals, modules, and optional chaining are guaranteed topics.

For database rounds that often follow JavaScript rounds, brush up with our Basic SQL Interview Questions guide, and if your stack includes Java back-ends, see Spring Boot Interview Questions.


Recommended Resources to Prepare Faster

ResourceTypeBest ForLink
JavaScript: The Definitive Guide (David Flanagan)BookComplete reference[Affiliate Link]
Eloquent JavaScriptBookConcept building[Affiliate Link]
Namaste JavaScript (Akshay Saini)Video CourseEvent loop & closures in depth[Affiliate Link]
JavaScript Algorithms BootcampOnline CourseCoding round preparation[Affiliate Link]
Frontend Interview Handbook ProCourseMock interviews & polyfills[Affiliate Link]

Affiliate Disclosure: Some links in this section are affiliate links. If you purchase through them, we may earn a small commission at no extra cost to you. We only recommend resources we genuinely believe will help your interview preparation.

For authoritative documentation, always cross-check concepts on MDN Web Docs and track new features at TC39 Proposals.


FAQ: JavaScript Interview Questions

Q1. Is JavaScript enough to get a job in 2026?

Core JavaScript plus one framework (React or Angular) plus basic HTML/CSS is enough for entry-level front-end roles. Adding Node.js opens full-stack positions, which pay significantly more.

Q2. How many days do I need to prepare for a JavaScript interview?

With consistent effort, 3–4 weeks is sufficient: week 1 for core concepts, week 2 for async JavaScript and ES6+, week 3 for coding practice and polyfills, and week 4 for mock interviews and projects revision.

Q3. What is the most asked JavaScript interview question?

“Explain closures with an example” is statistically the most asked question, followed closely by var/let/const differences, the event loop, and == vs ===.

Q4. Are JavaScript interviews harder for freshers or experienced developers?

Fresher interviews focus on fundamentals and output prediction. Experienced interviews add system design, performance optimization, framework internals, and architectural decisions — broader but built on the same core concepts.

Q5. Should I learn TypeScript before interviews?

For Angular roles, yes — TypeScript is mandatory. For React and Node roles, TypeScript is a strong plus in 2026, as most product companies have migrated. Learn JavaScript deeply first; TypeScript takes only 1–2 weeks afterward.


Conclusion

JavaScript interviews reward depth over breadth. Companies are not looking for developers who memorize 100 definitions — they want engineers who understand why closures retain memory, why promises beat callbacks, and why the event loop processes microtasks first. Work through all 30 questions in this guide, write the code yourself, practice polyfills until they feel natural, and walk into your interview with confidence.

Bookmark this page, share it with a friend preparing alongside you, and explore our other interview guides to prepare for every round of your dream job.

Disclaimer: This article is for educational purposes only. Interview questions, salary figures, and hiring trends mentioned here are indicative and may vary by company, location, and market conditions. Always research the specific company and role you are applying for.

Leave a Reply

Your email address will not be published. Required fields are marked *