Javascript Interview Questions

Updated 5/11/2026

JavaScript Interview Questions and Answers (2026)

Preparing for a JavaScript interview? You've landed in the right place. This comprehensive guide covers the most frequently asked JavaScript interview questions and answers for beginners, intermediate, and advanced developers in 2026.

Whether you're a fresher applying for your first frontend role or an experienced developer targeting senior positions at top tech companies, these questions will help you confidently tackle topics like closures, prototypes, async/await, the event loop, ES6+ features, and more.

What You'll Learn

  • Core JavaScript concepts asked in every technical interview
  • DOM manipulation, event handling, and browser APIs
  • Functions, closures, scope, and hoisting
  • Asynchronous JavaScript — callbacks, Promises, async/await
  • ES6+ features: arrow functions, destructuring, spread/rest, modules
  • Performance optimization and security best practices
  • Hands-on coding challenges with solutions

Why JavaScript Skills Matter in Interviews

JavaScript is the world's most widely used programming language, powering everything from interactive user interfaces to full-stack applications with Node.js. Interviewers test JavaScript deeply because it reveals how well a candidate understands runtime behavior, asynchronous programming, and language quirks that real production code depends on.

Mastering these questions will prepare you to:

  • Ace technical screens at startups and FAANG companies
  • Build full-fledged applications with React, Vue, and Angular
  • Work with modern frameworks and backend runtimes
  • Write performant, secure, and maintainable JavaScript code

Beginner-Level Questions

JavaScript Basics

1. What is JavaScript?

JavaScript is a lightweight, interpreted, high-level programming language with first-class functions. Originally created for browsers, it now runs on servers (Node.js), mobile apps, and desktop applications. It's prototype-based, multi-paradigm, single-threaded, and dynamically typed.

2. What are the differences between JavaScript and Java?

Despite their similar names, they're very different languages. Java is statically typed, compiled, and class-based. JavaScript is dynamically typed, interpreted, and prototype-based. Java requires explicit type declarations; JavaScript infers types at runtime.

3. What are the different data types in JavaScript?

JavaScript has 8 data types: 7 primitives (String, Number, BigInt, Boolean, undefined, null, Symbol) and 1 non-primitive (Object, which includes arrays, functions, and regular objects).

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

== (loose equality) compares values after type coercion — 0 == "0" is true. === (strict equality) compares both value AND type without coercion — 0 === "0" is false. Always prefer === to avoid unexpected bugs.

5. What is the difference between null and undefined?

undefined means a variable has been declared but not yet assigned a value. null is an intentional assignment meaning "no value". typeof undefined returns "undefined", while typeof null returns "object" (a known quirk). null == undefined is true, but null === undefined is false.

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

var is function-scoped, hoisted and initialized as undefined, and can be re-declared. let is block-scoped, in the Temporal Dead Zone until declared, cannot be re-declared in the same scope. const is block-scoped, must be initialized at declaration, cannot be reassigned (but objects it holds can be mutated).

7. What is hoisting in JavaScript?

Hoisting is JavaScript's behavior of moving declarations to the top of their scope before execution. var declarations are hoisted and initialized as undefined. Function declarations are fully hoisted (both declaration and body). let and const are hoisted but remain in the Temporal Dead Zone — accessing them before their declaration line throws a ReferenceError.

8. What is scope in JavaScript?

Scope determines where variables and functions are accessible. JavaScript has: Global scope (accessible everywhere), Function scope (accessible within the function), Block scope (let/const inside {}), and Module scope. Variables look up the scope chain from inner to outer until found.

9. What is a closure in JavaScript?

A closure is a function that retains access to its outer (lexical) scope even after the outer function has finished executing. The inner function "closes over" variables from its parent.

function counter() {
  let count = 0;
  return () => ++count;
}
const increment = counter();
increment(); // 1
increment(); // 2

10. What is the this keyword in JavaScript?

this refers to the object currently executing the function. Its value depends on the call site: in a method, this is the object; in a regular function, this is the global object (or undefined in strict mode); in an arrow function, this is inherited from the outer scope; in a constructor, this is the new object.


DOM Manipulation

11. What is the DOM (Document Object Model)?

The DOM is a programming interface for HTML/XML documents. It represents the page as a tree of nodes — document at the root, <html>, <body>, elements, attributes, and text nodes as children. JavaScript uses the DOM to dynamically read and modify page content, structure, and styles.

