Skip to content

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
1What is JavaScript?JavaScript is a scripting language used to create dynamic and interactive web pages.
2What are JavaScript data types?String, Number, Boolean, Null, Undefined, Symbol, BigInt, Object, Array, and Function.
3Difference between var, let, and const?var is function-scoped, let and const are block-scoped. const cannot be reassigned.
4What is hoisting?Hoisting means declarations are processed before code execution.
5What is scope?Scope defines where variables and functions can be accessed.
6What is a function?A reusable block of code designed to perform a task.
7What is an arrow function?A shorter function syntax introduced in ES6.
8What is an array?An ordered collection of values stored in a single variable.
9What is an object?A collection of key-value pairs.
10What is DOM?The Document Object Model represents an HTML page as a tree of objects.
11How do you select an element by ID?document.getElementById("title")
12How do you add an event listener?button.addEventListener("click", handleClick)
13What is strict equality?=== compares both value and type.
14What is type coercion?Automatic conversion of one data type to another.
15What is NaN?NaN means Not-a-Number.
16What is null?An intentional empty value.
17What is undefined?A variable declared but not assigned a value.
18What is JSON?JSON is a lightweight data format used for data exchange.
19What does JSON.parse do?It converts a JSON string into a JavaScript object.
20What does JSON.stringify do?It converts a JavaScript object into a JSON string.
21What is localStorage?Browser storage that persists after page refresh and browser restart.
22What is sessionStorage?Browser storage that lasts only for the current tab session.
23What is map?map() transforms each array item and returns a new array.
24What is filter?filter() returns array items that match a condition.
25What is reduce?reduce() combines array values into one result.
26What is a callback?A function passed as an argument to another function.
27What is a promise?An object representing a future success or failure value.
28What is async/await?A cleaner way to write promise-based asynchronous code.
29What is fetch?A browser API used to make HTTP requests.
30What is try...catch?A way to handle runtime errors safely.
31What is template literal?A string syntax using backticks and ${expression}.
32What is destructuring?Extracting values from arrays or objects into variables.
33What is spread syntax?It expands arrays, objects, or iterable values.
34What is rest syntax?It collects multiple values into one array or object.
35What is event bubbling?An event moves from child element to parent elements.
36What is event delegation?Handling events on a parent instead of every child element.
37What is this keyword?this refers to the object executing the function.
38What is closure?A function that remembers variables from its outer scope.
39What is prototype?An object from which another object inherits properties and methods.
40What is class?ES6 syntax for creating reusable object templates.
41What is module?A file that exports and imports reusable JavaScript code.
42What is setTimeout?Runs code once after a delay.
43What is setInterval?Runs code repeatedly after a delay.
44What is innerHTML?A property used to read or update HTML content.
45What is textContent?A safer way to update plain text content.
46What is preventDefault?Stops the browser's default behavior for an event.
47What is browser API?APIs provided by browsers, such as DOM, Fetch, Storage, and Clipboard.
48What is accessibility?Making web apps usable for people with disabilities.
49What is XSS?Cross-site scripting, a security issue caused by injecting unsafe scripts.
50How do you debug JavaScript?Use console logs, browser DevTools, breakpoints, and error messages.

Senior JavaScript Developer Interview Questions

