JavaScript Interview Questions and Answers for Freshers and Experienced (65 Questions)

Quick answer: These 65 JavaScript interview questions and answers cover what is asked most in front-end developer, full-stack developer and web developer roles: JavaScript basics, functions and scope, objects and arrays with ES6+, prototypes and classes, asynchronous JavaScript, the DOM and browser, and advanced and output-based questions. Key answers include short code examples.

Read each answer, then close the page and explain it aloud in two or three sentences. That is exactly what interviewers check.

Contents

1. JavaScript Basics Interview Questions

Q1. What is JavaScript?

JavaScript is a high-level, dynamically typed programming language that makes web pages interactive. It runs in every browser, and with Node.js it also runs on servers. Together with HTML and CSS, it is one of the three core web technologies.

Q2. What is the difference between JavaScript and Java?

They are unrelated languages with similar names. Java is statically typed, compiled to bytecode and class-based. JavaScript is dynamically typed, runs in browsers and Node.js, and uses prototype-based objects.

Q3. What are the data types in JavaScript?

There are seven primitive types: string, number, bigint, boolean, undefined, null and symbol. Everything else is an object, including arrays, functions and dates.

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

var is function-scoped, can be redeclared and is hoisted with the value undefined. let and const are block-scoped and cannot be redeclared in the same scope. const cannot be reassigned, though the contents of a const object or array can still change.

if (true) {
  var a = 1;
  let b = 2;
}
console.log(a); // 1
console.log(b); // ReferenceError

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

== compares values after type conversion (loose equality), so '5' == 5 is true. === compares both value and type (strict equality), so '5' === 5 is false. Use === by default.

Q6. What is the difference between null and undefined?

undefined means a variable has been declared but not given a value. null is a value you assign on purpose to mean 'no value'. typeof undefined is 'undefined', while typeof null is 'object', a long-standing quirk.

Q7. What is NaN?

NaN (Not a Number) is the result of an invalid number operation, such as 'abc' * 2. It is of type number and is not equal to anything, even itself, so check it with Number.isNaN().

Q8. What are truthy and falsy values?

In a boolean context, the falsy values are false, 0, -0, 0n, '' (empty string), null, undefined and NaN. Every other value is truthy, including '0', [] and {}.

Q9. What is type coercion?

Type coercion is JavaScript automatically converting one type to another. For example, '5' + 2 gives '52' (number to string), while '5' – 2 gives 3 (string to number).

Q10. What are template literals?

Template literals use backticks and let you insert expressions with ${} and write multi-line strings.

const name = 'Asha';
console.log(`Hello, ${name}! You have ${2 + 3} messages.`);

2. Functions and Scope Interview Questions

Q11. What is the difference between function declarations and function expressions?

A function declaration (function add() {}) is fully hoisted, so it can be called before it appears in the code. A function expression (const add = function() {}) is not available until that line runs.

Q12. What are arrow functions and how are they different?

Arrow functions are a shorter syntax, (a, b) => a + b. They do not have their own this, arguments or prototype; they take this from the surrounding scope, and they cannot be used as constructors.

Q13. What is hoisting?

Hoisting means declarations are processed before code runs. Function declarations are hoisted fully. var variables are hoisted and set to undefined. let and const are hoisted too, but cannot be accessed before their line (the temporal dead zone).

console.log(x); // undefined
var x = 5;
console.log(y); // ReferenceError
let y = 5;

Q14. What is scope in JavaScript?

Scope decides where a variable can be accessed. JavaScript has global scope, function scope and block scope (for let and const). Inner functions can access variables of outer functions, which is called lexical scope.

Q15. What is a closure?

A closure is a function that remembers the variables of the scope where it was created, even after that outer function has finished running. Closures are used for private data, counters and callbacks.

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

Q16. What is an IIFE?

An Immediately Invoked Function Expression runs as soon as it is defined, (function () { … })(). It was used to create private scope before let, const and modules existed.

Q17. What are higher-order functions?

A higher-order function takes another function as an argument or returns a function. map, filter, reduce and setTimeout are common examples.

Q18. What is the difference between call, apply and bind?