12. What is the difference between innerHTML and textContent?

innerHTML parses and sets HTML markup; risk of XSS if used with user data. textContent treats content as plain text (HTML tags are escaped); faster; no XSS risk. Always use textContent when displaying user-provided data.

13. What is event bubbling and event capturing?

Event propagation has 3 phases: Capturing (window → target), Target, and Bubbling (target → window). By default, listeners use the bubbling phase. Pass { capture: true } to addEventListener for the capturing phase. event.stopPropagation() stops further propagation.

14. Explain event delegation in JavaScript

Event delegation places one listener on a parent element to handle events from all children using bubbling. Instead of adding listeners to each item:

parent.addEventListener("click", e => {
  if (e.target.matches("li")) {
    // handle click
  }
});

Benefits: fewer listeners (memory efficient), works for dynamically added elements.


Functions

15. What is a higher-order function?

A higher-order function either takes a function as an argument or returns a function. Examples: Array.prototype.map(callback), filter, reduce, setTimeout(fn, delay). Custom examples: debounce(fn), throttle(fn), memoize(fn).

16. What is a callback function?

A callback is a function passed as an argument to another function to be executed later. Synchronous callbacks: [1,2,3].forEach(cb). Asynchronous callbacks: setTimeout(cb, 1000), fs.readFile(path, cb). Heavy nesting of async callbacks creates "callback hell" — solved by Promises and async/await.

17. What is a pure function?

A pure function always returns the same output for the same inputs (deterministic) and has no side effects (no external state mutation, no API calls, no logging).

const add = (a, b) => a + b; // pure
Math.random(); // impure
Date.now(); // impure

Pure functions are predictable, testable, and safe to memoize.

18. What is currying in JavaScript?

Currying transforms a function with multiple arguments into a sequence of single-argument functions. add(2, 3) becomes add(2)(3).

const multiply = a => b => a * b;
const double = multiply(2);
double(5); // 10

Enables partial application and is widely used in functional programming libraries.


Arrays and Objects

19. What is the difference between slice and splice?

Aspect slice() splice()
Mutates original No (non-destructive) Yes (destructive)
Returns New array with extracted portion Array of removed elements
Use case Extracting portions Inserting, removing, or replacing

20. What are Sets and Maps and how are they used?

Set stores unique values of any type, iterable with for...of. Methods: add, has, delete, size.

Map stores key-value pairs where keys can be any type, maintains insertion order. Methods: set, get, has, delete, size.


Intermediate-Level Questions

Asynchronous JavaScript

21. What is the event loop in JavaScript?

The event loop enables non-blocking I/O in single-threaded JavaScript. It monitors the call stack and task queues. When the stack is empty, it picks tasks from: (1) Microtask queue (Promises — highest priority, drained completely first), (2) Macrotask queue (setTimeout, setInterval, I/O). This cycle repeats continuously.

22. What are Promises and how do they work?

A Promise wraps an async operation and eventually provides a result. States: pending → fulfilled or rejected.

new Promise((resolve, reject) => {
  // async work
  resolve(value); // or reject(error)
})
.then(result => { /* success */ })
.catch(error => { /* failure */ })
.finally(() => { /* cleanup */ });

23. What is the use of Promise.all()?

Promise.all([p1, p2, p3]) runs promises in parallel and resolves when ALL resolve (returns array of results in order). Fails fast — rejects immediately if ANY promise rejects.

const [user, posts] = await Promise.all([
  fetchUser(),
  fetchPosts()
]);

24. What is async/await and how does it simplify asynchronous code?

async functions always return a Promise. await pauses execution inside the async function until a Promise resolves, making async code look synchronous.

async function fetchData() {
  try {
    const response = await fetch(url);
    const data = await response.json();
    return data;
  } catch(e) {
    console.error(e);
  }
}

ES6+ Features

25. What are template literals in JavaScript?

Template literals use backticks and support: multi-line strings, string interpolation, and tagged templates.

const name = "Alice";
const msg = `Hello ${name},
you have ${msgs.length} messages.`;

26. What is destructuring assignment in JavaScript?

Extracting values from arrays or properties from objects into named variables.

// Array destructuring
const [first, , third] = [1, 2, 3];

// Object destructuring
const { name, age = 0 } = person;

// Renaming
const { firstName: name } = user;