# Question Answer
1Explain the event loop.The event loop coordinates the call stack, microtask queue, callback queue, and Web APIs.
2Difference between microtask and macrotask?Promises run in the microtask queue. Timers and events run in the callback queue.
3Explain closure with use case.Closures preserve outer variables and are used for private state, factories, and callbacks.
4How do promises work?A promise has pending, fulfilled, and rejected states.
5Promise.all vs Promise.allSettled?Promise.all fails fast. Promise.allSettled returns all outcomes.
6Promise.race vs Promise.any?race returns first settled promise. any returns first fulfilled promise.
7What is debounce?Debounce delays execution until the user stops triggering an event.
8What is throttle?Throttle limits execution to once per time interval.
9How do you prevent memory leaks?Clean event listeners, timers, intervals, subscriptions, observers, and large references.
10What causes DOM performance issues?Frequent layout reads/writes, large DOM updates, and unnecessary re-rendering.
11How do you optimize JavaScript performance?Code splitting, lazy loading, memoization, debouncing, caching, and reducing main-thread work.
12How does prototypal inheritance work?Objects inherit properties through a prototype chain.
13Class vs prototype?Classes are syntax over JavaScript prototype-based inheritance.
14What is currying?Transforming a function with multiple arguments into nested single-argument functions.
15What is memoization?Caching function results to avoid repeated expensive calculations.
16What is composition?Combining small reusable functions or objects to build behavior.
17What is immutability?Updating data by creating new values instead of mutating existing values.
18How do you deep clone an object?Use structuredClone() when supported, or custom recursion for special cases.
19What is CORS?A browser security mechanism controlling cross-origin HTTP requests.
20How do you prevent XSS?Sanitize input, avoid unsafe innerHTML, use escaping, CSP, and trusted rendering.
21How do you secure localStorage?Do not store sensitive tokens or secrets in browser storage.
22How do you handle fetch errors?Use try...catch and check response.ok.
23How do you handle async cancellation?Use AbortController for fetch and cleanup logic for components.
24What is event delegation?Attach one listener to a parent and handle child events using event.target.
25What is lazy loading?Loading resources only when needed.
26What is code splitting?Splitting JavaScript bundles into smaller chunks.
27What is tree shaking?Removing unused code during bundling.
28What is module scope?Variables inside ES modules are scoped to that module unless exported.
29What is dynamic import?Loading a module at runtime using import().
30How do you improve accessibility with JS?Manage focus, ARIA states, keyboard navigation, and semantic behavior.
31What is requestAnimationFrame?A browser API for running animations before repaint.
32What is IntersectionObserver?An API for detecting when elements enter or leave the viewport.
33What is Web Worker?A browser API for running JavaScript in a background thread.
34How do you debug memory leaks?Use DevTools memory snapshots, allocation timelines, and listener inspection.
35What is garbage collection?Automatic memory cleanup for unreachable objects.
36What is shadow DOM?Encapsulated DOM used by Web Components.
37What is custom element?A reusable Web Component defined with JavaScript.
38What is hydration?Attaching JavaScript behavior to server-rendered HTML.
39What is progressive enhancement?Building core functionality first, then enhancing with JavaScript.
40How do you handle large lists?Use pagination, virtualization, lazy rendering, and efficient DOM updates.
41How do you debug async bugs?Use async stack traces, breakpoints, logging, and promise inspection.
42What is race condition?A bug caused by unpredictable order of asynchronous results.
43How do you avoid race conditions?Use cancellation, request IDs, locks, or latest-response checks.
44How do you design reusable utilities?Keep functions pure, small, typed, tested, and dependency-light.
45What is pure function?A function with no side effects and same output for same input.
46What is side effect?Changing external state, DOM, storage, network, or console output.
47How do you handle errors globally?Use error boundaries, logging services, window.onerror, and unhandledrejection.
48How do you test JavaScript?Use unit tests, integration tests, E2E tests, mocks, and coverage reports.
49What is defensive coding?Writing code that safely handles invalid, missing, or unexpected data.
50How do you review JavaScript code?Check readability, correctness, security, accessibility, performance, tests, and maintainability.

JavaScript Architect / Frontend Architect Interview Questions

