These JavaScript interview questions cover core language concepts, modern ES6+ features, asynchronous programming, browser behavior, objects, functions, and practical coding problems. Each answer explains the concept directly and includes examples where they help clarify expected interview responses.
Core JavaScript Interview Questions
1. What is JavaScript?
JavaScript is a high-level, dynamically typed programming language commonly used to add behavior and interactivity to web pages. It can run in web browsers and in server-side environments such as Node.js.
JavaScript supports several programming styles, including procedural, object-oriented, and functional programming.
2. What are the primitive data types in JavaScript?
JavaScript has the following primitive data types:
stringnumberbigintbooleanundefinedsymbolnull
Objects, arrays, and functions are non-primitive values. Primitive values are immutable, while objects can be modified after creation.
3. What is the difference between null and undefined?
undefined usually means that a variable or property has been declared but has not been assigned a value. null is an explicit value used to represent the intentional absence of an object or value.
let firstName;
const selectedUser = null;
console.log(firstName); // undefined
console.log(selectedUser); // null
A notable historical behavior is that typeof null returns "object". This should not be interpreted as meaning that null is an object.
4. What is the difference between == and === in JavaScript?
The loose equality operator == performs type conversion before comparing values. The strict equality operator === compares both value and type without implicit type conversion.
console.log(5 == "5"); // true
console.log(5 === "5"); // false
console.log(false == 0); // true
console.log(false === 0); // false
Strict equality is generally preferred because it avoids results caused by implicit coercion.
5. What is type coercion in JavaScript?
Type coercion is the conversion of a value from one data type to another. JavaScript may perform coercion implicitly, or a developer may perform it explicitly.
console.log("5" + 2); // "52"
console.log("5" - 2); // 3
console.log(Number("42")); // 42
console.log(String(false)); // "false"
console.log(Boolean(1)); // true
In the first expression, the number is converted to a string. In the second expression, subtraction requires numeric operands, so the string is converted to a number.
6. Which values are falsy in JavaScript?
Falsy values become false when evaluated in a Boolean context. Common falsy values are:
false0and-00n- An empty string:
"" nullundefinedNaN
Empty arrays and empty objects are truthy.
console.log(Boolean([])); // true
console.log(Boolean({})); // true
console.log(Boolean("")); // false
JavaScript Variable Scope and Hoisting Questions
7. What is the difference between var, let, and const?
| Keyword | Scope | Can be reassigned? | Can be redeclared in the same scope? |
|---|---|---|---|
var | Function scope | Yes | Yes |
let | Block scope | Yes | No |
const | Block scope | No | No |
A const declaration prevents reassignment of the variable binding. It does not make the contents of an object immutable.
const user = { name: "Asha" };
user.name = "Ravi"; // Allowed
// user = {}; // TypeError: assignment to a constant variable
8. What is hoisting in JavaScript?
Hoisting describes how declarations are processed before code execution. Function declarations can usually be called before their position in the source code. Variables declared with var are initialized with undefined, while let and const remain inaccessible until their declarations are evaluated.
console.log(total); // undefined
var total = 10;
sayHello();
function sayHello() {
console.log("Hello");
}
9. What is the temporal dead zone?
The temporal dead zone is the period between entering a block scope and evaluating a let, const, or class declaration. Accessing the binding during this period throws a ReferenceError.
{
// console.log(status); // ReferenceError
const status = "ready";
console.log(status);
}
10. What is lexical scope?
Lexical scope means that variable accessibility is determined by where functions and blocks are written in the source code. An inner function can access variables declared in its outer scope.
const language = "JavaScript";
function printLanguage() {
const message = "Current language";
function print() {
console.log(`${message}: ${language}`);
}
print();
}
printLanguage();
JavaScript Function and Closure Interview Questions
11. What is the difference between a function declaration and a function expression?
A function declaration defines a named function as a declaration. A function expression creates a function as part of an expression and usually assigns it to a variable.
function add(a, b) {
return a + b;
}
const subtract = function (a, b) {
return a - b;
};
Function declarations are initialized during scope creation and can generally be called before their declaration. Function expressions follow the initialization rules of the variable to which they are assigned.
12. How are arrow functions different from regular functions?
Arrow functions use shorter syntax and do not create their own this, arguments, super, or new.target bindings. Their this value is taken from the surrounding lexical scope.
const multiply = (a, b) => a * b;
const counter = {
value: 0,
start() {
setInterval(() => {
this.value++;
console.log(this.value);
}, 1000);
}
};
Arrow functions cannot be used as constructors with new. They are also unsuitable as object methods when the method needs its own dynamically determined this.
13. What is a closure in JavaScript?
A closure is created when a function retains access to variables from its lexical scope even after the outer function has finished executing.
function createCounter() {
let count = 0;
return function () {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
Closures are used for data privacy, function factories, callbacks, memoization, and maintaining state between function calls.
14. What is a higher-order function?
A higher-order function accepts one or more functions as arguments, returns a function, or does both. Array methods such as map(), filter(), and reduce() are common examples.
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(number => number * 2);
console.log(doubled); // [2, 4, 6, 8]
15. What are pure functions?
A pure function returns the same result for the same inputs and does not produce observable side effects. It does not modify external variables, mutate its arguments, write to storage, or perform network requests.
function calculateTax(amount, rate) {
return amount * rate;
}
Pure functions are easier to test and reason about because their behavior depends only on their inputs.
16. What do call(), apply(), and bind() do?
These methods control the this value used when a function runs.
call()invokes the function immediately and accepts arguments separately.apply()invokes the function immediately and accepts arguments as an array or array-like object.bind()returns a new function with a fixedthisvalue and optional preset arguments.
function introduce(greeting, punctuation) {
return `${greeting}, I am ${this.name}${punctuation}`;
}
const person = { name: "Meera" };
console.log(introduce.call(person, "Hello", "."));
console.log(introduce.apply(person, ["Hi", "!"]));
const boundIntroduce = introduce.bind(person, "Welcome");
console.log(boundIntroduce("."));
Objects, Prototypes, and Classes in JavaScript
17. How are objects created in JavaScript?
Objects can be created using object literals, constructor functions, classes, or Object.create().
const user1 = { name: "Riya" };
function User(name) {
this.name = name;
}
const user2 = new User("Arun");
class Customer {
constructor(name) {
this.name = name;
}
}
const user3 = new Customer("Neha");
const prototype = { role: "reader" };
const user4 = Object.create(prototype);
18. What is prototypal inheritance?
JavaScript objects can inherit properties and methods from another object through the prototype chain. When a property is not found directly on an object, JavaScript looks for it on the object’s prototype and continues up the chain until it finds the property or reaches null.
const animal = {
speak() {
return `${this.name} makes a sound`;
}
};
const dog = Object.create(animal);
dog.name = "Bruno";
console.log(dog.speak());
19. Are JavaScript classes different from prototypes?
JavaScript classes provide clearer syntax for creating constructor functions and defining prototype methods. They do not replace prototypal inheritance; class instances still inherit through the prototype chain.
class Employee {
constructor(name) {
this.name = name;
}
describe() {
return `Employee: ${this.name}`;
}
}
20. What is the difference between Object.freeze(), Object.seal(), and const?
| Feature | Effect |
|---|---|
const | Prevents reassignment of the variable binding. |
Object.seal() | Prevents adding or deleting properties, but existing writable properties may still be changed. |
Object.freeze() | Prevents adding, deleting, or changing the object’s own properties. |
Both Object.freeze() and Object.seal() are shallow. Nested objects remain mutable unless they are also sealed or frozen.
Arrays and ES6 JavaScript Interview Questions
21. What is the difference between map(), filter(), and reduce()?
map()creates a new array by transforming every element.filter()creates a new array containing elements that pass a condition.reduce()combines array elements into a single accumulated result.
const values = [1, 2, 3, 4];
const doubled = values.map(value => value * 2);
const even = values.filter(value => value % 2 === 0);
const total = values.reduce((sum, value) => sum + value, 0);
console.log(doubled); // [2, 4, 6, 8]
console.log(even); // [2, 4]
console.log(total); // 10
22. Which JavaScript array methods mutate the original array?
Common mutating array methods include push(), pop(), shift(), unshift(), splice(), sort(), reverse(), fill(), and copyWithin().
Methods such as map(), filter(), slice(), concat(), and flat() return new arrays instead of modifying the original array.
23. What are the spread and rest operators?
Both features use three dots, but their purpose depends on context. Spread expands an iterable or object into individual values. Rest collects multiple values into an array or object.
const first = [1, 2];
const combined = [...first, 3, 4];
function sum(...numbers) {
return numbers.reduce((total, number) => total + number, 0);
}
const user = { name: "Asha", city: "Pune" };
const updatedUser = { ...user, city: "Mumbai" };
24. What is destructuring in JavaScript?
Destructuring extracts values from arrays or properties from objects into separate variables.
const coordinates = [10, 20];
const [x, y] = coordinates;
const employee = {
name: "Kiran",
department: "Engineering"
};
const { name, department } = employee;
25. What are JavaScript modules?
Modules divide an application into reusable files with explicit imports and exports. ECMAScript modules use export and import.
// math.js
export function add(a, b) {
return a + b;
}
export const PI = 3.14159;
// app.js
import { add, PI } from "./math.js";
console.log(add(2, 3));
console.log(PI);
In a browser, an ECMAScript module can be loaded with a script element whose type is set to module.
<script type="module" src="app.js"></script>
Asynchronous JavaScript and Event Loop Questions
26. Is JavaScript synchronous or asynchronous?
JavaScript executes code on a single call stack in a synchronous manner. Host environments such as browsers and Node.js provide APIs for timers, network requests, file operations, and events. Their callbacks are scheduled for later execution through task queues and the event loop.
27. What is the JavaScript event loop?
The event loop coordinates the call stack and queued work. When the call stack is empty, queued callbacks can be moved to the stack for execution.
Promise handlers are placed in the microtask queue. Timer callbacks are placed in a task queue. After current synchronous code completes, pending microtasks are processed before the next task.
console.log("start");
setTimeout(() => {
console.log("timer");
}, 0);
Promise.resolve().then(() => {
console.log("promise");
});
console.log("end");
start
end
promise
timer
28. What is a Promise in JavaScript?
A Promise represents the eventual completion or failure of an asynchronous operation. It can be pending, fulfilled, or rejected.
function getUser() {
return fetch("/api/user")
.then(response => {
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return response.json();
});
}
getUser()
.then(user => console.log(user))
.catch(error => console.error(error));
29. How do async and await work?
An async function always returns a Promise. The await keyword pauses that function until the awaited Promise settles, without blocking the JavaScript thread.
async function getUser() {
const response = await fetch("/api/user");
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return response.json();
}
async function displayUser() {
try {
const user = await getUser();
console.log(user);
} catch (error) {
console.error(error);
}
}
30. What is the difference between Promise.all() and Promise.allSettled()?
Promise.all() fulfills when all input promises fulfill. It rejects as soon as one input promise rejects. Promise.allSettled() waits until every input promise has either fulfilled or rejected and returns the outcome of each operation.
const requests = [
fetch("/api/users"),
fetch("/api/orders"),
fetch("/api/products")
];
const responses = await Promise.all(requests);
const outcomes = await Promise.allSettled(requests);
Browser JavaScript Interview Questions
31. What is the DOM?
The Document Object Model, or DOM, is a programming interface that represents an HTML or XML document as a tree of nodes. JavaScript can use DOM APIs to read, create, update, and remove page elements.
const heading = document.querySelector("h1");
heading.textContent = "Updated heading";
const button = document.createElement("button");
button.textContent = "Save";
document.body.append(button);
32. What is event bubbling and event capturing?
During event capturing, an event travels from the document root toward the target element. During event bubbling, it travels from the target back through its ancestors. Most event listeners run during the bubbling phase unless capture is enabled.
const container = document.querySelector(".container");
container.addEventListener(
"click",
event => {
console.log("Capturing phase", event.target);
},
{ capture: true }
);
container.addEventListener("click", event => {
console.log("Bubbling phase", event.target);
});
33. What is event delegation?
Event delegation attaches one listener to a parent element instead of attaching separate listeners to many child elements. The listener inspects event.target or uses closest() to determine which child initiated the event.
const list = document.querySelector("#user-list");
list.addEventListener("click", event => {
const button = event.target.closest("button[data-user-id]");
if (!button || !list.contains(button)) {
return;
}
console.log("Selected user:", button.dataset.userId);
});
This technique is useful for dynamic lists because newly added child elements are handled by the existing parent listener.
34. What is the difference between localStorage, sessionStorage, and cookies?
| Storage type | Typical lifetime | Sent with HTTP requests? | Main use |
|---|---|---|---|
localStorage | Until explicitly cleared | No | Persistent browser-side string data |
sessionStorage | Until the browser tab or session closes | No | Temporary tab-specific string data |
| Cookie | Session-based or until an expiry date | Yes, when domain and path rules match | Sessions, preferences, and server-readable state |
Sensitive authentication tokens require careful security design. Browser storage is accessible to JavaScript running on the page, while an appropriately configured HttpOnly cookie is not readable through client-side JavaScript.
35. What is the difference between preventDefault() and stopPropagation()?
event.preventDefault() prevents the browser’s default action, such as following a link or submitting a form. event.stopPropagation() stops the event from continuing through the capturing or bubbling path.
const form = document.querySelector("form");
form.addEventListener("submit", event => {
event.preventDefault();
console.log("Validate and submit with JavaScript");
});
Practical JavaScript Coding Interview Questions
36. How do you remove duplicate values from an array?
For primitive values, a Set provides a concise solution because it stores unique values.
function removeDuplicates(values) {
return [...new Set(values)];
}
console.log(removeDuplicates([1, 2, 2, 3, 3, 4]));
[1, 2, 3, 4]
For objects, uniqueness must be defined using a property or comparison rule.
37. How do you reverse a string without using reverse()?
function reverseString(value) {
let result = "";
for (const character of value) {
result = character + result;
}
return result;
}
console.log(reverseString("JavaScript"));
tpircSavaJ
38. How do you check whether a string is a palindrome?
function isPalindrome(value) {
const normalized = value
.toLowerCase()
.replace(/[^a-z0-9]/g, "");
return normalized === [...normalized].reverse().join("");
}
console.log(isPalindrome("Never odd or even")); // true
39. How do you count character occurrences in a string?
function countCharacters(value) {
const counts = {};
for (const character of value) {
counts[character] = (counts[character] ?? 0) + 1;
}
return counts;
}
console.log(countCharacters("banana"));
{ b: 1, a: 3, n: 2 }
40. How do you flatten a nested array?
Modern JavaScript provides Array.prototype.flat(). Passing Infinity flattens all nesting levels.
const nested = [1, [2, [3, 4]], 5];
const flattened = nested.flat(Infinity);
console.log(flattened);
[1, 2, 3, 4, 5]
41. How do you implement debounce in JavaScript?
Debouncing delays a function call until a specified period has passed without another call. It is commonly used for search inputs, validation, and resize handlers.
function debounce(callback, delay) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => {
callback.apply(this, args);
}, delay);
};
}
const handleSearch = debounce(query => {
console.log("Searching for:", query);
}, 300);
42. How do you implement throttle in JavaScript?
Throttling limits a function so that it runs no more than once during a specified interval. It is useful for scroll, pointer-move, and resize events.
function throttle(callback, interval) {
let lastExecution = 0;
return function (...args) {
const now = Date.now();
if (now - lastExecution >= interval) {
lastExecution = now;
callback.apply(this, args);
}
};
}
const handleScroll = throttle(() => {
console.log("Scroll position:", window.scrollY);
}, 200);
43. How do you group an array of objects by a property?
function groupBy(items, property) {
return items.reduce((groups, item) => {
const key = item[property];
groups[key] ??= [];
groups[key].push(item);
return groups;
}, {});
}
const employees = [
{ name: "Anita", team: "Frontend" },
{ name: "Rahul", team: "Backend" },
{ name: "Vijay", team: "Frontend" }
];
console.log(groupBy(employees, "team"));
Senior JavaScript Developer Interview Topics
44. What is shallow copying and deep copying?
A shallow copy creates a new outer object but keeps references to nested objects. Spread syntax, Object.assign(), and Array.prototype.slice() produce shallow copies.
const original = {
name: "Asha",
address: { city: "Delhi" }
};
const shallowCopy = { ...original };
shallowCopy.address.city = "Pune";
console.log(original.address.city); // Pune
A deep copy duplicates nested supported values. structuredClone() is suitable for many built-in structured data types, but it cannot clone functions and some host-specific objects.
const deepCopy = structuredClone(original);
deepCopy.address.city = "Jaipur";
console.log(original.address.city); // Pune
console.log(deepCopy.address.city); // Jaipur
45. What is memoization?
Memoization caches the result of a function call so that repeated calls with the same input can reuse the stored result instead of performing the calculation again.
function memoize(callback) {
const cache = new Map();
return function (value) {
if (cache.has(value)) {
return cache.get(value);
}
const result = callback(value);
cache.set(value, result);
return result;
};
}
const square = memoize(number => number * number);
Real implementations may need a more reliable cache key for functions that accept multiple arguments or object arguments.
46. What causes memory leaks in JavaScript applications?
A memory leak occurs when objects that are no longer needed remain reachable and therefore cannot be garbage-collected. Common causes include:
- Event listeners that are never removed
- Intervals or timers that continue running
- Closures that retain large objects unnecessarily
- Detached DOM elements that remain referenced
- Unbounded caches, arrays, or maps
- Subscriptions that are not cleaned up
Memory problems can be investigated with browser developer tools, heap snapshots, allocation profiles, and careful lifecycle cleanup.
47. What is the difference between a Map and a plain object?
A Map can use values of any type as keys, preserves insertion order, provides a reliable size property, and is directly iterable. Plain object keys are strings or symbols and objects also inherit from a prototype unless created with a null prototype.
const user = { id: 1 };
const permissions = new Map();
permissions.set(user, ["read", "write"]);
console.log(permissions.get(user));
48. What are WeakMap and WeakSet?
WeakMap stores key-value pairs whose keys must be objects or non-registered symbols. WeakSet stores weakly held objects or non-registered symbols. Their entries do not prevent eligible objects from being garbage-collected.
Weak collections are not enumerable and do not expose a size property because entries may disappear when their keys are garbage-collected.
49. What is currying in JavaScript?
Currying transforms a function that accepts multiple arguments into a sequence of functions that each accept one argument.
const multiply = a => b => a * b;
const double = multiply(2);
console.log(double(5)); // 10
console.log(multiply(3)(4)); // 12
Currying can help create reusable, partially configured functions.
50. What is optional chaining and nullish coalescing?
Optional chaining, written as ?., safely accesses a property or calls a function when the preceding value may be null or undefined. Nullish coalescing, written as ??, provides a fallback only when the left side is null or undefined.
const user = {
profile: {
displayName: "Anita"
}
};
const name = user.profile?.displayName ?? "Guest";
const city = user.address?.city ?? "Not provided";
Unlike ||, the ?? operator does not replace valid falsy values such as 0, false, or an empty string.
How to Prepare for a JavaScript Technical Interview
A JavaScript interview may combine conceptual questions, output-prediction exercises, debugging tasks, browser questions, and coding problems. Preparation should include both explanation and implementation.
- Review scope, closures, hoisting, coercion, equality, prototypes, and
this. - Practise tracing synchronous code, Promise callbacks, timers, and event-loop output.
- Write solutions using arrays, objects, strings, maps, sets, and recursion where appropriate.
- Understand DOM events, event delegation, browser storage, and form handling.
- Explain the time and space complexity of coding solutions.
- Discuss edge cases before writing code.
- Test code with empty input, duplicate values, invalid values, and large inputs.
- For senior roles, prepare examples involving architecture, performance, testing, security, and production debugging.
JavaScript Interview Answer Checklist
- Define the JavaScript concept before giving an example.
- State whether an operation mutates the original array or object.
- Explain how
thisis determined in the specific function call. - Distinguish synchronous stack execution from queued asynchronous callbacks.
- Mention important edge cases such as
null,undefined,NaN, and empty input. - Use strict equality unless type coercion is intentional.
- Explain the complexity of coding solutions when it affects scalability.
- Avoid claiming that spread syntax creates a deep copy.
- Use
try...catchor Promise rejection handling for fallible asynchronous operations. - Clarify whether an API belongs to JavaScript itself or to the browser or Node.js environment.
JavaScript Interview Questions FAQ
Which JavaScript topics are most frequently tested in interviews?
Common topics include scope, closures, hoisting, this, prototypes, equality, type coercion, array methods, promises, async and await, the event loop, DOM events, and practical string or array problems. Senior interviews may also cover performance, memory management, application architecture, testing, and browser security.
Are ES6 questions still relevant in JavaScript interviews?
Yes. Features introduced in ES6 and later releases are part of modern JavaScript development. Candidates should understand let, const, arrow functions, classes, modules, destructuring, spread and rest syntax, promises, template literals, maps, sets, optional chaining, and related language features.
What should a senior JavaScript developer prepare beyond syntax questions?
A senior candidate should be ready to discuss design trade-offs, asynchronous workflows, API error handling, code organization, performance measurement, memory leaks, testing strategy, browser compatibility, security boundaries, observability, and production debugging. Answers should include examples of decisions made in real applications.
How should I answer a JavaScript output-prediction question?
Trace the program in execution order. Identify declarations, scope, the value of this, synchronous statements, Promise microtasks, timer callbacks, mutations, and implicit conversions. State the output only after explaining why each line executes in that order.
Should JavaScript coding answers include time complexity?
Include time and space complexity when the solution processes collections, uses nested loops, recursion, sorting, maps, or sets. Complexity analysis helps explain how the approach behaves as input size grows and may reveal a better solution.
TutorialKart.com