27. What is the rest parameter and spread operator?

Both use ... but serve different purposes.

Rest parameter collects multiple function arguments into an array:

function sum(...nums) {
  return nums.reduce((a,b) => a+b, 0);
}

Spread operator expands an iterable:

Math.max(...[1,2,3]);
const merged = { ...obj1, ...obj2 };
const copy = [...arr];

Advanced-Level Questions

Performance and Optimization

28. What is tree shaking in JavaScript?

Tree shaking eliminates dead code (unused exports) from the final bundle during build. Relies on ES6 static import/export syntax that bundlers (Webpack, Rollup) can statically analyze. CommonJS require() is dynamic and cannot be tree-shaken effectively. Reduces bundle size significantly.

29. What is the difference between debounce and throttle?

Aspect Debounce Throttle
Execution Only after N ms of silence At most once per N ms
Ideal for Search input (wait for user to stop typing) Scroll/resize handlers (steady rate)
Behavior Delays execution until activity stops Executes at regular intervals

30. What are Web Workers and how can they improve performance?

Web Workers run scripts on separate threads, off the main thread. Use for CPU-intensive tasks: image processing, large data parsing, cryptography. Communicate via postMessage/onmessage. No DOM access. Service Workers are a special type for caching and offline functionality (PWAs).


Security

31. What is Cross-Site Scripting (XSS) and how can you prevent it?

XSS injects malicious scripts into pages viewed by others.

Prevention:

  • Escape/sanitize user input before rendering
  • Use textContent not innerHTML for user data
  • Set Content-Security-Policy headers
  • Use HttpOnly cookies
  • Validate server-side

React escapes JSX output by default.

32. What is "use strict" in JavaScript?

"use strict" enables strict mode: throws on undeclared variables, prevents this from being global in regular functions, disallows duplicate parameter names, throws on assignment to read-only properties. All ES6 modules and classes use strict mode automatically.


Coding Challenges

Beginner

33. Write a function to reverse a string

function reverseString(str) {
  return str.split('').reverse().join('');
}

// Or using spread operator:
const reverse = (str) => [...str].reverse().join('');

34. Write a function to check if a string is a palindrome

function isPalindrome(str) {
  const cleaned = str.toLowerCase()
    .replace(/[^a-z0-9]/g, '');
  return cleaned === [...cleaned].reverse().join('');
}

Intermediate

35. Write a function to implement a debounce function

function debounce(fn, delay) {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}

36. Write a function to flatten a nested array

// Modern:
const flatten = (arr) => arr.flat(Infinity);

// Recursive:
function flatten(arr) {
  return arr.reduce(
    (acc, val) => Array.isArray(val) 
      ? acc.concat(flatten(val)) 
      : acc.concat(val),
    []
  );
}

Advanced

37. Write a polyfill for Promise.all

Promise.myAll = function (promises) {
  return new Promise((resolve, reject) => {
    const results = [];
    let remaining = promises.length;
    if (remaining === 0) return resolve([]);
    
    promises.forEach((p, i) => {
      Promise.resolve(p)
        .then((val) => {
          results[i] = val;
          if (--remaining === 0) resolve(results);
        })
        .catch(reject);
    });
  });
};

Best Practices and Debugging

38. How do you debug JavaScript code?

Use browser DevTools: set breakpoints in the Sources tab, step through code, inspect variables in scope, watch expressions, view the call stack. Use console.log, console.error, console.table, console.time for logging. debugger; statement triggers a breakpoint.

39. What are some best practices for writing clean JavaScript code?

  • Use const/let appropriately (prefer const)
  • Use descriptive variable and function names
  • Keep functions small and focused (single responsibility)
  • Handle errors explicitly
  • Avoid deeply nested code (use early returns)
  • Use ES6+ features for cleaner syntax
  • Write tests
  • Avoid global variables
  • Use strict mode
  • Consistent formatting (Prettier/ESLint)

Practice Makes Perfect! This guide covers a wide range of JavaScript interview questions from basics to advanced topics. The key to success is hands-on practice, understanding the reasoning behind each answer, and being able to explain your thinking process clearly during interviews.

Additional Resources

Best of luck with your JavaScript interviews! Remember: understanding concepts deeply is more important than memorizing answers. Focus on the "why" behind each concept, practice coding regularly, and always be ready to explain your thought process.

← Back to JobScoutify