# Question Answer
1How do you architect a large JavaScript application?Use modular architecture, feature boundaries, shared libraries, routing, state strategy, testing, performance budgets, and CI/CD.
2How do you choose between SPA, SSR, SSG, and MPA?Choose based on SEO, performance, personalization, routing complexity, and hosting needs.
3What is micro frontend architecture?Splitting frontend into independently owned, deployed, and composed applications.
4When should you avoid micro frontends?For small teams, simple apps, or when operational complexity outweighs benefits.
5How do you manage shared dependencies?Use version governance, peer dependencies, module federation sharing, and dependency review.
6How do you define frontend architecture standards?Create coding guidelines, design patterns, testing strategy, accessibility rules, and reusable templates.
7How do you design a design system?Use tokens, components, accessibility, documentation, versioning, governance, and adoption metrics.
8How do you ensure accessibility at scale?Use semantic HTML, ARIA rules, keyboard support, automated checks, manual testing, and design reviews.
9How do you set performance budgets?Define limits for bundle size, LCP, INP, CLS, JS execution time, and network requests.
10How do you reduce JavaScript bundle size?Tree shaking, code splitting, lazy loading, dependency audits, and removing unused code.
11How do you handle state management architecture?Separate local, shared, server, URL, and persistent state.
12How do you design API integration?Use typed clients, error handling, retries, caching, cancellation, and consistent response contracts.
13How do you secure frontend apps?CSP, input sanitization, token safety, dependency scanning, HTTPS, secure headers, and XSS prevention.
14How do you handle authentication architecture?Use secure token flow, refresh strategy, route guards, session expiry, and server-side validation.
15How do you prevent XSS at scale?Sanitize data, avoid unsafe HTML, use CSP, encode output, and review third-party scripts.
16How do you handle observability?Use logs, metrics, traces, error reporting, performance monitoring, and user session diagnostics.
17How do you manage releases?Use CI/CD, automated tests, feature flags, canary releases, rollbacks, and monitoring.
18What is a feature flag?A runtime switch to enable or disable features without redeploying.
19How do you handle browser compatibility?Use baseline support policy, polyfills, transpilation, progressive enhancement, and testing matrix.
20How do you manage third-party scripts?Audit security, performance impact, loading strategy, ownership, and fallback behavior.
21How do you handle dependency risk?Use lockfiles, audits, license checks, security scanning, and update policies.
22How do you create frontend coding standards?Use ESLint, Prettier, TypeScript rules, architecture docs, examples, and code review checklists.
23How do you scale frontend teams?Define ownership, boundaries, shared platforms, documentation, templates, and governance.
24How do you handle cross-team component reuse?Use design system packages, documentation, versioning, changelogs, and migration guides.
25How do you design error handling architecture?Centralize logging, standardize error models, user-friendly messages, retries, and alerting.
26How do you handle offline support?Use service workers, cache strategies, IndexedDB, sync queues, and clear offline UI.
27How do you choose storage?Use memory for temporary state, localStorage for simple preferences, IndexedDB for large data, server for sensitive data.
28How do you build resilient UI?Handle loading, empty, error, partial, offline, and timeout states.
29How do you design module boundaries?Separate features by domain, avoid circular dependencies, expose stable APIs.
30How do you prevent memory leaks in architecture?Standardize cleanup for listeners, intervals, observers, subscriptions, and caches.
31What is dependency inversion in frontend?High-level modules depend on abstractions, not concrete implementations.
32What design patterns are useful in JavaScript?Module, Factory, Observer, Strategy, Adapter, Facade, Singleton, Command, and Pub/Sub.
33How do you handle legacy migration?Use strangler pattern, wrappers, incremental refactoring, tests, and compatibility layers.
34How do you improve Core Web Vitals?Optimize images, reduce JavaScript, lazy load, cache, SSR, split code, and reduce layout shifts.
35How do you architect forms?Use validation schema, accessibility, error summary, controlled state, and server validation.
36How do you handle internationalization?Use message catalogs, formatting APIs, locale routing, RTL support, and translation workflows.
37How do you handle theming?Use design tokens, CSS variables, theme provider, and accessible contrast rules.
38How do you handle analytics safely?Track meaningful events, respect privacy, avoid PII, and measure performance impact.
39How do you define a frontend platform?Reusable tooling, patterns, libraries, observability, design system, testing, and deployment standards.
40How do you review architecture decisions?Use ADRs, tradeoff analysis, proof of concepts, metrics, and stakeholder review.
41What is an ADR?An Architecture Decision Record documenting context, decision, alternatives, and consequences.
42How do you choose framework vs vanilla JS?Consider team skill, complexity, rendering needs, ecosystem, performance, and maintainability.
43How do you handle shared UI state across MFEs?Prefer URL, events, shared services, or shell-owned state with clear contracts.
44How do you handle versioning?Use semantic versioning, changelogs, migration guides, and compatibility policies.
45How do you design testing strategy?Use unit, integration, visual, accessibility, contract, and E2E tests.
46How do you support developer experience?Fast builds, templates, docs, CLI tools, local mocks, linting, and good error messages.
47How do you handle frontend governance?Define standards, review boards, automation, metrics, and contribution workflows.
48How do you evaluate architecture success?Measure delivery speed, quality, performance, accessibility, reliability, adoption, and cost.
49How do you handle critical incidents?Detect, rollback, communicate, mitigate, investigate, and document learnings.
50What 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.