All three set the value of this. call invokes the function immediately with arguments listed one by one. apply invokes it immediately with arguments as an array. bind returns a new function with this fixed, to be called later.

function greet(msg) { return msg + ', ' + this.name; }
const user = { name: 'Ravi' };
greet.call(user, 'Hi');      // 'Hi, Ravi'
greet.apply(user, ['Hello']); // 'Hello, Ravi'
const g = greet.bind(user);
g('Hey');                     // 'Hey, Ravi'

Q19. How does the this keyword work?

this depends on how a function is called: in a method it is the object before the dot; in a plain function it is undefined in strict mode (or the global object otherwise); with new it is the new object; with call, apply or bind it is set explicitly; and arrow functions take this from their surrounding scope.

Q20. What are default parameters and rest parameters?

Default parameters give a value when an argument is missing, function f(x = 10). Rest parameters collect remaining arguments into an array, function sum(…nums).

Q21. What is currying?

Currying turns a function with several arguments into a chain of functions that each take one argument, such as add(2)(3) instead of add(2, 3). It helps create reusable, partly filled functions.

3. Objects, Arrays and ES6+ Interview Questions

Q22. What are the ways to create an object?

Object literals ({}), constructor functions with new, ES6 classes, Object.create() and factory functions. Object literals are the most common.

Q23. What is destructuring?

Destructuring unpacks values from arrays or properties from objects into separate variables.

const user = { name: 'Asha', age: 22 };
const { name, age } = user;
const [first, second] = [10, 20];

Q24. What is the spread operator?

The spread operator (…) expands an array or object into individual elements. It is used to copy or merge arrays and objects.

const a = [1, 2];
const b = [...a, 3];            // [1, 2, 3]
const obj = { ...user, city: 'Hyderabad' };

Q25. What is the difference between shallow copy and deep copy?

A shallow copy, made with spread or Object.assign, copies only the top level, so nested objects are still shared. A deep copy duplicates everything; structuredClone(obj) is the modern built-in way.

Q26. What do map, filter and reduce do?

map returns a new array with each element transformed. filter returns a new array with only the elements that pass a test. reduce combines all elements into a single value.

const nums = [1, 2, 3, 4];
nums.map(n => n * 2);            // [2, 4, 6, 8]
nums.filter(n => n % 2 === 0);   // [2, 4]
nums.reduce((s, n) => s + n, 0); // 10

Q27. What is the difference between forEach and map?

forEach runs a function on each element and returns undefined. map returns a new array of the results. Use map when you need the transformed array.

Q28. How do you remove duplicates from an array?

Convert it to a Set, which keeps only unique values, and spread it back into an array.

const unique = [...new Set([1, 2, 2, 3, 3])]; // [1, 2, 3]

Q29. What is the difference between slice and splice?

slice(start, end) returns a copy of part of an array without changing the original. splice(start, count, …items) changes the original array by removing or adding elements.

Q30. What is optional chaining?

Optional chaining (?.) safely reads nested properties: if any part is null or undefined, the result is undefined instead of an error, as in user?.address?.city.

Q31. What is the nullish coalescing operator?

?? returns the right-hand value only when the left side is null or undefined. Unlike ||, it keeps valid values such as 0 and ''. For example, count ?? 10 keeps a count of 0.

Q32. What are Map and Set?

Map stores key-value pairs where keys can be any type and insertion order is kept. Set stores unique values. Both have size, has(), delete() and are easy to iterate.

Q33. What are ES6 modules?

Modules let you split code into files and share it with export and import. Each module has its own scope, so variables do not leak into the global scope.

Preparing for a JavaScript interview? We run live one-to-one classes and mock interviews in JavaScript, web development and DSA, arranged around your free time. Chat on WhatsApp.

4. Prototypes and Classes Interview Questions

Q34. What is prototypal inheritance?

Every JavaScript object has a hidden link to another object called its prototype. When a property is not found on an object, JavaScript looks up the prototype chain. This is how objects inherit methods.

Q35. What are ES6 classes?

Classes are cleaner syntax over prototype-based inheritance, with constructor, methods, extends and super.

