JavaScript Interview Questions
This lesson explains JavaScript Interview Questions in JavaScript with beginner-friendly examples, practical use cases, and clear best practices.
Junior JavaScript Developer Interview Questions
| # | Question | Answer |
|---|---|---|
| 1 | What is JavaScript? | JavaScript is a scripting language used to create dynamic and interactive web pages. |
| 2 | What are JavaScript data types? | String, Number, Boolean, Null, Undefined, Symbol, BigInt, Object, Array, and Function. |
| 3 | Difference between var, let, and const? | var is function-scoped, let and const are block-scoped. const cannot be reassigned. |
| 4 | What is hoisting? | Hoisting means declarations are processed before code execution. |
| 5 | What is scope? | Scope defines where variables and functions can be accessed. |
| 6 | What is a function? | A reusable block of code designed to perform a task. |
| 7 | What is an arrow function? | A shorter function syntax introduced in ES6. |
| 8 | What is an array? | An ordered collection of values stored in a single variable. |
| 9 | What is an object? | A collection of key-value pairs. |
| 10 | What is DOM? | The Document Object Model represents an HTML page as a tree of objects. |
| 11 | How do you select an element by ID? | document.getElementById("title") |
| 12 | How do you add an event listener? | button.addEventListener("click", handleClick) |
| 13 | What is strict equality? | === compares both value and type. |
| 14 | What is type coercion? | Automatic conversion of one data type to another. |
| 15 | What is NaN? | NaN means Not-a-Number. |
| 16 | What is null? | An intentional empty value. |
| 17 | What is undefined? | A variable declared but not assigned a value. |
| 18 | What is JSON? | JSON is a lightweight data format used for data exchange. |
| 19 | What does JSON.parse do? | It converts a JSON string into a JavaScript object. |
| 20 | What does JSON.stringify do? | It converts a JavaScript object into a JSON string. |
| 21 | What is localStorage? | Browser storage that persists after page refresh and browser restart. |
| 22 | What is sessionStorage? | Browser storage that lasts only for the current tab session. |
| 23 | What is map? | map() transforms each array item and returns a
new array. |
| 24 | What is filter? | filter() returns array items that match a condition. |
| 25 | What is reduce? | reduce() combines array values into one result. |
| 26 | What is a callback? | A function passed as an argument to another function. |
| 27 | What is a promise? | An object representing a future success or failure value. |
| 28 | What is async/await? | A cleaner way to write promise-based asynchronous code. |
| 29 | What is fetch? | A browser API used to make HTTP requests. |
| 30 | What is try...catch? | A way to handle runtime errors safely. |
| 31 | What is template literal? | A string syntax using backticks and ${expression}. |
| 32 | What is destructuring? | Extracting values from arrays or objects into variables. |
| 33 | What is spread syntax? | It expands arrays, objects, or iterable values. |
| 34 | What is rest syntax? | It collects multiple values into one array or object. |
| 35 | What is event bubbling? | An event moves from child element to parent elements. |
| 36 | What is event delegation? | Handling events on a parent instead of every child element. |
| 37 | What is this keyword? | this refers to the object executing the function. |
| 38 | What is closure? | A function that remembers variables from its outer scope. |
| 39 | What is prototype? | An object from which another object inherits properties and methods. |
| 40 | What is class? | ES6 syntax for creating reusable object templates. |
| 41 | What is module? | A file that exports and imports reusable JavaScript code. |
| 42 | What is setTimeout? | Runs code once after a delay. |
| 43 | What is setInterval? | Runs code repeatedly after a delay. |
| 44 | What is innerHTML? | A property used to read or update HTML content. |
| 45 | What is textContent? | A safer way to update plain text content. |
| 46 | What is preventDefault? | Stops the browser's default behavior for an event. |
| 47 | What is browser API? | APIs provided by browsers, such as DOM, Fetch, Storage, and Clipboard. |
| 48 | What is accessibility? | Making web apps usable for people with disabilities. |
| 49 | What is XSS? | Cross-site scripting, a security issue caused by injecting unsafe scripts. |
| 50 | How do you debug JavaScript? | Use console logs, browser DevTools, breakpoints, and error messages. |
Senior JavaScript Developer Interview Questions
| # | Question | Answer |
|---|---|---|
| 1 | Explain the event loop. | The event loop coordinates the call stack, microtask queue, callback queue, and Web APIs. |
| 2 | Difference between microtask and macrotask? | Promises run in the microtask queue. Timers and events run in the callback queue. |
| 3 | Explain closure with use case. | Closures preserve outer variables and are used for private state, factories, and callbacks. |
| 4 | How do promises work? | A promise has pending, fulfilled, and rejected states. |
| 5 | Promise.all vs Promise.allSettled? | Promise.all fails fast. Promise.allSettled returns all outcomes. |
| 6 | Promise.race vs Promise.any? | race returns first settled promise. any returns first fulfilled promise. |
| 7 | What is debounce? | Debounce delays execution until the user stops triggering an event. |
| 8 | What is throttle? | Throttle limits execution to once per time interval. |
| 9 | How do you prevent memory leaks? | Clean event listeners, timers, intervals, subscriptions, observers, and large references. |
| 10 | What causes DOM performance issues? | Frequent layout reads/writes, large DOM updates, and unnecessary re-rendering. |
| 11 | How do you optimize JavaScript performance? | Code splitting, lazy loading, memoization, debouncing, caching, and reducing main-thread work. |
| 12 | How does prototypal inheritance work? | Objects inherit properties through a prototype chain. |
| 13 | Class vs prototype? | Classes are syntax over JavaScript prototype-based inheritance. |
| 14 | What is currying? | Transforming a function with multiple arguments into nested single-argument functions. |
| 15 | What is memoization? | Caching function results to avoid repeated expensive calculations. |
| 16 | What is composition? | Combining small reusable functions or objects to build behavior. |
| 17 | What is immutability? | Updating data by creating new values instead of mutating existing values. |
| 18 | How do you deep clone an object? | Use structuredClone() when supported, or custom
recursion for special cases. |
| 19 | What is CORS? | A browser security mechanism controlling cross-origin HTTP requests. |
| 20 | How do you prevent XSS? | Sanitize input, avoid unsafe innerHTML, use
escaping, CSP, and trusted rendering. |
| 21 | How do you secure localStorage? | Do not store sensitive tokens or secrets in browser storage. |
| 22 | How do you handle fetch errors? | Use try...catch and check response.ok. |
| 23 | How do you handle async cancellation? | Use AbortController for fetch and cleanup logic
for components. |
| 24 | What is event delegation? | Attach one listener to a parent and handle child events
using event.target. |
| 25 | What is lazy loading? | Loading resources only when needed. |
| 26 | What is code splitting? | Splitting JavaScript bundles into smaller chunks. |
| 27 | What is tree shaking? | Removing unused code during bundling. |
| 28 | What is module scope? | Variables inside ES modules are scoped to that module unless exported. |
| 29 | What is dynamic import? | Loading a module at runtime using import(). |
| 30 | How do you improve accessibility with JS? | Manage focus, ARIA states, keyboard navigation, and semantic behavior. |
| 31 | What is requestAnimationFrame? | A browser API for running animations before repaint. |
| 32 | What is IntersectionObserver? | An API for detecting when elements enter or leave the viewport. |
| 33 | What is Web Worker? | A browser API for running JavaScript in a background thread. |
| 34 | How do you debug memory leaks? | Use DevTools memory snapshots, allocation timelines, and listener inspection. |
| 35 | What is garbage collection? | Automatic memory cleanup for unreachable objects. |
| 36 | What is shadow DOM? | Encapsulated DOM used by Web Components. |
| 37 | What is custom element? | A reusable Web Component defined with JavaScript. |
| 38 | What is hydration? | Attaching JavaScript behavior to server-rendered HTML. |
| 39 | What is progressive enhancement? | Building core functionality first, then enhancing with JavaScript. |
| 40 | How do you handle large lists? | Use pagination, virtualization, lazy rendering, and efficient DOM updates. |
| 41 | How do you debug async bugs? | Use async stack traces, breakpoints, logging, and promise inspection. |
| 42 | What is race condition? | A bug caused by unpredictable order of asynchronous results. |
| 43 | How do you avoid race conditions? | Use cancellation, request IDs, locks, or latest-response checks. |
| 44 | How do you design reusable utilities? | Keep functions pure, small, typed, tested, and dependency-light. |
| 45 | What is pure function? | A function with no side effects and same output for same input. |
| 46 | What is side effect? | Changing external state, DOM, storage, network, or console output. |
| 47 | How do you handle errors globally? | Use error boundaries, logging services, window.onerror, and unhandledrejection. |
| 48 | How do you test JavaScript? | Use unit tests, integration tests, E2E tests, mocks, and coverage reports. |
| 49 | What is defensive coding? | Writing code that safely handles invalid, missing, or unexpected data. |
| 50 | How do you review JavaScript code? | Check readability, correctness, security, accessibility, performance, tests, and maintainability. |
JavaScript Architect / Frontend Architect Interview Questions
| # | Question | Answer |
|---|---|---|
| 1 | How do you architect a large JavaScript application? | Use modular architecture, feature boundaries, shared libraries, routing, state strategy, testing, performance budgets, and CI/CD. |
| 2 | How do you choose between SPA, SSR, SSG, and MPA? | Choose based on SEO, performance, personalization, routing complexity, and hosting needs. |
| 3 | What is micro frontend architecture? | Splitting frontend into independently owned, deployed, and composed applications. |
| 4 | When should you avoid micro frontends? | For small teams, simple apps, or when operational complexity outweighs benefits. |
| 5 | How do you manage shared dependencies? | Use version governance, peer dependencies, module federation sharing, and dependency review. |
| 6 | How do you define frontend architecture standards? | Create coding guidelines, design patterns, testing strategy, accessibility rules, and reusable templates. |
| 7 | How do you design a design system? | Use tokens, components, accessibility, documentation, versioning, governance, and adoption metrics. |
| 8 | How do you ensure accessibility at scale? | Use semantic HTML, ARIA rules, keyboard support, automated checks, manual testing, and design reviews. |
| 9 | How do you set performance budgets? | Define limits for bundle size, LCP, INP, CLS, JS execution time, and network requests. |
| 10 | How do you reduce JavaScript bundle size? | Tree shaking, code splitting, lazy loading, dependency audits, and removing unused code. |
| 11 | How do you handle state management architecture? | Separate local, shared, server, URL, and persistent state. |
| 12 | How do you design API integration? | Use typed clients, error handling, retries, caching, cancellation, and consistent response contracts. |
| 13 | How do you secure frontend apps? | CSP, input sanitization, token safety, dependency scanning, HTTPS, secure headers, and XSS prevention. |
| 14 | How do you handle authentication architecture? | Use secure token flow, refresh strategy, route guards, session expiry, and server-side validation. |
| 15 | How do you prevent XSS at scale? | Sanitize data, avoid unsafe HTML, use CSP, encode output, and review third-party scripts. |
| 16 | How do you handle observability? | Use logs, metrics, traces, error reporting, performance monitoring, and user session diagnostics. |
| 17 | How do you manage releases? | Use CI/CD, automated tests, feature flags, canary releases, rollbacks, and monitoring. |
| 18 | What is a feature flag? | A runtime switch to enable or disable features without redeploying. |
| 19 | How do you handle browser compatibility? | Use baseline support policy, polyfills, transpilation, progressive enhancement, and testing matrix. |
| 20 | How do you manage third-party scripts? | Audit security, performance impact, loading strategy, ownership, and fallback behavior. |
| 21 | How do you handle dependency risk? | Use lockfiles, audits, license checks, security scanning, and update policies. |
| 22 | How do you create frontend coding standards? | Use ESLint, Prettier, TypeScript rules, architecture docs, examples, and code review checklists. |
| 23 | How do you scale frontend teams? | Define ownership, boundaries, shared platforms, documentation, templates, and governance. |
| 24 | How do you handle cross-team component reuse? | Use design system packages, documentation, versioning, changelogs, and migration guides. |
| 25 | How do you design error handling architecture? | Centralize logging, standardize error models, user-friendly messages, retries, and alerting. |
| 26 | How do you handle offline support? | Use service workers, cache strategies, IndexedDB, sync queues, and clear offline UI. |
| 27 | How do you choose storage? | Use memory for temporary state, localStorage for simple preferences, IndexedDB for large data, server for sensitive data. |
| 28 | How do you build resilient UI? | Handle loading, empty, error, partial, offline, and timeout states. |
| 29 | How do you design module boundaries? | Separate features by domain, avoid circular dependencies, expose stable APIs. |
| 30 | How do you prevent memory leaks in architecture? | Standardize cleanup for listeners, intervals, observers, subscriptions, and caches. |
| 31 | What is dependency inversion in frontend? | High-level modules depend on abstractions, not concrete implementations. |
| 32 | What design patterns are useful in JavaScript? | Module, Factory, Observer, Strategy, Adapter, Facade, Singleton, Command, and Pub/Sub. |
| 33 | How do you handle legacy migration? | Use strangler pattern, wrappers, incremental refactoring, tests, and compatibility layers. |
| 34 | How do you improve Core Web Vitals? | Optimize images, reduce JavaScript, lazy load, cache, SSR, split code, and reduce layout shifts. |
| 35 | How do you architect forms? | Use validation schema, accessibility, error summary, controlled state, and server validation. |
| 36 | How do you handle internationalization? | Use message catalogs, formatting APIs, locale routing, RTL support, and translation workflows. |
| 37 | How do you handle theming? | Use design tokens, CSS variables, theme provider, and accessible contrast rules. |
| 38 | How do you handle analytics safely? | Track meaningful events, respect privacy, avoid PII, and measure performance impact. |
| 39 | How do you define a frontend platform? | Reusable tooling, patterns, libraries, observability, design system, testing, and deployment standards. |
| 40 | How do you review architecture decisions? | Use ADRs, tradeoff analysis, proof of concepts, metrics, and stakeholder review. |
| 41 | What is an ADR? | An Architecture Decision Record documenting context, decision, alternatives, and consequences. |
| 42 | How do you choose framework vs vanilla JS? | Consider team skill, complexity, rendering needs, ecosystem, performance, and maintainability. |
| 43 | How do you handle shared UI state across MFEs? | Prefer URL, events, shared services, or shell-owned state with clear contracts. |
| 44 | How do you handle versioning? | Use semantic versioning, changelogs, migration guides, and compatibility policies. |
| 45 | How do you design testing strategy? | Use unit, integration, visual, accessibility, contract, and E2E tests. |
| 46 | How do you support developer experience? | Fast builds, templates, docs, CLI tools, local mocks, linting, and good error messages. |
| 47 | How do you handle frontend governance? | Define standards, review boards, automation, metrics, and contribution workflows. |
| 48 | How do you evaluate architecture success? | Measure delivery speed, quality, performance, accessibility, reliability, adoption, and cost. |
| 49 | How do you handle critical incidents? | Detect, rollback, communicate, mitigate, investigate, and document learnings. |
| 50 | What makes a good frontend architect? | Technical depth, system thinking, communication, standards, mentorship, tradeoff analysis, and delivery focus. |
30 JavaScript Coding Interview Questions with Solutions
1. Reverse a String
function reverseString(str) {
return str.split("").reverse().join("");
}
console.log(reverseString("hello")); 2. Check Palindrome
function isPalindrome(str) {
const clean = str.toLowerCase().replace(/[^a-z0-9]/g, "");
return clean === clean.split("").reverse().join("");
} 3. Find Largest Number
function findLargest(numbers) {
return Math.max(...numbers);
} 4. Remove Duplicates
function removeDuplicates(arr) {
return [...new Set(arr)];
} 5. Count Vowels
function countVowels(str) {
return str.match(/[aeiou]/gi)?.length || 0;
} 6. FizzBuzz
function fizzBuzz(n) {
for (let i = 1; i <= n; i++) {
if (i % 15 === 0) console.log("FizzBuzz");
else if (i % 3 === 0) console.log("Fizz");
else if (i % 5 === 0) console.log("Buzz");
else console.log(i);
}
} 7. Factorial
function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
} 8. Fibonacci
function fibonacci(n) {
const result = [0, 1];
for (let i = 2; i < n; i++) {
result.push(result[i - 1] + result[i - 2]);
}
return result.slice(0, n);
} 9. Flatten Array
function flattenArray(arr) {
return arr.flat(Infinity);
} 10. Deep Clone Object
function deepClone(value) {
return structuredClone(value);
} 11. Debounce
function debounce(fn, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(function() {
fn.apply(this, args);
}, delay);
};
} 12. Throttle
function throttle(fn, delay) {
let lastTime = 0;
return function(...args) {
const now = Date.now();
if (now - lastTime >= delay) {
lastTime = now;
fn.apply(this, args);
}
};
} 13. Memoization
function memoize(fn) {
const cache = {};
return function(value) {
if (cache[value]) return cache[value];
cache[value] = fn(value);
return cache[value];
};
} 14. Curry Function
function curryAdd(a) {
return function(b) {
return a + b;
};
} 15. Group Array by Key
function groupBy(items, key) {
return items.reduce(function(result, item) {
const group = item[key];
if (!result[group]) {
result[group] = [];
}
result[group].push(item);
return result;
}, {});
} 16. Custom map()
Array.prototype.customMap = function(callback) {
const result = [];
for (let i = 0; i < this.length; i++) {
result.push(callback(this[i], i, this));
}
return result;
}; 17. Custom filter()
Array.prototype.customFilter = function(callback) {
const result = [];
for (let i = 0; i < this.length; i++) {
if (callback(this[i], i, this)) {
result.push(this[i]);
}
}
return result;
}; 18. Custom reduce()
Array.prototype.customReduce = function(callback, initialValue) {
let accumulator = initialValue;
for (let i = 0; i < this.length; i++) {
accumulator = callback(accumulator, this[i], i, this);
}
return accumulator;
}; 19. Promise.all Polyfill
function promiseAll(promises) {
return new Promise(function(resolve, reject) {
const results = [];
let completed = 0;
promises.forEach(function(promise, index) {
Promise.resolve(promise)
.then(function(value) {
results[index] = value;
completed++;
if (completed === promises.length) {
resolve(results);
}
})
.catch(reject);
});
});
} 20. Event Emitter
class EventEmitter {
constructor() {
this.events = {};
}
on(event, callback) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(callback);
}
emit(event, data) {
if (this.events[event]) {
this.events[event].forEach(function(callback) {
callback(data);
});
}
}
} 21. Check Anagram
function isAnagram(a, b) {
return a.split("").sort().join("") === b.split("").sort().join("");
} 22. Capitalize Words
function capitalizeWords(str) {
return str
.split(" ")
.map(function(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
})
.join(" ");
} 23. Find Missing Number
function findMissingNumber(arr, n) {
const expected = (n * (n + 1)) / 2;
const actual = arr.reduce((sum, num) => sum + num, 0);
return expected - actual;
} 24. Count Occurrences
function countOccurrences(arr) {
return arr.reduce(function(result, item) {
result[item] = (result[item] || 0) + 1;
return result;
}, {});
} 25. Merge Objects
function mergeObjects(a, b) {
return { ...a, ...b };
} 26. Safe JSON Parse
function safeJsonParse(text) {
try {
return JSON.parse(text);
} catch (error) {
return null;
}
} 27. Retry Async Function
async function retry(fn, attempts) {
for (let i = 0; i < attempts; i++) {
try {
return await fn();
} catch (error) {
if (i === attempts - 1) throw error;
}
}
} 28. Timeout Promise
function delay(ms) {
return new Promise(function(resolve) {
setTimeout(resolve, ms);
});
} 29. Toggle Class
function toggleActive(element) {
element.classList.toggle("active");
} 30. Validate Email
function validateEmail(email) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
} JavaScript Interview Questions FAQ
How many JavaScript questions should I prepare?
Prepare core theory, coding, debugging, async JavaScript, DOM, browser APIs, performance, security, and real-world scenario questions.
What should junior developers focus on?
Variables, data types, functions, arrays, objects, DOM, events, JSON, fetch, promises, and basic coding problems.
What should senior developers focus on?
Closures, prototypes, event loop, memory leaks, performance, security, testing, async patterns, design patterns, and debugging.
What should architects focus on?
System design, frontend architecture, micro frontends, design systems, scalability, accessibility, performance budgets, governance, and observability.
Are coding questions important?
Yes. Coding questions test problem-solving, JavaScript fundamentals, debugging, edge cases, and clean code.
Conclusion
This JavaScript interview guide covers junior, senior, and architect-level questions with answers, coding examples, debugging topics, async JavaScript, DOM, browser APIs, performance, security, accessibility, modules, closures, prototypes, promises, async/await, and design patterns.
To prepare effectively, practice small examples, explain concepts in your own words, debug real code, and build projects that use APIs, forms, DOM updates, async workflows, and reusable JavaScript patterns.