class Animal {
  constructor(name) { this.name = name; }
  speak() { return `${this.name} makes a sound`; }
}
class Dog extends Animal {
  speak() { return `${this.name} barks`; }
}
new Dog('Tommy').speak(); // 'Tommy barks'

Q36. What does the new keyword do?

new creates an empty object, links it to the constructor's prototype, runs the constructor with this set to the new object, and returns that object.

Q37. What is the difference between Object.freeze and Object.seal?

Object.freeze makes an object fully read-only: no adding, removing or changing properties. Object.seal prevents adding or removing properties but still allows changing existing ones. Both are shallow.

5. Asynchronous JavaScript Interview Questions

Q38. Is JavaScript single-threaded?

Yes, JavaScript runs on one main thread. It handles slow tasks such as network requests and timers asynchronously, using browser or Node.js APIs and the event loop, so the page does not freeze.

Q39. What is the event loop?

The event loop keeps checking whether the call stack is empty. When it is, it first runs all pending microtasks (promise callbacks), then takes the next macrotask (such as a setTimeout callback) from the task queue.

Q40. What is the output order of this code?

Synchronous code runs first, then microtasks (promises), then macrotasks (timers). So the output is A, D, C, B.

console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');
// A, D, C, B

Q41. What is a callback and what is callback hell?

A callback is a function passed to another function to run later. Callback hell is deeply nested callbacks that are hard to read and maintain. Promises and async/await solve it.

Q42. What is a Promise?

A Promise represents a value that will be available later. It is pending, then either fulfilled with a value or rejected with an error. You handle it with .then(), .catch() and .finally().

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

Promise.all waits for all and fails if any fails. allSettled waits for all and reports each result. race settles with the first to settle, success or failure. any resolves with the first success and fails only if all fail.

Q44. What are async and await?

async makes a function return a promise. await pauses that function until a promise settles, so asynchronous code reads like normal step-by-step code. Use try/catch for errors.

async function loadUser(id) {
  try {
    const res = await fetch(`/api/users/${id}`);
    return await res.json();
  } catch (err) {
    console.error('Failed', err);
  }
}

Q45. What is the difference between setTimeout and setInterval?

setTimeout runs a function once after a delay. setInterval runs it repeatedly at a fixed interval until clearInterval is called.

Q46. What are debouncing and throttling?

Debouncing waits until events stop for a set time before running a function, which suits search boxes. Throttling runs a function at most once every set interval, which suits scroll and resize handlers.

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

6. DOM and Browser Interview Questions

Q47. What is the DOM?

The Document Object Model is a tree of objects the browser builds from HTML. JavaScript uses it to read and change page content, structure and styles, for example with document.querySelector.

Q48. How do you select and change elements?

Use querySelector or getElementById to find elements, then change textContent, innerHTML, classList or style.

const btn = document.querySelector('#save');
btn.textContent = 'Saved';
btn.classList.add('done');

Q49. What is event bubbling and capturing?

When an event happens on an element, it first travels down from the document (capturing), then up from the target to its ancestors (bubbling). Handlers run in the bubbling phase by default. stopPropagation() stops it travelling further.

Q50. What is event delegation?

Event delegation attaches one listener to a parent element and uses event.target to handle events from its children. It saves memory and works for elements added later.

document.querySelector('#list').addEventListener('click', e => {
  if (e.target.tagName === 'LI') e.target.classList.toggle('done');
});

Q51. What is the difference between preventDefault and stopPropagation?

preventDefault() stops the browser's default action, such as a form submitting or a link opening. stopPropagation() stops the event from reaching other elements.

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

localStorage keeps data until it is cleared, about 5 MB per site. sessionStorage keeps data only for the browser tab session. Cookies are small (about 4 KB), can expire, and are sent to the server with every request.

Q53. What is the difference between innerHTML and textContent?

innerHTML reads or sets HTML markup, so inserting user input with it can cause cross-site scripting (XSS). textContent treats everything as plain text, which is safer and faster.

Q54. What are defer and async on script tags?

Both download the script without blocking HTML parsing. async runs the script as soon as it downloads, in any order. defer runs scripts in order after the HTML has been parsed, which suits most page scripts.

Q55. What is CORS?

Cross-Origin Resource Sharing is a browser security rule. A page can call an API on another domain only if that server allows it with headers such as Access-Control-Allow-Origin.

7. Advanced Concepts and Coding Interview Questions

Q56. What is strict mode?

'use strict' turns on a stricter version of JavaScript that throws errors for unsafe actions, such as using undeclared variables, and makes this undefined in plain functions. ES6 modules and classes are always strict.

Q57. What is memoization?

Memoization caches the results of a function for given inputs, so repeated calls return the saved result instead of recomputing.

Q58. What is the difference between synchronous and asynchronous code?

Synchronous code runs line by line and each line waits for the previous one. Asynchronous code starts a task and continues, handling the result later through callbacks, promises or async/await.

Q59. What are generators?

A generator function, written function*, can pause with yield and resume later, producing values one at a time. It is useful for lazy sequences and custom iterators.

Q60. What is garbage collection in JavaScript?

The engine automatically frees memory for objects that can no longer be reached from the program, mainly using the mark-and-sweep algorithm. Forgotten timers, global variables and detached DOM nodes can still cause memory leaks.

Q61. How do you reverse a string?

Split it into characters, reverse the array and join it.

const reverse = s => s.split('').reverse().join('');
reverse('hello'); // 'olleh'

Q62. How do you flatten a nested array?

Use the built-in flat(Infinity), or recursion with reduce.

[1, [2, [3, [4]]]].flat(Infinity); // [1, 2, 3, 4]

Q63. How do you check whether two strings are anagrams?

Sort the characters of both strings and compare.

const isAnagram = (a, b) =>
  a.split('').sort().join('') === b.split('').sort().join('');
isAnagram('listen', 'silent'); // true

Q64. What is the output of [] + [] and [] + {}?

[] + [] gives '' (an empty string), because both arrays become empty strings. [] + {} gives '[object Object]'. These questions test understanding of type coercion.

Q65. What is the output of 0.1 + 0.2 === 0.3?

false. Numbers are stored as binary floating point, so 0.1 + 0.2 is 0.30000000000000004. Compare with a small tolerance, such as Math.abs(a – b) < Number.EPSILON.

How to Prepare for a JavaScript Interview

  1. Understand, do not memorise: closures, hoisting and this are best explained with your own tiny example.
  2. Predict outputs: interviewers love short snippets on the event loop, coercion and scope.
  3. Know async well: callbacks, promises, async/await and the microtask queue.
  4. Build projects: a to-do app, weather app or quiz app shows DOM and API skills.
  5. Learn one framework next: React is the most requested in front-end job posts.

Next steps: revise problem solving with DSA interview questions, compare with Python interview questions, and choose a web project from our final year projects for computer science.

Want a mentor for your preparation? We teach JavaScript, web development and DSA through live online classes arranged around your free time, with mock interviews before your placement. Message us on WhatsApp or email engineersrworld@gmail.com.

More interview preparation: see all interview questions, including Python, SQL, SQL query, Java, JavaScript, React, C++, .NET, Spring Boot, Node.js, DSA, OOPs, DBMS, operating system, networking, machine learning, data science, AI, Excel, Power BI, DevOps, manual testing, Selenium, cyber security and HR.

Frequently Asked Questions

Which JavaScript topics are most asked in interviews?

Closures, hoisting, this, var versus let versus const, == versus ===, promises and async/await, the event loop, and array methods such as map, filter and reduce appear in almost every front-end interview.

Is JavaScript enough to get a job?

JavaScript with HTML and CSS is enough for many front-end roles, especially with a framework such as React. Adding Node.js lets you apply for full-stack roles.

Should I learn JavaScript or TypeScript first?

Learn JavaScript first. TypeScript adds types on top of JavaScript, so it is much easier once the JavaScript basics are clear.

How should I prepare for a JavaScript interview?

Revise the concepts on this page, predict the output of small code snippets, build two or three projects such as a to-do app or weather app, and practise explaining the event loop and closures aloud.

Scroll to Top