JavaScript interviews cover everything from basic syntax and data types to closures, asynchronous programming, the event loop, promises, DOM manipulation, modern ES6+ features, performance, and practical coding problems. For beginner roles, interviewers usually focus on fundamentals and problem-solving. For experienced roles, they expect a deeper understanding of how JavaScript works and how you apply it when building real applications.
This guide covers JavaScript interview questions and answers from beginner to advanced level, including conceptual questions, code examples, tricky output questions, practical coding problems, browser concepts, Node.js fundamentals, and topics frequently asked in frontend and full-stack interviews.
Whether you are preparing for your first JavaScript interview, a frontend developer position, a React role, or a senior software engineer interview, use this guide to understand the concepts rather than memorize definitions.
Table of Contents
Quick Answer: What Are the Most Common JavaScript Interview Questions?
If you have limited time before your interview, start with these questions:
| # | Question | What you need to know |
|---|---|---|
| 1 | What is JavaScript? | Language purpose and execution |
| 2 | What are the data types in JavaScript? | Primitive and non-primitive types |
| 3 | What is the difference between var, let, and const? | Scope and reassignment |
| 4 | What is hoisting? | Declaration processing |
| 5 | What is a closure? | Access to outer variables |
| 6 | What is the difference between == and ===? | Equality and type coercion |
| 7 | What is the difference between null and undefined? | Missing and intentional values |
| 8 | What is the this keyword? | Execution context |
| 9 | What are arrow functions? | Syntax and lexical this |
| 10 | What are callbacks? | Passing functions as arguments |
| 11 | What are promises? | Asynchronous operations |
| 12 | What is async and await? | Promise-based asynchronous syntax |
| 13 | What is the event loop? | JavaScript concurrency model |
| 14 | What is the difference between map(), filter() and reduce()? | Array processing |
| 15 | What is the DOM? | Browser document representation |
| 16 | What is event bubbling? | Event propagation |
| 17 | What is prototypal inheritance? | Objects and prototypes |
| 18 | What is destructuring? | Extracting values |
| 19 | What is the difference between spread and rest operators? | ... syntax |
| 20 | What is the difference between shallow copy and deep copy? | Object copying |
| 21 | What are JavaScript modules? | Import and export |
| 22 | What is debouncing and throttling? | Event optimization |
| 23 | What is the difference between synchronous and asynchronous code? | Execution behavior |
| 24 | What are call(), apply() and bind()? | Function context |
| 25 | How does JavaScript handle memory? | Garbage collection and references |
These are the foundations. The sections below explain them in detail and cover the additional questions interviewers use to distinguish candidates who understand JavaScript from those who have only memorized answers.
1. JavaScript Fundamentals Interview Questions
1. What is JavaScript?
JavaScript is a high-level programming language primarily used to make websites interactive and build dynamic applications. It runs in web browsers and can also run outside browsers through environments such as Node.js.
JavaScript can handle user interactions, update webpage content, validate forms, communicate with APIs, manage application logic, and build server-side applications.
Unlike HTML which describes the structure of a webpage and CSS which controls its appearance, JavaScript handles behavior.
For example:
const button = document.querySelector("button");
button.addEventListener("click", () => {
alert("Button clicked!");
});
This code listens for a button click and displays a message when the user clicks it.
JavaScript is used for:
- Frontend web development
- Backend development with Node.js
- Mobile applications
- Desktop applications
- Browser-based games
- Interactive web applications
- API development
- Serverless applications
2. Is JavaScript the same as Java?
No. JavaScript and Java are different programming languages despite their similar names.
| JavaScript | Java |
|---|---|
| Dynamically typed | Statically typed |
| Commonly executed by JavaScript engines | Compiled into bytecode and executed by the JVM |
| Widely used in web development | Widely used in enterprise applications and Android-related ecosystems |
| Supports prototype-based inheritance | Primarily class-based inheritance |
| Commonly used with browsers and Node.js | Runs on the Java Virtual Machine |
Their names are similar because JavaScript was originally marketed under a name associated with Java during the period when Java was popular. The languages are not versions of one another.
3. What are the main features of JavaScript?
Important JavaScript features include:
- Dynamic typing
- First-class functions
- Prototype-based inheritance
- Closures
- Event-driven programming
- Asynchronous programming
- Garbage collection
- Support for object-oriented and functional programming styles
- Cross-platform execution through compatible runtimes
JavaScript supports multiple programming paradigms. You can write procedural code, use objects and classes, or use functional techniques such as passing functions and transforming arrays.
4. Is JavaScript single-threaded?
JavaScript execution in a typical browser main thread is single-threaded. This means one piece of JavaScript code executes at a time on that thread.
However, that does not mean JavaScript applications cannot handle multiple operations efficiently.
The runtime can delegate tasks such as timers, network requests and other operations to browser or runtime facilities. When those operations complete, their callbacks or continuations can be scheduled for JavaScript execution.
JavaScript also supports parallel execution through Web Workers in browsers and Worker Threads in Node.js, although these operate differently from the main JavaScript execution thread.
5. Is JavaScript interpreted or compiled?
JavaScript engines use a combination of execution techniques.
Modern engines often begin by interpreting code and then use just-in-time compilation to optimize frequently executed code. For example, the V8 engine used in Chrome and Node.js can compile JavaScript into machine code for performance.
So, describing JavaScript as purely interpreted is outdated. Its execution model depends on the engine and its optimization strategies.
6. What is ECMAScript?
ECMAScript is the standardized specification that defines the JavaScript language.
JavaScript is an implementation of ECMAScript along with runtime-specific APIs and features. ECMAScript defines things such as syntax, functions, objects, data types, promises and language behavior.
New language features are developed through the ECMAScript standardization process and are released in annual editions.
For example, ES6 is another name for ECMAScript 2015. It introduced major features such as:
letandconst- Arrow functions
- Classes
- Promises
- Template literals
- Destructuring
- Modules
7. What is the difference between JavaScript and TypeScript?
JavaScript is the core programming language used for application logic. TypeScript is a programming language developed by Microsoft that extends JavaScript with a static type system and additional development features.
| JavaScript | TypeScript |
|---|---|
| Dynamic typing | Static type checking |
| Runs directly in supported runtimes | Commonly transpiled into JavaScript |
| Types are not checked at compile time by default | Can catch many type-related mistakes during development |
| Simpler setup for small projects | Useful for larger and more structured projects |
Uses .js files | Commonly uses .ts files |
Example JavaScript:
function add(a, b) {
return a + b;
}
TypeScript:
function add(a: number, b: number): number {
return a + b;
}
TypeScript helps identify certain errors before the code runs, but its types do not automatically provide runtime validation of external data.
2. JavaScript Data Types Interview Questions
8. What are the data types in JavaScript?
JavaScript has seven primitive types and one broad non-primitive category represented by objects.
Primitive data types
- String
- Number
- BigInt
- Boolean
- Undefined
- Null
- Symbol
Non-primitive type
– Object — including arrays, functions, dates and many other object types
Example:
let name = "Alex";
let age = 25;
let isActive = true;
let score;
let user = null;
let id = Symbol("id");
let largeNumber = 12345678901234567890n;
let person = {
name: "Alex",
age: 25
};
9. What is the difference between primitive and non-primitive data types?
Primitive values represent individual values and are immutable. Objects are collections of properties and can be mutable.
| Primitive | Non-primitive |
|---|---|
| String | Object |
| Number | Array |
| Boolean | Function |
| Undefined | Date |
| Null | Map and Set |
| BigInt | Other object instances |
| Symbol |
Primitives are assigned and passed by value. When objects are assigned to variables, the variables hold references to the same object.
let a = 10;
let b = a;
b = 20;
console.log(a); // 10
console.log(b); // 20
With objects:
let first = { name: "Alex" };
let second = first;
second.name = "Sam";
console.log(first.name); // Sam
Both variables refer to the same object.
10. What is undefined in JavaScript?
undefined means a value has not been assigned or is unavailable in a particular context.
let name;
console.log(name); // undefined
Common situations include:
- Declaring a variable without assigning a value
- Accessing a missing object property
- A function that does not explicitly return a value
- A function parameter that was not supplied
function greet() {
}
console.log(greet()); // undefined
11. What is null in JavaScript?
null represents the intentional absence of an object-like value or a value deliberately set to empty.
let selectedUser = null;
This often means that no user has been selected yet.
Unlike undefined, which commonly indicates an uninitialized or missing value, null is generally assigned intentionally.
One unusual JavaScript behavior is:
console.log(typeof null); // "object"
This is a longstanding language quirk. null is not actually an object.
12. What is the difference between null and undefined?
null | undefined |
|---|---|
| Usually assigned intentionally | Often appears when no value was assigned |
| Represents an intentional empty value | Represents an unavailable or missing value |
typeof null returns "object" | typeof undefined returns "undefined" |
| Used to clear or reset values | Common with uninitialized variables or missing properties |
let a = null;
let b;
console.log(a); // null
console.log(b); // undefined
13. What is NaN?
NaN stands for Not a Number. It is a special numeric value that represents an invalid or unrepresentable numeric result.
console.log("hello" / 2); // NaN
console.log(Number("abc")); // NaN
Interestingly:
console.log(typeof NaN); // "number"
To check whether a value is NaN, use:
Number.isNaN(value);
For example:
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN("hello")); // false
Avoid relying on NaN === NaN because it returns false.
14. What is the difference between isNaN() and Number.isNaN()?
The global isNaN() converts the input to a number before checking it. Number.isNaN() checks whether the value is already the numeric NaN value without coercing it.
console.log(isNaN("hello")); // true
console.log(Number.isNaN("hello")); // false
console.log(isNaN("123")); // false
console.log(Number.isNaN("123")); // false
Number.isNaN() is generally more predictable when validating numeric results.
15. What is the difference between typeof and instanceof?
typeof identifies the general type of a value. instanceof checks whether an object’s prototype chain contains a particular constructor’s prototype.
console.log(typeof "hello"); // string
console.log(typeof 10); // number
console.log([] instanceof Array); // true
console.log([] instanceof Object); // true
typeof is useful for primitive checks. instanceof is mainly useful for objects and constructor relationships.
Be aware that instanceof can behave unexpectedly across different realms such as separate browser windows.
16. What is a Symbol?
A Symbol is a primitive type used to create unique identifiers.
const id1 = Symbol("id");
const id2 = Symbol("id");
console.log(id1 === id2); // false
Even when they have the same description, symbols are unique.
Symbols can be used as object property keys to reduce accidental naming collisions.
17. What is BigInt?
BigInt allows JavaScript to represent integers larger than the safe integer range of the Number type.
const bigNumber = 9007199254740993n;
console.log(bigNumber);
The n suffix indicates a BigInt literal.
BigInt and Number cannot generally be mixed directly in arithmetic operations.
// 10n + 5 // TypeError
console.log(10n + 5n); // 15n
3. Variables, Scope and Hoisting
These concepts are among the most frequently tested areas in JavaScript interviews because they determine how values are stored, accessed and changed during program execution.
18. What is the difference between var, let and const?
JavaScript provides three main ways to declare variables: var, let and const. They differ in scope, reassignment and redeclaration behavior.
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Reassignment | Allowed | Allowed | Not allowed |
| Redeclaration in same scope | Allowed | Not allowed | Not allowed |
| Hoisted | Yes | Yes but uninitialized | Yes but uninitialized |
| Must initialize at declaration | No | No | Yes |
Example:
var name = "Alex";
name = "Sam"; // Allowed
let age = 25;
age = 26; // Allowed
const country = "USA";
// country = "Canada"; // TypeError
In modern JavaScript, use const by default when the variable does not need to be reassigned. Use let when reassignment is necessary. Avoid var in most new code because its function scope can lead to unexpected behavior.
19. What is variable scope in JavaScript?
Scope determines where a variable can be accessed in a program.
JavaScript has three commonly discussed scope types:
- Global scope
- Function scope
- Block scope
Global scope
A variable declared outside a function or block may be accessible throughout the relevant script or module scope.
const message = "Hello";
function greet() {
console.log(message);
}
greet(); // Hello
Function scope
Variables declared inside a function are generally available only inside that function.
function showMessage() {
const message = "Hello";
console.log(message);
}
showMessage();
// console.log(message); // ReferenceError
Block scope
Variables declared using let and const inside a block are only accessible within that block.
if (true) {
let age = 25;
const name = "Alex";
}
console.log(age); // ReferenceError
Unlike let and const, var is not block-scoped.
if (true) {
var age = 25;
}
console.log(age); // 25
20. What is hoisting in JavaScript?
Hoisting describes the behavior in which declarations are processed before their corresponding execution reaches the declaration’s position in the code.
It does not mean JavaScript physically moves your code to the top of the file.
Consider:
console.log(name);
var name = "Alex";
Output:
undefined
The variable declaration is available in the scope before the assignment happens.
This is why the code behaves roughly like:
var name;
console.log(name);
name = "Alex";
Function declarations can also be called before their declaration appears in the code.
greet();
function greet() {
console.log("Hello");
}
Output:
Hello
Hoisting behavior differs between var, let, const, functions and classes.
21. What is the Temporal Dead Zone (TDZ)?
The Temporal Dead Zone is the period between entering a scope and the point where a let, const or class declaration is initialized.
During this period, accessing the variable results in a ReferenceError.
console.log(age); // ReferenceError
let age = 25;
Compare that with var:
console.log(age); // undefined
var age = 25;
The variable exists in the scope before its assignment. With let and const, the variable is inaccessible until initialization.
The TDZ helps prevent accidental use of variables before they have been properly initialized.Â
22. Can you redeclare a variable using var, let and const?
var permits redeclaration within the same scope. let and const do not.
var age = 20;
var age = 25; // Allowed
But:
let age = 20;
let age = 25; // SyntaxError
And:
const age = 20;
const age = 25; // SyntaxError
This restriction helps avoid accidental declaration conflicts.
23. What is the difference between global scope and local scope?
Global scope refers to variables accessible from the broader script or module context. Local scope refers to variables limited to a function or block.
const company = "ABC";
function employee() {
const name = "Alex";
console.log(company); // Accessible
console.log(name); // Accessible
}
employee();
console.log(company); // Accessible
// console.log(name); // Not accessible
A local variable can access an outer variable if the outer scope permits it. The reverse is not true.
24. What is lexical scope?
Lexical scope means that a function’s access to variables is determined by where the function is written in the source code rather than where it is called.
const name = "Alex";
function greet() {
console.log(name);
}
function anotherFunction() {
const name = "Sam";
greet();
}
anotherFunction(); // Alex
greet() was defined in the scope where name refers to "Alex". Calling it from anotherFunction() does not change its lexical environment.
Lexical scope is the foundation of closures.
25. What is the scope chain?
The scope chain is the process JavaScript uses to look for a variable.
When JavaScript encounters a variable inside a function, it first checks the current scope. If the variable is not found, it searches the outer scope and continues until it finds the variable or reaches the outermost scope.
const country = "USA";
function outer() {
const state = "California";
function inner() {
const city = "Los Angeles";
console.log(city);
console.log(state);
console.log(country);
}
inner();
}
outer();
Output:
Los Angeles
California
USA
The inner() function can access variables from its own scope, outer() and the global scope.
26. What is the difference between hoisting and the Temporal Dead Zone?
Hoisting describes declaration availability within a scope before the declaration’s position in the code. The Temporal Dead Zone is the period during which a lexical variable exists in its scope but cannot yet be accessed.
| Hoisting | TDZ |
|---|---|
| Declaration processing before normal execution | Period before lexical variable initialization |
| Applies differently to different declaration types | Applies to let, const and class |
var can be accessed before assignment as undefined | Accessing a lexical variable in the TDZ throws ReferenceError |
27. What happens when a variable is declared without a value?
It depends on the declaration type.
var a;
let b;
console.log(a); // undefined
console.log(b); // undefined
Both variables are initialized with undefined once their declarations are reached. A const declaration cannot omit its initializer.
const c; // SyntaxError
28. What is shadowing in JavaScript?
Shadowing occurs when a variable declared in an inner scope has the same name as a variable from an outer scope.
const name = "Alex";
function greet() {
const name = "Sam";
console.log(name);
}
greet(); // Sam
console.log(name); // Alex
The inner name shadows the outer name inside the function. It does not change the original variable.
29. What is illegal shadowing?
Illegal shadowing happens when a declaration conflicts with another declaration in a scope in a way that JavaScript does not allow.
For example:
let age = 25;
{
// var age = 30; // SyntaxError
}
A var declaration is function-scoped and cannot be used to redeclare a lexical let binding in the same surrounding scope.
However, this is valid:
let age = 25;
{
let age = 30;
console.log(age); // 30
}
console.log(age); // 25
30. What is the difference between a variable and a constant in JavaScript?
A variable declared with let can be reassigned. A binding declared with const cannot be reassigned.
However, a const object or array can still have its contents modified.
const user = {
name: "Alex"
};
user.name = "Sam"; // Allowed
// user = {}; // Not allowed
const protects the binding, not the contents of an object from modification.
4. Operators and Type Coercion Interview Questions
31. What is type coercion in JavaScript?
Type coercion is the conversion of a value from one data type to another.
JavaScript sometimes performs this conversion automatically. This is known as implicit coercion. Developers can also convert types explicitly.
Implicit coercion:
console.log("5" + 2); // "52"
console.log("5" - 2); // 3
The + operator concatenates strings when string conversion applies, while - performs numeric subtraction.
Explicit coercion:
const value = "25";
console.log(Number(value)); // 25
console.log(String(25)); // "25"
console.log(Boolean(1)); // true
Understanding coercion is important because it explains many unexpected JavaScript outputs.
32. What is the difference between == and ===?
The == operator compares values after performing type coercion where necessary. The === operator compares both value and type without performing that coercion.
console.log(5 == "5"); // true
console.log(5 === "5"); // false
More examples:
console.log(null == undefined); // true
console.log(null === undefined); // false
console.log(false == 0); // true
console.log(false === 0); // false
Use strict equality === in most application code because it makes comparisons more predictable.
33. What is the difference between != and !==?
!= checks inequality after type coercion where necessary. !== checks inequality without type coercion.
console.log(5 != "5"); // false
console.log(5 !== "5"); // true
Strict inequality is generally preferred for the same reasons as strict equality.
34. What are truthy and falsy values?
JavaScript values can be evaluated as true or false in conditional expressions.
Falsy values include:
false0-00n""nullundefinedNaN
Most other values are truthy, including empty arrays and empty objects.
if ("hello") {
console.log("Truthy");
}
if ([]) {
console.log("Empty array is truthy");
}
if ({}) {
console.log("Empty object is truthy");
}
Output:
Truthy
Empty array is truthy
Empty object is truthy
35. What is the difference between || and ???
The logical OR operator || returns the right-hand value when the left-hand value is falsy.
The nullish coalescing operator ?? returns the right-hand value only when the left-hand value is null or undefined.
const count = 0;
console.log(count || 10); // 10
console.log(count ?? 10); // 0
This distinction matters when zero, false or an empty string are valid values.
| Value | value || fallback | value ?? fallback |
|—|—|—|
| 0 | Fallback | 0 |
| false | Fallback | false |
| "" | Fallback | "" |
| null | Fallback | Fallback |
| undefined | Fallback | Fallback |
36. What is the ternary operator?
The ternary operator is a conditional expression that evaluates a condition and returns one of two values.
Syntax:
condition ? valueIfTrue : valueIfFalse;
Example:
const age = 20;
const status = age >= 18 ? "Adult" : "Minor";
console.log(status); // Adult
It is useful for short conditional assignments but should not be nested excessively.
37. What is the difference between &&, || and !?
&&returns the first falsy value or the final operand if all are truthy.||returns the first truthy value or the final operand if all are falsy.!converts a value to a Boolean and then negates it.
console.log("Hello" && 10); // 10
console.log(0 || "Default"); // Default
console.log(!true); // false
These are logical operators but they do not always return Boolean values.
38. What is short-circuit evaluation?
Short-circuit evaluation means JavaScript stops evaluating an expression as soon as the result is determined.
const user = null;
console.log(user && user.name);
Because user is falsy, JavaScript does not attempt to evaluate user.name.
This can help prevent errors when accessing properties on values that may be missing.
39. What is the difference between ?? and optional chaining ?.?
Nullish coalescing provides a fallback value. Optional chaining safely accesses a property or calls a function when the value before it is null or undefined.
const user = null;
console.log(user?.name); // undefined
console.log(user ?? "Guest"); // Guest
They can also be combined:
const username = user?.name ?? "Guest";
console.log(username); // Guest
Optional chaining does not protect against every invalid value. For example, trying to access a property on a number is generally valid in JavaScript due to boxing behavior. The operator specifically short-circuits on null and undefined.
40. What is the difference between the + operator and other arithmetic operators?
The + operator can perform numeric addition or string concatenation. Other arithmetic operators generally perform numeric operations after conversion.
console.log(2 + 3); // 5
console.log("2" + 3); // "23"
console.log("2" - 3); // -1
console.log("2" * 3); // 6
This is one of the most common reasons output-based JavaScript questions behave unexpectedly.
41. What is the difference between ++i and i++?
Both increment a variable by one, but their value within an expression differs.
++iincrements first and returns the updated value.i++returns the current value and then increments.
let a = 5;
console.log(++a); // 6
let b = 5;
console.log(b++); // 5
console.log(b); // 6
42. What is the difference between Object.is() and ===?
Both compare values, but Object.is() handles two special cases differently.
console.log(NaN === NaN); // false
console.log(Object.is(NaN, NaN)); // true
console.log(0 === -0); // true
console.log(Object.is(0, -0)); // false
For most ordinary comparisons, they behave the same. Object.is() is useful when these edge cases matter.
43. What is operator precedence?
Operator precedence determines which operations are evaluated first in an expression.
console.log(2 + 3 * 4); // 14
Multiplication is performed before addition.
Use parentheses to make the intended order clear:
console.log((2 + 3) * 4); // 20
Interviewers may test operator precedence through output questions involving arithmetic, comparisons, logical operators and assignments.
5. Functions and Functional Programming Interview Questions
Functions are central to JavaScript. They are used to organize code, reuse logic, handle events, process data and manage asynchronous operations.
44. What is a function in JavaScript?
A function is a reusable block of code designed to perform a specific task. It can accept inputs called parameters and return an output.
function add(a, b) {
return a + b;
}
console.log(add(5, 3)); // 8
Functions can be declared, assigned to variables, passed to other functions and returned from functions.
45. What is the difference between a function declaration and a function expression?
A function declaration defines a function using the function keyword and a name. A function expression creates a function as part of an expression and can assign it to a variable.
Function declaration
function greet() {
console.log("Hello");
}
Function expression
const greet = function() {
console.log("Hello");
};
Function declarations can generally be called before their declaration appears in the code because they are hoisted with their function definition. Function expressions assigned to let or const cannot be called before the variable is initialized.
46. What is an arrow function?
An arrow function is a shorter syntax for creating functions introduced in ES6.
const add = (a, b) => a + b;
console.log(add(5, 3)); // 8
Arrow functions are especially useful for callbacks and short functions.
They differ from regular functions in important ways:
- They do not have their own
this. - They do not have their own
argumentsobject. - They cannot be used as constructors with
new. - They do not have a
prototypeproperty used for constructor behavior.
47. What is the difference between regular functions and arrow functions?
| Regular function | Arrow function |
|---|---|
Has its own this based on how it is called | Inherits this lexically |
Has an arguments object | No own arguments object |
| Can be used as a constructor | Cannot be used as a constructor |
| Can be used as a method | Often unsuitable as an object method when dynamic this is needed |
Has a prototype property when constructible | No constructor prototype property |
Example:
const user = {
name: "Alex",
regular() {
console.log(this.name);
},
arrow: () => {
console.log(this.name);
}
};
user.regular(); // Alex
user.arrow(); // Depends on the outer this
An arrow function does not receive this from user.arrow(). It inherits this from the surrounding lexical scope.
48. What are parameters and arguments?
Parameters are variables defined in a function declaration. Arguments are the actual values supplied when the function is called.
function greet(name) { // name is a parameter
console.log("Hello " + name);
}
greet("Alex"); // "Alex" is an argument
49. What are default parameters?
Default parameters allow a function parameter to have a fallback value when the argument is omitted or passed as undefined.
function greet(name = "Guest") {
console.log(`Hello ${name}`);
}
greet(); // Hello Guest
greet("Alex"); // Hello Alex
A default parameter is not used when the argument is null.
greet(null); // Hello null
50. What are rest parameters?
Rest parameters allow a function to collect multiple arguments into an array using the ... syntax.
function sum(...numbers) {
return numbers.reduce((total, number) => total + number, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
Rest parameters must appear at the end of the parameter list.
51. What is the arguments object?
The arguments object is an array-like object available inside regular functions. It contains the arguments passed to the function.
function showArguments() {
console.log(arguments);
}
showArguments(10, 20, 30);
It is not a true array, so it does not have all standard array methods.
Modern JavaScript generally prefers rest parameters.
function showArguments(...args) {
console.log(args);
}
showArguments(10, 20, 30);
Here args is a real array.
52. What is a callback function?
A callback is a function passed to another function so that it can be called later.
function processUser(name, callback) {
console.log("Processing " + name);
callback();
}
function complete() {
console.log("Finished");
}
processUser("Alex", complete);
Output:
Processing Alex
Finished
Callbacks are commonly used for event handling, asynchronous operations and array methods.
53. What is a higher-order function?
A higher-order function is a function that takes one or more functions as arguments, returns a function, or does both.
function calculate(a, b, operation) {
return operation(a, b);
}
const add = (a, b) => a + b;
const multiply = (a, b) => a * b;
console.log(calculate(5, 3, add)); // 8
console.log(calculate(5, 3, multiply)); // 15
Functions such as map(), filter() and reduce() are higher-order functions because they accept callback functions.
54. What is a pure function?
A pure function produces the same output for the same input and does not cause observable side effects.
function add(a, b) {
return a + b;
}
This function is pure because it depends only on its inputs and does not change external state.
An impure function:
let total = 0;
function addToTotal(value) {
total += value;
return total;
}
Its output depends on and modifies external state.
Pure functions are easier to test, understand and reuse.
55. What is an IIFE?
IIFE stands for Immediately Invoked Function Expression. It is a function expression that runs immediately after it is created.
(function() {
console.log("Runs immediately");
})();
An IIFE can create a private scope for variables.
const result = (function() {
const secret = 100;
return secret * 2;
})();
console.log(result); // 200
IIFEs were commonly used before block-scoped declarations and modules became widespread.
56. What is recursion?
Recursion occurs when a function calls itself to solve a smaller version of a problem.
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5)); // 120
A recursive function must have a base case. Without one, it can continue calling itself until the call stack overflows.
57. What is function currying?
Currying transforms a function that takes multiple arguments into a series of functions that each take one argument.
function multiply(a) {
return function(b) {
return a * b;
};
}
const multiplyByFive = multiply(5);
console.log(multiplyByFive(4)); // 20
Currying allows functions to be partially applied and reused with specific values.
An arrow function version:
const multiply = a => b => a * b;
console.log(multiply(5)(4)); // 20
58. What is function composition?
Function composition combines multiple functions so the output of one becomes the input of another.
const double = x => x * 2;
const addFive = x => x + 5;
const result = double(addFive(3));
console.log(result); // 16
The addFive function runs first, followed by double.
Composition can help create small functions that are combined into more complex operations.
59. What is a generator function?
A generator function can pause its execution and resume later. It is declared using the function* syntax and returns an iterator.
function* numbers() {
yield 1;
yield 2;
yield 3;
}
const iterator = numbers();
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
console.log(iterator.next()); // { value: undefined, done: true }
The yield keyword pauses execution and produces a value.
Generators are useful for custom iteration and certain streaming or step-by-step workflows.
60. What is a function’s return value?
The return value is the value a function sends back to the code that called it.
function square(number) {
return number * number;
}
const result = square(4);
console.log(result); // 16
If a function does not explicitly return a value, it returns undefined.
function greet() {
console.log("Hello");
}
const result = greet();
console.log(result); // undefined
61. What is the difference between return and console.log()?
return sends a value back to the caller. console.log() displays a value in the console.
function add(a, b) {
return a + b;
}
const result = add(2, 3);
console.log(result); // 5
If you use console.log() inside a function but don’t return the result, the function still returns undefined.
function add(a, b) {
console.log(a + b);
}
const result = add(2, 3); // prints 5
console.log(result); // undefined
6. Closures Interview Questions
Closures are one of the most important JavaScript interview topics. Interviewers often use them in output questions, counter implementations, callbacks, event handlers and utility functions.
62. What is a closure in JavaScript?
A closure is a function that retains access to variables from its surrounding lexical scope even after the outer function has finished executing.
function outer() {
const message = "Hello";
function inner() {
console.log(message);
}
return inner;
}
const result = outer();
result(); // Hello
Although outer() has finished executing, inner() still has access to the message variable because it was created inside that scope.
Closures are created naturally when functions are defined within other functions and use variables from their outer scope. MDN
63. How do closures work?
JavaScript functions retain access to their lexical environment. When a function references a variable from an outer scope, that variable remains available while the function can still use it.
function createCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
The returned function maintains access to the same count variable. It does not create a new count every time it is called.
64. What are the practical uses of closures?
Closures are used for:
- Maintaining private state
- Creating function factories
- Implementing counters
- Event handlers
- Callbacks
- Debouncing and throttling
- Memoization
- Module patterns
- Preserving state between function calls
65. How can closures be used to create private variables?
Closures can keep variables inaccessible directly from outside a function while allowing controlled access through returned methods.
function createBankAccount() {
let balance = 1000;
return {
deposit(amount) {
balance += amount;
},
getBalance() {
return balance;
}
};
}
const account = createBankAccount();
account.deposit(500);
console.log(account.getBalance()); // 1500
console.log(account.balance); // undefined
The balance variable is not a public property of the returned object. The methods can access it through their closure.
This is a simple example of encapsulation.
66. What is the difference between a closure and a scope?
Scope determines where a variable can be accessed. A closure is the function and its retained access to the lexical environment in which it was created.
Scope is a language rule. A closure is a behavior that follows from lexical scoping and function objects.
67. What is the closure problem with var inside loops?
When a loop uses var, the variable is shared across iterations because var is function-scoped.
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
Output:
3
3
3
The callbacks execute after the loop has completed. All three callbacks reference the same i variable, whose final value is 3.
68. How do you fix the closure problem in a loop?
Use let, which creates a new binding for each iteration of the loop.
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
Output:
0
1
2
You can also use a function to capture the current value, but let is the straightforward modern solution.
69. Can closures cause memory leaks?
Closures can contribute to memory problems when they retain references to objects or data that are no longer needed.
function createHandler() {
const largeData = new Array(1000000).fill("data");
return function() {
console.log(largeData.length);
};
}
const handler = createHandler();
As long as handler remains reachable, the captured data may also remain reachable.
Closures themselves are not memory leaks. The issue is keeping unnecessary references alive for longer than needed.
7. this, call(), apply() and bind() Interview Questions
70. What is the this keyword in JavaScript?
this refers to a value associated with the current function invocation. In regular functions, its value depends on how the function is called.
const user = {
name: "Alex",
greet() {
console.log(this.name);
}
};
user.greet(); // Alex
Here, this refers to the object before the dot, which is user.
The value of this is not simply determined by where a function is written.
71. How does this behave in a regular function?
In a regular function, this is determined by the call site.
function show() {
console.log(this);
}
show();
In non-strict script code, a plain function call may use the global object as this. In strict mode, a plain function call gives this the value undefined.
When the function is called as a method:
const user = {
name: "Alex",
show() {
console.log(this.name);
}
};
user.show(); // Alex
The method call provides the object as this.
72. How does this behave in arrow functions?
Arrow functions do not create their own this. They use the this value from their surrounding lexical context.
const user = {
name: "Alex",
greet() {
const sayHello = () => {
console.log(this.name);
};
sayHello();
}
};
user.greet(); // Alex
This makes arrow functions useful for callbacks inside methods.
73. Why does this sometimes become undefined?
When a method is extracted from an object and called separately, it no longer receives the original object as its call-site receiver.
const user = {
name: "Alex",
greet() {
console.log(this.name);
}
};
const greet = user.greet;
greet();
In strict mode, this is undefined for this plain function call, so accessing this.name throws a TypeError.
This is commonly encountered when passing methods as callbacks.
74. What is the difference between call(), apply() and bind()?
These methods allow you to control the this value of a regular function.
| Method | What it does | Arguments |
|---|---|---|
call() | Executes the function immediately | Passed individually |
apply() | Executes the function immediately | Passed as an array or array-like object |
bind() | Returns a new function with bound this | Passed individually when binding |
Example:
function greet(city, country) {
console.log(`${this.name} lives in ${city}, ${country}`);
}
const user = { name: "Alex" };
greet.call(user, "Austin", "USA");
greet.apply(user, ["Austin", "USA"]);
const boundGreet = greet.bind(user, "Austin");
boundGreet("USA");
Output:
Alex lives in Austin, USA
Alex lives in Austin, USA
Alex lives in Austin, USA
75. What is bind() used for?
bind() creates a new function with a fixed this value and optionally prefilled arguments.
const user = {
name: "Alex"
};
function greet() {
console.log(this.name);
}
const bound = greet.bind(user);
bound(); // Alex
Unlike call() and apply(), bind() does not immediately execute the function.
76. Can you change this in an arrow function using call() or bind()?
No. Arrow functions use lexical this. Calling call(), apply() or bind() on an arrow function cannot change that thisvalue.
const greet = () => {
console.log(this.name);
};
greet.call({ name: "Alex" });
The arrow function still uses this from the scope in which it was created.
77. What is the difference between this in an object method and a nested function?
An object method called through an object receives that object as this. A nested regular function gets its own thisaccording to its invocation.
const user = {
name: "Alex",
greet() {
function inner() {
console.log(this.name);
}
inner();
}
};
user.greet();
In strict mode, inner() is a plain call, so its this is undefined. This is why accessing this.name throws.
Use an arrow function to inherit the outer method’s this:
const user = {
name: "Alex",
greet() {
const inner = () => {
console.log(this.name);
};
inner();
}
};
user.greet(); // Alex
8. Objects and Object-Oriented JavaScript Interview Questions
JavaScript uses objects extensively. Understanding object creation, property access, prototypes and classes is important for frontend and backend interviews.
78. What is an object in JavaScript?
An object is a collection of properties. Each property has a key and a value. The value can be a primitive, another object or a function.
const employee = {
name: "Alex",
role: "Developer",
salary: 80000,
introduce() {
return `I am ${this.name}`;
}
};
console.log(employee.name); // Alex
console.log(employee.introduce()); // I am Alex
Objects are used to represent data, organize application state and define behavior.
79. What are object properties and methods?
A property stores a value associated with an object. A method is a function stored as an object property and used to perform an operation.
const car = {
brand: "Toyota",
model: "Camry",
start() {
console.log("Car started");
}
};
console.log(car.brand); // Toyota
car.start(); // Car started
brand and model are properties. start() is a method.
80. How do you create objects in JavaScript?
There are several ways.
Object literal
const user = {
name: "Alex",
age: 25
};
Object constructor
const user = new Object();
user.name = "Alex";
user.age = 25;
Constructor function
function User(name) {
this.name = name;
}
const user = new User("Alex");
Class
class User {
constructor(name) {
this.name = name;
}
}
const user = new User("Alex");
Object.create()
const prototype = {
greet() {
console.log("Hello");
}
};
const user = Object.create(prototype);
user.greet();
81. What is the difference between dot notation and bracket notation?
Dot notation uses a property name directly. Bracket notation allows dynamic property names and keys containing characters that cannot be used with dot notation.
const user = {
name: "Alex",
age: 25
};
console.log(user.name);
console.log(user["age"]);
Bracket notation is especially useful when the property name is stored in a variable.
const key = "name";
console.log(user[key]); // Alex
82. How do you add, update and delete object properties?
const user = {
name: "Alex"
};
// Add
user.age = 25;
// Update
user.name = "Sam";
// Delete
delete user.age;
console.log(user);
The delete operator removes a property from an object. It does not delete the entire object or directly free memory.
83. What is object destructuring?
Destructuring allows you to extract properties from objects into variables.
const user = {
name: "Alex",
age: 25,
city: "Austin"
};
const { name, age } = user;
console.log(name); // Alex
console.log(age); // 25
You can rename variables:
const { name: userName } = user;
console.log(userName); // Alex
You can also provide defaults:
const { country = "USA" } = user;
console.log(country); // USA
84. What is the spread operator?
The spread operator expands an iterable or object into individual elements or properties.
Array example
const first = [1, 2, 3];
const second = [...first, 4, 5];
console.log(second); // [1, 2, 3, 4, 5]
Object example
const user = { name: "Alex", age: 25 };
const updatedUser = { ...user, age: 26 };
console.log(updatedUser);
Spread is commonly used for copying arrays and objects, combining data and creating updated values.
85. What is the rest operator?
The rest operator collects remaining values into an array or object.
const [first, ...others] = [10, 20, 30, 40];
console.log(first); // 10
console.log(others); // [20, 30, 40]
In function parameters:
function sum(...values) {
return values.reduce((total, value) => total + value, 0);
}
The same ... syntax is called spread or rest depending on whether it expands or collects values.
86. What is the difference between spread and rest?
| Spread | Rest |
|---|---|
| Expands values | Collects values |
| Used in function calls and array or object literals | Used in function parameters and destructuring |
| Turns an iterable into individual elements | Collects remaining elements |
// Spread
const numbers = [1, 2, 3];
console.log(...numbers);
// Rest
function total(...numbers) {
return numbers.length;
}
87. What is a shallow copy?
A shallow copy copies the outer object or array but does not recursively copy nested objects.
const original = {
name: "Alex",
address: {
city: "Austin"
}
};
const copy = { ...original };
copy.name = "Sam";
copy.address.city = "Dallas";
console.log(original.name); // Alex
console.log(original.address.city); // Dallas
The top-level properties are copied, but both objects still refer to the same nested address object.
88. What is a deep copy?
A deep copy creates a new object structure with nested objects copied as well, rather than retaining shared nested references.
For supported values, structuredClone() provides a built-in way to create deep copies.
const original = {
name: "Alex",
address: {
city: "Austin"
}
};
const copy = structuredClone(original);
copy.address.city = "Dallas";
console.log(original.address.city); // Austin
console.log(copy.address.city); // Dallas
A deep copy has limitations depending on the values being copied. For example, functions cannot be cloned with structuredClone(), and DOM nodes cannot be cloned this way.
89. What is Object.assign()?
Object.assign() copies enumerable own properties from one or more source objects to a target object.
const target = { name: "Alex" };
const source = { age: 25, city: "Austin" };
Object.assign(target, source);
console.log(target);
It modifies the target object and performs a shallow copy.
90. What is the difference between Object.freeze() and Object.seal()?
Object.freeze() | Object.seal() |
|---|---|
| Prevents adding properties | Prevents adding properties |
| Prevents removing properties | Prevents removing properties |
| Prevents changing existing property values | Existing writable properties may still be changed |
| Makes the object more restrictive | Restricts the object’s structure |
const user = { name: "Alex" };
Object.freeze(user);
// user.name = "Sam"; // Cannot change in strict mode
Both are shallow by default. Freezing an object does not automatically freeze nested objects.
91. What is the prototype of an object?
A prototype is another object from which an object can inherit properties and methods.
JavaScript uses a prototype-based inheritance system. An object can access properties from its prototype even when those properties are not defined directly on itself.
const animal = {
eat() {
console.log("Eating");
}
};
const dog = Object.create(animal);
dog.eat(); // Eating
Here, dog inherits the eat() method from animal.
92. What is the prototype chain?
The prototype chain is the sequence of objects JavaScript searches when looking for a property.
If a property does not exist on the current object, JavaScript checks its prototype. It continues until it finds the property or reaches null.
const animal = {
eat() {
console.log("Eating");
}
};
const dog = Object.create(animal);
dog.bark = function() {
console.log("Barking");
};
dog.bark(); // Barking
dog.eat(); // Eating
bark() belongs to dog. eat() is inherited.
93. What is the difference between __proto__ and prototype?
These terms are related but not interchangeable.
prototypeis a property found on certain functions, particularly constructor functions. It is the object that instances created withnewuse as their prototype.__proto__is a legacy accessor for an object’s internal prototype. Modern code can useObject.getPrototypeOf()andObject.setPrototypeOf()instead.
function User(name) {
this.name = name;
}
const user = new User("Alex");
console.log(Object.getPrototypeOf(user) === User.prototype); // true
A common interview mistake is saying that every object has a prototype property. Ordinary objects have an internal prototype, but not necessarily a property named prototype.
94. What is prototypal inheritance?
Prototypal inheritance means objects can inherit properties and methods from other objects through their prototype chain.
const person = {
greet() {
console.log("Hello");
}
};
const employee = Object.create(person);
employee.work = function() {
console.log("Working");
};
employee.greet(); // Hello
employee.work(); // Working
JavaScript’s inheritance model is based on objects inheriting from other objects.
95. What is a constructor function?
A constructor function is a regular function intended to create and initialize objects when called with the new keyword.
function Person(name, age) {
this.name = name;
this.age = age;
}
const person1 = new Person("Alex", 25);
const person2 = new Person("Sam", 30);
console.log(person1.name); // Alex
console.log(person2.name); // Sam
The new keyword creates a new object, connects its prototype to the constructor’s prototype property, calls the constructor with that object as this, and returns the new object unless the constructor explicitly returns a suitable object.
96. What is the new keyword?
The new keyword creates an instance from a constructor function or class.
Conceptually, it:
- Creates a new object.
- Links the new object’s prototype to the constructor’s prototype.
- Executes the constructor with the new object as
this. - Returns the new object unless the constructor returns another object.
function Car(brand) {
this.brand = brand;
}
const car = new Car("Toyota");
console.log(car.brand); // Toyota
97. What are JavaScript classes?
Classes provide syntax for creating objects and organizing methods around constructors and inheritance.
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, ${this.name}`);
}
}
const person = new Person("Alex");
person.greet();
JavaScript classes use the prototype-based object model. Class syntax provides a structured way to work with constructors, methods and inheritance.
98. What is the constructor method in a class?
The constructor() method is a special method used to initialize an instance when a class is instantiated.
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const user = new User("Alex", 25);
It is automatically called when you use new User().
99. What is inheritance in JavaScript classes?
Inheritance allows one class to extend another and reuse its properties and methods.
class Animal {
speak() {
console.log("Animal sound");
}
}
class Dog extends Animal {
bark() {
console.log("Woof");
}
}
const dog = new Dog();
dog.speak(); // Animal sound
dog.bark(); // Woof
The extends keyword creates the inheritance relationship.
100. What is the super keyword?
super is used to access a parent class’s constructor or methods.
class Animal {
constructor(name) {
this.name = name;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
}
const dog = new Dog("Max", "Labrador");
console.log(dog.name); // Max
console.log(dog.breed); // Labrador
In a derived class constructor, you must call super() before accessing this.
101. What is method overriding?
Method overriding occurs when a child class defines a method with the same name as a method inherited from its parent class.
class Animal {
speak() {
console.log("Animal sound");
}
}
class Dog extends Animal {
speak() {
console.log("Woof");
}
}
const dog = new Dog();
dog.speak(); // Woof
The child class’s method is used for this instance’s method call.
102. What are static methods?
Static methods belong to the class itself rather than individual instances.
class MathHelper {
static add(a, b) {
return a + b;
}
}
console.log(MathHelper.add(2, 3)); // 5
You call the method through the class. It is not normally available on instances.
103. What are private class fields?
Private class fields are properties that can only be accessed from within the class where they are declared. They use the #prefix.
class BankAccount {
#balance = 1000;
getBalance() {
return this.#balance;
}
}
const account = new BankAccount();
console.log(account.getBalance()); // 1000
// console.log(account.#balance); // SyntaxError
Private fields are enforced by the language, not merely hidden by naming conventions.
104. What is polymorphism in JavaScript?
Polymorphism means different objects can be used through a common interface while providing their own implementations of behavior.
class Shape {
area() {
return 0;
}
}
class Circle extends Shape {
constructor(radius) {
super();
this.radius = radius;
}
area() {
return Math.PI * this.radius ** 2;
}
}
class Square extends Shape {
constructor(side) {
super();
this.side = side;
}
area() {
return this.side ** 2;
}
}
const shapes = [new Circle(5), new Square(4)];
shapes.forEach(shape => {
console.log(shape.area());
});
Both objects use the area() method, but they calculate it differently.
105. What is encapsulation?
Encapsulation means keeping an object’s internal details controlled and exposing a clear interface for interacting with it.
JavaScript supports encapsulation through:
- Private class fields
- Closures
- Module scope
- Methods that control access to internal state
Encapsulation helps prevent external code from modifying internal data in unintended ways.
106. What is abstraction?
Abstraction means hiding unnecessary implementation details and exposing only the parts needed to use a feature.
For example, when you call:
array.map(number => number * 2);
You use the map() method without needing to implement its internal iteration logic yourself.
In object-oriented programming, abstraction can be achieved through functions, classes, modules and well-defined interfaces.
107. What is composition and how is it different from inheritance?
Inheritance builds relationships between classes or objects where one can extend another. Composition builds functionality by combining smaller components.
Composition often provides more flexibility when functionality needs to be shared across unrelated types.
For example:
const canFly = {
fly() {
console.log("Flying");
}
};
const canSwim = {
swim() {
console.log("Swimming");
}
};
const duck = {
...canFly,
...canSwim
};
duck.fly();
duck.swim();
This example combines behaviors without requiring a deep inheritance hierarchy.
9. Arrays and Array Methods Interview Questions
Array questions are extremely common in JavaScript interviews. You may be asked to explain an array method, compare two methods, transform a dataset or solve a coding problem without using built-in helpers.
108. What is an array in JavaScript?
An array is an ordered collection of values stored in a single variable. Arrays can contain different data types and can grow or shrink dynamically.
const values = [10, "Hello", true, null];
console.log(values[0]); // 10
console.log(values.length); // 4
Arrays are zero-indexed. The first element is at index 0.
109. How do you add and remove elements from an array?
| Method | Action | Changes original array? |
|---|---|---|
push() | Adds to the end | Yes |
pop() | Removes from the end | Yes |
unshift() | Adds to the beginning | Yes |
shift() | Removes from the beginning | Yes |
splice() | Adds or removes at specific positions | Yes |
slice() | Extracts a portion | No |
concat() | Combines arrays | No |
Example:
const numbers = [1, 2, 3];
numbers.push(4);
numbers.unshift(0);
console.log(numbers); // [0, 1, 2, 3, 4]
numbers.pop();
numbers.shift();
console.log(numbers); // [1, 2, 3]
110. What is the difference between slice() and splice()?
slice() returns a shallow copy of a portion of an array without modifying the original. splice() changes the original array by removing, replacing or adding elements.
const numbers = [10, 20, 30, 40, 50];
console.log(numbers.slice(1, 3)); // [20, 30]
console.log(numbers); // Original unchanged
numbers.splice(1, 2);
console.log(numbers); // [10, 40, 50]
slice() | splice() |
|---|---|
| Does not modify original | Modifies original |
| Extracts elements | Removes, inserts or replaces |
| Returns copied portion | Returns removed elements |
111. What is the difference between map() and forEach()?
map() creates and returns a new array containing the results of applying a callback to each element. forEach() runs a callback for each element and returns undefined.
const numbers = [1, 2, 3];
const doubled = numbers.map(number => number * 2);
numbers.forEach(number => {
console.log(number);
});
console.log(doubled); // [2, 4, 6]
Use map() when transforming data into a new array. Use forEach() when you want to perform an action for each item without needing a resulting array.
112. What is the difference between map() and filter()?
map() transforms each element. filter() selects elements that meet a condition.
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(number => number * 2);
const even = numbers.filter(number => number % 2 === 0);
console.log(doubled); // [2, 4, 6, 8, 10]
console.log(even); // [2, 4]
113. What is reduce() in JavaScript?
reduce() processes an array and accumulates its elements into a single result. The result can be a number, string, object, array or any other value.
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((total, number) => {
return total + number;
}, 0);
console.log(sum); // 10
The callback receives:
- The accumulator
- The current element
- The current index
- The original array
The initial value of the accumulator is supplied as the second argument to reduce().
114. How do map(), filter() and reduce() differ?
| Method | Purpose | Returns |
|---|---|---|
map() | Transform every element | New array of mapped results |
filter() | Keep elements that match a condition | New array of selected elements |
reduce() | Accumulate elements into a result | Accumulator result |
Example using all three:
const numbers = [1, 2, 3, 4, 5, 6];
const result = numbers
.filter(number => number % 2 === 0)
.map(number => number * 10)
.reduce((total, number) => total + number, 0);
console.log(result); // 120
The code selects even numbers, multiplies them by 10 and adds the results.
115. What is the difference between find() and filter()?
find() returns the first element that satisfies a condition. filter() returns all elements that satisfy the condition.
const numbers = [5, 10, 15, 20];
const first = numbers.find(number => number > 10);
const all = numbers.filter(number => number > 10);
console.log(first); // 15
console.log(all); // [15, 20]
If find() does not find a matching element, it returns undefined.
116. What is the difference between some() and every()?
some() checks whether at least one element satisfies a condition. every() checks whether all elements satisfy the condition.
const numbers = [2, 4, 6, 8];
console.log(numbers.some(number => number > 5)); // true
console.log(numbers.every(number => number % 2 === 0)); // true
Both return Boolean values.
117. What is the difference between includes() and indexOf()?
includes() returns a Boolean indicating whether an element exists. indexOf() returns the index of the first matching element or -1 if it is not found.
const fruits = ["apple", "banana", "orange"];
console.log(fruits.includes("banana")); // true
console.log(fruits.indexOf("banana")); // 1
console.log(fruits.indexOf("grape")); // -1
118. How do you remove duplicates from an array?
One common approach is to use a Set.
const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]
A Set stores unique values. Converting the set back into an array gives the unique elements.
119. How do you sort an array in JavaScript?
The sort() method sorts array elements in place.
By default, it compares elements as strings, which can produce unexpected results for numbers.
const numbers = [10, 2, 30, 4];
numbers.sort();
console.log(numbers); // [10, 2, 30, 4]
For numerical sorting, use a comparison function:
const numbers = [10, 2, 30, 4];
numbers.sort((a, b) => a - b);
console.log(numbers); // [2, 4, 10, 30]
For descending order:
numbers.sort((a, b) => b - a);
120. How do you reverse an array?
The reverse() method reverses the elements of an array in place.
const numbers = [1, 2, 3, 4];
numbers.reverse();
console.log(numbers); // [4, 3, 2, 1]
If you want to keep the original array unchanged:
const original = [1, 2, 3];
const reversed = [...original].reverse();
console.log(original); // [1, 2, 3]
console.log(reversed); // [3, 2, 1]
121. What is array destructuring?
Array destructuring allows you to assign array elements to variables based on their positions.
const colors = ["red", "green", "blue"];
const [first, second] = colors;
console.log(first); // red
console.log(second); // green
You can skip elements:
const [first, , third] = colors;
console.log(third); // blue
122. What is the difference between for...in and for...of?
for...in iterates over enumerable property keys. for...of iterates over values provided by an iterable.
const numbers = [10, 20, 30];
for (const index in numbers) {
console.log(index);
}
for (const value of numbers) {
console.log(value);
}
Output:
0
1
2
10
20
30
For arrays, for...of is usually the better choice when you want the values. for...in is generally intended for enumerating object keys.
123. What is the difference between forEach() and for...of?
Both can iterate over arrays, but for...of supports break, continue and await in an async function when used with appropriate iterables.
forEach() does not allow you to break out of its iteration using break, and it does not wait for promises returned by its callback.
const numbers = [1, 2, 3];
for (const number of numbers) {
if (number === 2) break;
console.log(number);
}
This makes for...of a better choice when you need control over iteration.
124. What is Array.from()?
Array.from() creates a new array from an iterable or array-like object.
const text = "hello";
const letters = Array.from(text);
console.log(letters); // ["h", "e", "l", "l", "o"]
It can also accept a mapping function:
const numbers = Array.from([1, 2, 3], number => number * 2);
console.log(numbers); // [2, 4, 6]
125. What is Array.isArray()?
Array.isArray() checks whether a value is an array.
console.log(Array.isArray([1, 2, 3])); // true
console.log(Array.isArray({})); // false
It is a reliable way to identify arrays compared with using typeof, which returns "object" for arrays.
126. What is array flattening?
Array flattening converts nested arrays into a single-level array or reduces their nesting.
const numbers = [1, [2, 3], [4, [5]]];
console.log(numbers.flat()); // [1, 2, 3, 4, [5]]
console.log(numbers.flat(2)); // [1, 2, 3, 4, 5]
The flat() method accepts a depth. The default is 1.
127. What is the difference between flat() and flatMap()?
flat() flattens nested arrays. flatMap() maps each element and then flattens the result by one level.
const numbers = [1, 2, 3];
const result = numbers.flatMap(number => [number, number * 2]);
console.log(result); // [1, 2, 2, 4, 3, 6]
flatMap() is useful when one input element may produce zero, one or several output elements.
128. What is the difference between push() and concat()?
push() modifies the original array by adding elements. concat() returns a new combined array without modifying the originals.
const first = [1, 2];
const second = [3, 4];
first.push(...second);
console.log(first); // [1, 2, 3, 4]
const a = [1, 2];
const b = a.concat([3, 4]);
console.log(a); // [1, 2]
console.log(b); // [1, 2, 3, 4]
129. What is an immutable array operation?
An immutable operation produces a new array without changing the original array.
const numbers = [1, 2, 3];
const updated = numbers.map(number => number * 2);
console.log(numbers); // [1, 2, 3]
console.log(updated); // [2, 4, 6]
Methods such as map(), filter(), slice() and concat() are commonly used for immutable transformations. Methods such as push(), pop(), splice() and reverse() modify the original array.
10. String Interview Questions
130. What is a string in JavaScript?
A string is a sequence of characters used to represent text.
const name = "Alex";
const message = "Hello World";
Strings are immutable. Methods that appear to modify a string return a new string instead.
131. How do you reverse a string?
One common approach is to convert the string into an array, reverse the array and join it back into a string.
const text = "hello";
const reversed = text.split("").reverse().join("");
console.log(reversed); // olleh
This works for many basic examples, but it is not fully Unicode-safe for all characters such as emoji and some combined characters.
132. How do you check whether a string contains a substring?
Use includes().
const text = "JavaScript interview preparation";
console.log(text.includes("interview")); // true
You can also use indexOf() or regular expressions depending on the requirement.
133. What is a template literal?
A template literal is a string written using backticks. It supports variable interpolation and multiline strings.
const name = "Alex";
const age = 25;
const message = `My name is ${name} and I am ${age}.`;
console.log(message);
Template literals make string formatting more readable than concatenating multiple strings with +.
134. What is the difference between substring(), slice() and substr()?
| Method | Description |
|---|---|
slice() | Extracts a portion using start and end positions. Supports negative indices. |
substring() | Extracts between start and end positions. Negative values are treated as zero. |
substr() | Extracts a specified length starting at a position. It is legacy and should generally be avoided. |
const text = "JavaScript";
console.log(text.slice(0, 4)); // Java
console.log(text.substring(0, 4)); // Java
135. How do you convert a string to uppercase or lowercase?
Use toUpperCase() or toLowerCase().
const text = "JavaScript";
console.log(text.toUpperCase()); // JAVASCRIPT
console.log(text.toLowerCase()); // javascript
These methods return new strings and do not change the original.
136. What is the difference between trim(), trimStart() and trimEnd()?
trim()removes whitespace from both ends.trimStart()removes whitespace from the beginning.trimEnd()removes whitespace from the end.
const text = " Hello World ";
console.log(text.trim());
console.log(text.trimStart());
console.log(text.trimEnd());
These methods do not remove spaces in the middle of the string.
137. What is the difference between split() and join()?
split() converts a string into an array based on a separator. join() converts array elements into a string using a separator.
const text = "red,green,blue";
const colors = text.split(",");
console.log(colors); // ["red", "green", "blue"]
console.log(colors.join(" - ")); // red - green - blue
138. What are regular expressions in JavaScript?
Regular expressions are patterns used to search, match, validate or replace text.
const email = "alex@example.com";
const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(pattern.test(email)); // true
Regular expressions can be used for:
- Input validation
- Searching strings
- Extracting text
- Replacing text
- Matching patterns
The example is a basic email format check, not a complete email validation system.
11. Map, Set and Other Data Structures
JavaScript includes collections that provide different ways to store and work with data.
139. What is a Map in JavaScript?
A Map stores key-value pairs. Unlike ordinary objects, its keys can be values of any type, including objects and functions.
const map = new Map();
map.set("name", "Alex");
map.set(1, "One");
console.log(map.get("name")); // Alex
console.log(map.get(1)); // One
console.log(map.size); // 2
A Map preserves insertion order and provides methods such as set(), get(), has(), delete() and clear().
140. What is the difference between Map and Object?
Map | Object |
|---|---|
| Keys can be any value | Keys are strings or symbols |
Has a built-in size property | No direct size property |
| Designed for key-value collections | Often used for structured records |
| Preserves insertion order for iteration | Property ordering follows defined rules |
| Has collection-specific methods | Uses object property operations |
Use Map when you need a flexible key-value collection. Use an ordinary object when representing structured data with named properties.
141. What is a Set in JavaScript?
A Set is a collection that stores unique values.
const set = new Set([1, 2, 2, 3, 4]);
console.log(set); // Set(4) {1, 2, 3, 4}
Sets automatically remove duplicate values according to their equality rules.
142. How do you use a Set to remove duplicates?
const numbers = [1, 2, 2, 3, 4, 4];
const unique = [...new Set(numbers)];
console.log(unique); // [1, 2, 3, 4]
This is one of the simplest ways to remove duplicates from an array.
143. What is the difference between Map and Set?
| Map | Set |
|---|---|
| Stores key-value pairs | Stores values only |
| Keys are unique | Values are unique |
Use get() to retrieve values | No key-value lookup |
| Useful for lookup tables | Useful for unique collections |
144. What is a WeakMap?
A WeakMap stores key-value pairs where keys must be objects or non-registered symbols that are permitted as weak keys by the language.
Unlike a regular Map, a WeakMap does not strongly keep its object keys alive. If a key object is otherwise no longer reachable, it can be garbage-collected.
const weakMap = new WeakMap();
let user = { name: "Alex" };
weakMap.set(user, "Private data");
console.log(weakMap.get(user)); // Private data
WeakMaps are not enumerable and do not expose a size property. They are useful for associating data with objects without extending the lifetime of those objects solely because they are keys in the WeakMap.
145. What is a WeakSet?
A WeakSet stores unique object references as weak values. It cannot store primitive values and does not keep its objects alive solely because they are members.
const weakSet = new WeakSet();
const user = { name: "Alex" };
weakSet.add(user);
console.log(weakSet.has(user)); // true
WeakSets are useful for tracking objects without preventing their garbage collection.
146. What is the difference between Map and WeakMap?
| Map | WeakMap |
|---|---|
| Keys can be any value | Keys must be objects or supported weak-key symbols |
| Strongly holds keys | Weakly holds eligible keys |
| Enumerable | Not enumerable |
Has size | No size |
| Can be iterated | Cannot be iterated |
147. What is a queue and how can you implement one in JavaScript?
A queue follows the First In First Out (FIFO) principle. The first element added is the first one removed.
class Queue {
constructor() {
this.items = [];
}
enqueue(value) {
this.items.push(value);
}
dequeue() {
return this.items.shift();
}
peek() {
return this.items[0];
}
isEmpty() {
return this.items.length === 0;
}
}
const queue = new Queue();
queue.enqueue(10);
queue.enqueue(20);
console.log(queue.dequeue()); // 10
console.log(queue.peek()); // 20
For high-volume queues, repeatedly using shift() can be inefficient because it moves array elements. A queue implemented with a moving head index or linked structure can avoid that cost.
148. What is a stack and how can you implement one?
A stack follows the Last In First Out (LIFO) principle. The last element added is the first one removed.
class Stack {
constructor() {
this.items = [];
}
push(value) {
this.items.push(value);
}
pop() {
return this.items.pop();
}
peek() {
return this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length === 0;
}
}
const stack = new Stack();
stack.push(10);
stack.push(20);
console.log(stack.pop()); // 20
console.log(stack.peek()); // 10
Stacks are used in function execution, undo operations, expression evaluation and many algorithmic problems.
12. Asynchronous JavaScript Interview Questions
Asynchronous JavaScript is a major interview topic. Developers need to understand how JavaScript handles operations that take time without blocking normal execution.
149. What is synchronous programming?
Synchronous programming executes operations in sequence. Each operation must finish before the next operation continues in that execution flow.
console.log("First");
console.log("Second");
console.log("Third");
Output:
First
Second
Third
150. What is asynchronous programming?
Asynchronous programming allows operations to complete later without holding up the main execution flow while waiting for them to finish.
For example, a network request may take time. Instead of blocking JavaScript until the response arrives, the application can continue performing other work.
console.log("Start");
setTimeout(() => {
console.log("Timer completed");
}, 1000);
console.log("End");
Output:
Start
End
Timer completed
The timer callback runs later.
151. What is the difference between synchronous and asynchronous code?
| Synchronous | Asynchronous |
|---|---|
| Executes in the current sequence | Completion is handled later |
| Can block subsequent operations | Allows other work to proceed while waiting |
| Easier to follow sequentially | Requires understanding callbacks or promise-based flow |
| Common for simple calculations | Common for network requests, timers and I/O |
Asynchronous programming does not mean that JavaScript is executing several pieces of code simultaneously on the same thread. It means the runtime can coordinate operations and schedule their continuations without blocking that thread unnecessarily.
152. What is a callback in asynchronous JavaScript?
A callback is a function that is called after an operation completes or when a particular event occurs.
function getData(callback) {
setTimeout(() => {
callback("Data received");
}, 1000);
}
getData(data => {
console.log(data);
});
Callbacks were widely used for asynchronous operations before promises became common.
153. What is callback hell?
Callback hell occurs when callbacks are deeply nested, making code difficult to read, maintain and handle errors.
getUser(function(user) {
getOrders(user, function(orders) {
getProducts(orders, function(products) {
processProducts(products, function(result) {
console.log(result);
});
});
});
});
This structure can become difficult to manage as operations increase.
Promises and async/await help flatten this structure and improve readability.
154. What is a Promise in JavaScript?
A Promise is an object representing the eventual completion or failure of an asynchronous operation and its resulting value.
A promise has three states:
| State | Meaning |
|---|---|
| Pending | The operation has not settled |
| Fulfilled | The operation completed successfully |
| Rejected | The operation failed |
Once a promise becomes fulfilled or rejected, it is settled and cannot change to another state.
const promise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve("Operation successful");
} else {
reject("Operation failed");
}
});
promise
.then(result => console.log(result))
.catch(error => console.error(error));
155. How do you create a Promise?
A promise is created using the Promise constructor, which accepts an executor function with resolve and rejectparameters.
const promise = new Promise((resolve, reject) => {
const result = 10;
if (result > 0) {
resolve(result);
} else {
reject(new Error("Invalid result"));
}
});
The executor runs immediately when the promise is constructed. resolve() fulfills the promise with a value or adopts another promise’s state. reject() rejects it.
156. What are resolve() and reject()?
resolve() fulfills a promise with a value, or causes it to adopt the state of another promise or thenable. reject() rejects a promise with a reason.
const success = Promise.resolve("Done");
const failure = Promise.reject(new Error("Failed"));
success.then(console.log);
failure.catch(error => console.log(error.message));
157. What is .then() in a Promise?
The then() method registers handlers for fulfillment and optionally rejection. It returns a new promise, which allows chaining.
Promise.resolve(5)
.then(value => value * 2)
.then(value => value + 10)
.then(console.log); // 20
Each then() receives the result of the previous promise chain, unless the previous handler returns another promise, in which case the chain waits for it.
158. What is .catch()?
catch() registers a rejection handler for the promise chain.
Promise.reject(new Error("Something went wrong"))
.catch(error => {
console.log(error.message);
});
It is equivalent to calling then(undefined, onRejected).
159. What is .finally()?
finally() registers a callback that runs after a promise settles, whether fulfilled or rejected.
fetch("/api/data")
.then(response => response.json())
.catch(error => console.error(error))
.finally(() => {
console.log("Request finished");
});
It is commonly used for cleanup tasks such as hiding loading indicators.
The callback generally does not receive the fulfillment value or rejection reason. If finally() returns normally, the original result or rejection is preserved. If it throws or returns a rejected promise, that can change the chain’s outcome.
160. What is Promise chaining?
Promise chaining means connecting multiple then() handlers so asynchronous operations can run in sequence.
fetch("/api/user")
.then(response => response.json())
.then(user => fetch(`/api/orders/${user.id}`))
.then(response => response.json())
.then(orders => console.log(orders))
.catch(error => console.error(error));
Each handler returns a value or promise that becomes the result for the next handler.
161. What is the difference between async and await?
async declares a function that returns a promise. await pauses the execution of that async function until the awaited promise settles, then resumes with its result or throws its rejection.
async function getData() {
const result = await Promise.resolve("Hello");
console.log(result);
}
getData();
An async function always returns a promise.
async function greet() {
return "Hello";
}
greet().then(console.log); // Hello
162. Does await block the entire JavaScript application?
No. await suspends the execution of the async function containing it, not the entire JavaScript thread or application.
async function task() {
console.log("Task started");
await new Promise(resolve => setTimeout(resolve, 1000));
console.log("Task completed");
}
console.log("Outside");
task();
console.log("Continues");
Output:
Outside
Task started
Continues
Task completed
JavaScript can continue executing other code while the async function is suspended.
163. What is the difference between Promise.all() and Promise.allSettled()?
Promise.all() fulfills when all promises fulfill. It rejects as soon as one input promise rejects.
Promise.allSettled() waits for all input promises to settle and returns their outcomes.
const promises = [
Promise.resolve("Success"),
Promise.reject("Failure"),
Promise.resolve("Another success")
];
Promise.allSettled(promises).then(console.log);
The returned array contains an outcome object for each promise with either a status of "fulfilled" and a value, or a status of "rejected" and a reason.
Promise.all() | Promise.allSettled() |
|---|---|
| Rejects if an input rejects | Waits for all outcomes |
| Returns values if all fulfill | Returns status objects |
| Useful when all results are required for success | Useful when every result matters even if some fail |
164. What is Promise.race()?
Promise.race() settles with the outcome of the first input promise to settle, whether fulfillment or rejection.
const first = new Promise(resolve => {
setTimeout(() => resolve("First"), 1000);
});
const second = new Promise(resolve => {
setTimeout(() => resolve("Second"), 500);
});
Promise.race([first, second]).then(console.log);
Output:
Second
It can be used for timeouts or racing multiple operations, but it does not automatically cancel the promises that lose the race.
165. What is Promise.any()?
Promise.any() fulfills with the first input promise to fulfill. It ignores rejections unless all input promises reject.
const promises = [
Promise.reject("Error 1"),
Promise.resolve("Success"),
Promise.reject("Error 2")
];
Promise.any(promises).then(console.log); // Success
If every input rejects, Promise.any() rejects with an AggregateError containing the rejection reasons.
166. What is the difference between Promise.all(), race(), allSettled()and any()?
| Method | Result |
|---|---|
Promise.all() | All fulfill or first rejection |
Promise.race() | First promise to settle |
Promise.allSettled() | All promises settle |
Promise.any() | First fulfillment or AggregateError if all reject |
167. What is the event loop in JavaScript?
The event loop is the mechanism that coordinates JavaScript execution with queued work such as events, timers and asynchronous operation completions.
JavaScript executes synchronous code on the current call stack. When asynchronous operations complete, their associated callbacks or continuations are scheduled to run when the execution stack and scheduling rules permit.
The event loop allows JavaScript environments to handle asynchronous work without blocking the main execution thread while waiting for every operation to finish.Â
168. What is the call stack?
The call stack tracks functions that are currently executing.
function first() {
second();
}
function second() {
third();
}
function third() {
console.log("Hello");
}
first();
When first() calls second(), and second() calls third(), each function is added to the stack. Once a function finishes, it is removed.
169. What are microtasks and tasks?
JavaScript runtimes schedule different types of work.
- Tasks are often called macrotasks informally. They include events and timer callbacks.
- Microtasks include promise reaction callbacks and
queueMicrotask()callbacks.
Microtasks are processed at microtask checkpoints, generally after the current task’s synchronous execution finishes and before the runtime moves on to another task. The browser’s event-loop model includes more details such as rendering opportunities and multiple task sources.
170. What is the difference between a microtask and a macrotask?
| Microtask | Task or macrotask |
|---|---|
| Promise handlers | Timer callbacks |
queueMicrotask() | Many event callbacks |
| Runs at microtask checkpoints | Selected by event-loop scheduling |
| Microtasks are drained before moving to the next task | Tasks are processed by the event loop |
“Macrotask” is common interview terminology, while the browser specifications generally refer to tasks and task queues.
171. What is the execution order of synchronous code, promises and setTimeout()?
Synchronous code runs first. Promise handlers are scheduled as microtasks. Timer callbacks run later as tasks.
console.log("A");
setTimeout(() => {
console.log("B");
}, 0);
Promise.resolve().then(() => {
console.log("C");
});
console.log("D");
Output:
A
D
C
B
Why?
Aexecutes immediately.- The timer callback is scheduled.
- The promise handler is queued as a microtask.
Dexecutes immediately.- The synchronous stack finishes.
- The promise microtask runs and prints
C. - The timer task runs later and prints
B.
A timer delay of zero does not mean the callback executes immediately.
172. What is setTimeout()?
setTimeout() schedules a callback to run after a minimum delay, once the runtime can execute it.
setTimeout(() => {
console.log("Executed");
}, 1000);
It does not guarantee that the callback runs exactly one second later. Other work, scheduling and runtime conditions can delay it.
173. What is setInterval()?
setInterval() schedules a callback to run repeatedly at a specified interval.
const interval = setInterval(() => {
console.log("Running");
}, 1000);
To stop it:
clearInterval(interval);
The delay is not an exact guarantee of timing, and callbacks can be delayed by other work.
174. What is the difference between setTimeout() and setInterval()?
setTimeout() | setInterval() |
|---|---|
| Runs a callback once after a delay | Schedules repeated callbacks |
Use clearTimeout() to cancel | Use clearInterval() to cancel |
| Can be recursively scheduled | Repeats until cancelled |
175. What is queueMicrotask()?
queueMicrotask() schedules a function to run in the microtask queue.
console.log("Start");
queueMicrotask(() => {
console.log("Microtask");
});
console.log("End");
Output:
Start
End
Microtask
It is useful when you need to schedule work after the current synchronous execution but before the event loop proceeds to another task.
176. What is AbortController?
AbortController provides a mechanism for cancelling certain asynchronous operations, such as a fetch() request.
const controller = new AbortController();
fetch("/api/data", {
signal: controller.signal
})
.then(response => response.json())
.catch(error => console.log(error.name));
controller.abort();
When the request is aborted, the promise rejects with an abort-related error.
It is useful for cancelling requests when a user navigates away from a page or when a newer request replaces an older one.
177. What is the difference between concurrency and parallelism?
Concurrency means multiple operations can make progress over overlapping periods of time. Parallelism means multiple operations are actually executing simultaneously.
JavaScript can coordinate many asynchronous operations concurrently through its runtime. Actual parallel execution may be provided through workers or runtime mechanisms.
This distinction is important because using Promise.all() does not itself guarantee CPU parallelism.
178. Can you use await outside an async function?
In modern JavaScript modules, top-level await is supported.
const response = await fetch("/api/data");
const data = await response.json();
console.log(data);
Top-level await is supported in modules but not generally in classic scripts.
13. DOM and Browser Interview Questions
These questions are especially important for frontend developer interviews because JavaScript often interacts with HTML through the Document Object Model.
179. What is the DOM?
The DOM stands for Document Object Model. It is a programming interface that represents an HTML or XML document as a structured tree of nodes.
JavaScript can use the DOM to:
- Select elements
- Change text and HTML
- Change styles
- Add or remove elements
- Handle events
- Modify attributes
For example:
document.querySelector("h1").textContent = "Welcome";
This changes the text of the first matching heading.
180. What is the difference between the DOM and HTML?
HTML is the markup used to describe the structure of a webpage. The DOM is the document representation that the browser exposes to scripts.
JavaScript interacts with the DOM rather than directly rewriting the original HTML file.
181. What is the difference between getElementById() and querySelector()?
getElementById() selects an element by its ID. querySelector() selects the first element that matches a CSS selector.
const element1 = document.getElementById("title");
const element2 = document.querySelector(".heading");
const element3 = document.querySelector("p");
querySelector() is more flexible because it supports CSS selectors.
182. What is the difference between querySelector() and querySelectorAll()?
querySelector() returns the first matching element. querySelectorAll() returns a static NodeList containing all matching elements.
const first = document.querySelector(".item");
const all = document.querySelectorAll(".item");
The NodeList returned by querySelectorAll() is static. It does not automatically update when new matching elements are added to the DOM.
183. What is the difference between innerHTML, innerText and textContent?
| Property | Behavior |
|---|---|
innerHTML | Reads or writes HTML markup inside an element |
innerText | Reads or writes rendered text and considers layout |
textContent | Reads or writes text content without parsing HTML |
Example:
const element = document.querySelector("#content");
element.innerHTML = "<strong>Hello</strong>";
element.textContent = "<strong>Hello</strong>";
With innerHTML, the text becomes bold markup. With textContent, the tags are displayed as text.
When inserting untrusted content, use textContent rather than innerHTML to avoid introducing HTML injection vulnerabilities.
184. How do you create and add elements to the DOM?
Use methods such as createElement() and append().
const paragraph = document.createElement("p");
paragraph.textContent = "New paragraph";
document.body.append(paragraph);
You can also use appendChild().
185. How do you remove an element from the DOM?
Use remove().
const element = document.querySelector("#item");
element.remove();
You can also remove a child using methods on its parent, though remove() is usually simpler.
186. What is event handling in JavaScript?
Event handling allows JavaScript to respond to actions such as clicks, keyboard input, form submissions, mouse movement and browser events.
const button = document.querySelector("#button");
button.addEventListener("click", () => {
console.log("Clicked");
});
The function passed to addEventListener() is called when the event occurs.
187. What is event bubbling?
Event bubbling means an event can propagate from the target element upward through its ancestors.
For example, when a button inside a div is clicked, the click event can be handled by the button, then the div, then other ancestors.
document.querySelector("#parent").addEventListener("click", () => {
console.log("Parent clicked");
});
document.querySelector("#child").addEventListener("click", () => {
console.log("Child clicked");
});
Clicking the child typically prints:
Child clicked
Parent clicked
188. What is event capturing?
Event capturing is the propagation phase in which an event travels from the outer ancestors toward the target element.
You can register an event listener for the capturing phase using the third argument of addEventListener().
element.addEventListener("click", handler, true);
The third argument can also be an options object:
element.addEventListener("click", handler, {
capture: true
});
189. What is the difference between event bubbling and event capturing?
| Event bubbling | Event capturing |
|---|---|
| Target to outer ancestors | Outer ancestors to target |
| Default behavior for many event listeners | Must be enabled when registering |
| Useful for event delegation | Useful when an ancestor must intercept before the target |
An event may pass through capturing, target and bubbling phases depending on its type and listener configuration.
190. What is event delegation?
Event delegation means attaching an event listener to a parent element and handling events from its children by checking the event target.
document.querySelector("#list").addEventListener("click", event => {
if (event.target.matches("li")) {
console.log(event.target.textContent);
}
});
Instead of adding listeners to every list item, a single listener handles clicks on the list.
Benefits include:
- Fewer event listeners
- Better handling of dynamically added elements
- Less repetitive code
- Easier event management
191. What is event.target?
event.target refers to the element that originally triggered the event.
document.addEventListener("click", event => {
console.log(event.target);
});
If the user clicks a button, the target is typically the button.
192. What is event.currentTarget?
event.currentTarget refers to the element whose listener is currently executing.
parent.addEventListener("click", event => {
console.log(event.target);
console.log(event.currentTarget);
});
When a child is clicked, target may be the child while currentTarget is the parent.
193. What is preventDefault()?
preventDefault() prevents the browser’s default action for an event when the event is cancelable.
document.querySelector("a").addEventListener("click", event => {
event.preventDefault();
console.log("Link navigation prevented");
});
For a form, it can prevent a normal page submission.
194. What is stopPropagation()?
stopPropagation() prevents the event from continuing through its propagation path.
child.addEventListener("click", event => {
event.stopPropagation();
});
It does not prevent the default browser action. That is the job of preventDefault().
195. What is the difference between preventDefault() and stopPropagation()?
preventDefault() | stopPropagation() |
|---|---|
| Prevents the default action | Stops further propagation |
| Does not automatically stop bubbling | Does not automatically prevent the default action |
| Used for form submission or navigation control | Used to control event propagation |
196. What is the difference between DOMContentLoaded and load?
DOMContentLoaded fires when the HTML has been parsed and the DOM is ready. It does not wait for every image or other resource to finish loading.
The load event fires when the page and dependent resources have finished loading.
document.addEventListener("DOMContentLoaded", () => {
console.log("DOM ready");
});
window.addEventListener("load", () => {
console.log("Page and resources loaded");
});
197. What is the difference between defer and async in script loading?
Both attributes affect how external scripts are loaded and executed.
defer | async |
|---|---|
| Downloads while HTML parsing continues | Downloads while HTML parsing continues |
| Executes after parsing completes | Executes when download finishes |
| Deferred scripts preserve document order | Execution order is not guaranteed |
Fires before DOMContentLoaded | May execute before or after DOM parsing finishes |
For scripts that depend on the parsed DOM and each other, defer is often more suitable.
198. What is a browser event?
A browser event is an occurrence that the browser exposes to JavaScript, such as a click, keypress, page load, form submission or pointer movement.
JavaScript can register handlers to respond to these events.
199. What is the difference between focus and blur?
focusoccurs when an element receives focus.bluroccurs when an element loses focus.
These events are commonly used for form interactions, accessibility and input validation.
200. What is the difference between mouseover and mouseenter?
mouseover can fire when the pointer moves onto an element or one of its descendants. mouseenter fires when the pointer enters the element itself and does not bubble.
This difference can matter when working with nested elements and event delegation.
14. Browser Storage and Web APIs Interview Questions
201. What is localStorage?
localStorage is a browser storage API that allows websites to store data as key-value pairs. The data persists across browser sessions until it is cleared.
localStorage.setItem("username", "Alex");
const username = localStorage.getItem("username");
console.log(username); // Alex
It stores strings, so objects need to be serialized.
const user = {
name: "Alex",
age: 25
};
localStorage.setItem("user", JSON.stringify(user));
const savedUser = JSON.parse(localStorage.getItem("user"));
console.log(savedUser.name); // Alex
202. What is sessionStorage?
sessionStorage stores data for a browser page session. It is generally available for the lifetime of the tab or window session and is cleared when that session ends.
sessionStorage.setItem("token", "example");
console.log(sessionStorage.getItem("token"));
Unlike localStorage, session storage is not designed to persist across separate browsing sessions.
203. What is the difference between localStorage, sessionStorage and cookies?
| Feature | localStorage | sessionStorage | Cookies |
|---|---|---|---|
| Persistence | Until cleared | Tab or page session | Depends on expiry settings |
| Storage | Browser-side | Browser-side | Browser-side |
| Sent with HTTP requests automatically | No | No | Yes, when applicable |
| Typical use | Preferences and non-sensitive state | Temporary session state | Server-related session or state |
| Size | Larger than cookies in typical browser limits | Larger than cookies in typical browser limits | Much smaller |
Do not store sensitive data in browser storage without understanding the security risks. Cookies with appropriate security attributes are often used for authentication-related server interactions.
204. What is IndexedDB?
IndexedDB is a browser API for storing structured data, including larger amounts of data, locally.
Unlike localStorage, it supports database-style storage, indexes, transactions and asynchronous operations.
It can be used for:
- Offline applications
- Cached data
- Large structured datasets
- Progressive web apps
- Data that needs to be queried
205. What is the Fetch API?
The Fetch API provides a modern way to make HTTP requests from JavaScript.
fetch("https://api.example.com/users")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
It returns a promise that resolves to a Response object when the request receives a response.
206. Does fetch() reject when a server returns a 404 or 500 response?
Not by default. fetch() generally fulfills when an HTTP response is received, even if the status is 404 or 500.
You need to check response.ok or response.status.
async function getData() {
const response = await fetch("/api/data");
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return response.json();
}
The promise can reject for network-level failures or other errors, but HTTP error status codes alone do not normally cause rejection.
207. What is CORS?
CORS stands for Cross-Origin Resource Sharing. It is a browser security mechanism that allows a server to specify which origins may access its resources through browser-based cross-origin requests.
An origin is defined by its scheme, host and port.
For example, these are different origins:
https://example.comhttps://api.example.comhttp://example.com
A server can allow or restrict cross-origin requests through HTTP response headers. Some requests require a preflight request before the browser sends the actual request.
CORS is enforced by browsers. It is not a general-purpose authentication or authorization mechanism.
208. What is JSON?
JSON stands for JavaScript Object Notation. It is a text format commonly used to exchange structured data between applications.
{
"name": "Alex",
"age": 25,
"active": true
}
JSON supports strings, numbers, Boolean values, arrays, objects and null.
209. What is the difference between JSON.stringify() and JSON.parse()?
JSON.stringify() converts a JavaScript value into a JSON string. JSON.parse() converts valid JSON text into a JavaScript value.
const user = {
name: "Alex",
age: 25
};
const json = JSON.stringify(user);
const parsed = JSON.parse(json);
console.log(json);
console.log(parsed.name);
These methods are commonly used when sending data to APIs or storing structured data in string-based storage.
210. What is the difference between JSON and a JavaScript object?
| JSON | JavaScript object |
|---|---|
| Text-based data format | JavaScript runtime value |
| Uses strict syntax rules | Can contain functions and many other value types |
| Keys and string values use double quotes | Property names can often be written without quotes |
Does not support functions or undefined as JSON values | Can contain functions and undefined |
| Used for data exchange | Used for data and behavior within applications |
15. JavaScript Modules, Error Handling and Tooling
211. What are JavaScript modules?
Modules allow JavaScript code to be divided into separate files. Each file can export functionality and import functionality from other files.
Modules help organize larger applications and make code easier to maintain and reuse.
212. What is the difference between named exports and default exports?
Named exports allow a file to export multiple named values. A default export provides one primary exported value.
Named exports:
// math.js
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
Import them:
import { add, subtract } from "./math.js";
Default export:
// greet.js
export default function greet() {
console.log("Hello");
}
Import it:
import greet from "./greet.js";
A module can have one default export and multiple named exports.
213. What is the difference between import and require()?
import is the syntax used by ECMAScript modules. require() is commonly associated with CommonJS modules.
| ES Modules | CommonJS |
|---|---|
import and export | require() and module.exports |
| Standard JavaScript module system | Node.js’s traditional module system |
| Static imports are analyzed before execution | require() is generally called at runtime |
Supports top-level await in modules | Does not support ES module top-level await in the same way |
ES modules are the standard JavaScript module system. Node.js supports both systems, with file extensions and package configuration determining how modules are interpreted.
214. What is CommonJS?
CommonJS is a module format commonly used in Node.js.
// math.js
function add(a, b) {
return a + b;
}
module.exports = add;
Importing it:
const add = require("./math");
console.log(add(2, 3)); // 5
CommonJS is still found in many existing Node.js projects.
215. What is strict mode?
Strict mode enables a stricter set of JavaScript rules that help catch certain mistakes and change some language behaviors.
"use strict";
x = 10; // ReferenceError
Without strict mode in certain non-module contexts, assigning to an undeclared variable may create a global property. Strict mode prevents that.
JavaScript modules and class bodies are strict by default.
216. What is error handling in JavaScript?
Error handling is the process of detecting, managing and responding to errors that occur during program execution.
JavaScript uses try, catch and finally for handling exceptions.
try {
const result = JSON.parse("{invalid json}");
} catch (error) {
console.log("Invalid JSON");
} finally {
console.log("Finished");
}
trycontains code that may throw an error.catchhandles the error.finallyruns after the try and catch flow completes, whether an exception occurred or not.
217. What is the difference between a syntax error and a runtime error?
| Syntax error | Runtime error |
|---|---|
| Code violates language syntax rules | Error occurs while executing valid syntax |
| Often detected before execution | Occurs during execution |
| Prevents affected code from being parsed | May happen only under certain conditions |
Example syntax error:
// const = 10; // Invalid syntax
Example runtime error:
console.log(user.name); // ReferenceError if user is not declared
218. What is a TypeError?
A TypeError occurs when an operation is performed on a value that is not suitable for that operation.
const user = null;
user.name; // TypeError
Other examples include calling something that is not a function or attempting to use an operation that is incompatible with a value’s type.
219. What is a ReferenceError?
A ReferenceError occurs when code tries to access a variable that cannot be resolved or is not accessible in the current execution context.
console.log(unknownVariable); // ReferenceError
Accessing a lexical variable inside its Temporal Dead Zone also causes a ReferenceError.
220. What is a RangeError?
A RangeError occurs when a value is outside the valid range expected by an operation.
const number = 1;
number.toFixed(101); // RangeError
The precision argument for toFixed() has a permitted range. Exceeding that range causes an error.
221. How do you throw a custom error?
Use the throw statement.
function withdraw(balance, amount) {
if (amount > balance) {
throw new Error("Insufficient funds");
}
return balance - amount;
}
try {
withdraw(100, 150);
} catch (error) {
console.log(error.message);
}
You can also define custom error classes.
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
throw new ValidationError("Invalid input");
222. What is the difference between throw and return?
return exits a function and optionally sends a value back. throw raises an exception and transfers control to an appropriate error handler.
function checkAge(age) {
if (age < 18) {
throw new Error("Must be 18 or older");
}
return true;
}
A throw can interrupt normal flow and propagate through callers until it is caught.
223. What is debugging in JavaScript?
Debugging is the process of finding, understanding and fixing errors in code.
Common tools include:
- Browser DevTools
- Console output
- Breakpoints
- Step-through debugging
- Network inspection
- Performance profiling
- Node.js debugger
- Unit tests
For a browser application, DevTools can help inspect variables, DOM changes, network requests, event handlers and JavaScript execution.
224. What is a source map?
A source map connects generated code to the original source code.
When JavaScript is bundled or transpiled, the code may be transformed into a different file. Source maps allow debugging tools to show the original code locations and names where supported.
They are particularly useful with TypeScript, bundlers and minified production code.
225. What is transpilation?
Transpilation converts source code from one language form or syntax level to another while preserving its general purpose.
For example, TypeScript can be transpiled to JavaScript. Modern JavaScript can also be transformed into syntax compatible with older environments.
Transpilation is not the same as bundling, which combines or packages code and dependencies.
226. What is bundling?
Bundling combines application files and dependencies into one or more output files optimized for delivery or execution.
Tools such as Webpack, Vite and Rollup can help manage modules, assets, development servers and production builds.
Bundling can reduce the number of files or optimize how code is delivered, though modern bundlers often produce multiple chunks instead of one large file.
227. What is minification?
Minification reduces file size by removing unnecessary characters and sometimes shortening names without changing intended behavior.
Example:
function calculateTotal(price, tax) {
return price + tax;
}
A minifier may transform the code into something like:
function a(b,c){return b+c}
Minification reduces transfer size. It is not the same as encryption or security.
16. Performance, Memory and Optimization Interview Questions
228. What is garbage collection in JavaScript?
Garbage collection is the automatic memory management process that identifies objects no longer reachable by the program and reclaims their memory.
JavaScript developers generally do not manually free memory as they would in languages that require explicit memory management.
Modern JavaScript engines commonly use reachability-based garbage collection strategies. Objects that remain reachable through active references generally cannot be collected.
229. What is a memory leak in JavaScript?
A memory leak occurs when memory that is no longer useful remains retained and cannot be reclaimed because references still exist.
Common causes include:
- Unremoved event listeners
- Unintentionally retained global variables
- Closures retaining large objects
- Timers that continue running unnecessarily
- Detached DOM elements still referenced
- Cache structures that grow without limits
Memory leaks can cause applications to become slower, use more memory or crash.
230. How can you prevent memory leaks?
- Remove event listeners when they are no longer needed.
- Clear timers and intervals.
- Avoid unnecessary global variables.
- Release references to unused objects.
- Keep caches under control.
- Use lifecycle cleanup in UI frameworks.
- Profile memory and investigate retained objects.
231. What is debouncing?
Debouncing delays the execution of a function until a certain amount of time has passed since the last call.
If the function is repeatedly called, the timer resets. The function runs only when calls stop for the configured period.
A common example is a search input where you do not want to send a request for every keystroke.
function debounce(func, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
Usage:
const search = debounce(value => {
console.log("Searching:", value);
}, 300);
search("Java");
search("JavaScript");
Only the last call is executed after the delay, assuming no further calls occur.
232. What is throttling?
Throttling limits how often a function can execute within a period.
For example, if a scroll handler is throttled to 200 milliseconds, it will not execute more frequently than the throttling policy allows.
function throttle(func, delay) {
let lastCall = 0;
return function(...args) {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
func.apply(this, args);
}
};
}
This is a basic leading-edge throttle. Other versions may also support trailing execution.
233. What is the difference between debounce and throttle?
| Debounce | Throttle |
|---|---|
| Waits until calls stop for a period | Limits execution frequency |
| Executes after the final call | Executes at controlled intervals during repeated calls |
| Useful for search input | Useful for scroll and resize handlers |
234. What is memoization?
Memoization is an optimization technique that stores the results of previous function calls and reuses them when the same inputs occur again.
function memoize(func) {
const cache = new Map();
return function(value) {
if (cache.has(value)) {
return cache.get(value);
}
const result = func(value);
cache.set(value, result);
return result;
};
}
function square(number) {
return number * number;
}
const memoizedSquare = memoize(square);
console.log(memoizedSquare(5)); // 25
console.log(memoizedSquare(5)); // Uses cached result
Memoization is useful when computations are expensive and inputs repeat. It can also consume memory, so the cache should be managed appropriately.
235. What is lazy loading?
Lazy loading delays loading resources until they are needed.
For example, a webpage may load images only when they are near the visible area rather than loading every image immediately.
<img src="photo.jpg" loading="lazy" alt="Photo">
In JavaScript applications, lazy loading can also be used for modules, routes, components and data.
236. What is code splitting?
Code splitting divides an application into smaller bundles that can be loaded separately.
Instead of loading an entire application at once, the browser can download the code needed for the current page and load additional code when required.
This can improve initial loading performance.
237. What is tree shaking?
Tree shaking is a bundler optimization that removes unused code from the output bundle when it can determine that the code is not needed.
It works best with static ES module imports and exports.
For example, if a module exports three functions but the application imports only one, a compatible build tool may remove the unused functions from the final bundle.
238. What is the difference between synchronous blocking and asynchronous non-blocking operations?
A blocking operation prevents the current execution flow from progressing until it finishes. A non-blocking operation allows the current flow to continue while the operation is handled elsewhere.
For example, synchronous file reading in Node.js can block the event loop. Asynchronous file reading allows other work to proceed while the file operation completes.
This is particularly important in server-side JavaScript.
239. What is a Web Worker?
A Web Worker allows JavaScript to run in a separate worker thread in the browser.
It can perform computationally intensive tasks without blocking the main thread that handles the user interface.
Workers communicate with the main thread using messages. They do not directly manipulate the DOM.
240. What is the difference between a Web Worker and the main thread?
| Main thread | Web Worker |
|---|---|
| Handles DOM interaction | Runs separate JavaScript work |
| Manages typical UI updates | Cannot directly access the DOM |
| Can be blocked by heavy computation | Helps move computation away from the UI |
| Communicates with workers | Communicates using messages |
Web Workers are useful for CPU-intensive tasks such as data processing, calculations and certain parsing operations.
241. What is requestAnimationFrame()?
requestAnimationFrame() asks the browser to call a callback before the next repaint.
It is commonly used for smooth animations.
function animate() {
// Update animation state
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
Unlike a fixed timer, it is coordinated with the browser’s rendering process.
17. JavaScript Security Interview Questions
Security questions are especially important for frontend and full-stack developers. JavaScript runs in environments where it may handle user input, API responses and application data. A developer needs to understand how to avoid exposing users to common vulnerabilities.
242. What is Cross-Site Scripting (XSS)?
Cross-Site Scripting, or XSS, is a vulnerability in which an attacker is able to inject malicious scripts or content into a webpage viewed by other users.
For example, if an application directly inserts untrusted input into the page using innerHTML, the content may be interpreted as HTML rather than plain text.
Unsafe pattern:
element.innerHTML = userInput;
Safer for plain text:
element.textContent = userInput;
The best defense depends on the context. Use context-aware output encoding, sanitize HTML when rich HTML is required, avoid unsafe DOM APIs, and apply a Content Security Policy as an additional defense.
243. What is CSRF?
Cross-Site Request Forgery (CSRF) is an attack in which a user who is authenticated to a website is tricked into making an unwanted request to that website.
For example, an attacker may cause a user’s browser to submit a request to a site where the user is already logged in.
Common defenses include:
- CSRF tokens
- SameSite cookie settings
- Origin or Referer validation where appropriate
- Appropriate authentication and authorization checks
- Avoiding state-changing requests through GET
244. What is the difference between XSS and CSRF?
| XSS | CSRF |
|---|---|
| Injects or executes unwanted script in a trusted site context | Tricks an authenticated browser into making an unwanted request |
| Targets the user’s interaction with a vulnerable page | Exploits the browser’s automatic inclusion of credentials |
| Often caused by unsafe handling of content | Often caused by insufficient request protections |
245. What is a Content Security Policy (CSP)?
A Content Security Policy is a browser security mechanism that allows a website to define which sources are permitted for certain types of resources.
It can help reduce the impact of XSS by restricting script execution and other resource loading.
For example, a site can use CSP directives to restrict scripts to approved sources and avoid unsafe inline scripts.
CSP is usually configured through HTTP response headers.
246. Is storing authentication tokens in localStorage safe?
Not automatically. JavaScript running on the page can access localStorage. If an XSS vulnerability occurs, an attacker may be able to read stored tokens.
For authentication, developers should consider the threat model and often prefer secure cookies with attributes such as HttpOnly, Secure and appropriate SameSite settings.
The right solution depends on the architecture. No storage method eliminates all security risks.
247. What is input validation?
Input validation checks whether data meets expected requirements before it is accepted or processed.
function validateAge(age) {
return Number.isInteger(age) && age >= 18 && age <= 120;
}
console.log(validateAge(25)); // true
console.log(validateAge(-5)); // false
Validation can check type, range, format, length and allowed values.
Client-side validation improves user experience, but server-side validation is essential because client-side checks can be bypassed.
248. What is sanitization?
Sanitization modifies or removes unsafe parts of input to make it safe for a particular use.
For example, HTML sanitization can remove unsafe markup before content is displayed as HTML.
Validation and sanitization are different:
- Validation checks whether input meets requirements.
- Sanitization transforms input to reduce risk or make it suitable for a context.
They should not be treated as interchangeable.
18. Node.js Interview Questions
These questions are useful for candidates applying for JavaScript backend, full-stack or Node.js roles. Browser JavaScript and Node.js share the language but provide different runtime APIs.
249. What is Node.js?
Node.js is a JavaScript runtime that allows JavaScript to run outside the browser. It is commonly used for backend development, APIs, command-line tools, automation, real-time applications and server-side services.
Node.js uses the V8 JavaScript engine and provides additional APIs for working with files, networking, processes and other system resources.
250. What is the difference between JavaScript and Node.js?
| JavaScript | Node.js |
|---|---|
| Programming language | Runtime environment |
| Defines language syntax and behavior | Executes JavaScript outside the browser |
| Can run in browsers or compatible runtimes | Provides server and system APIs |
| Browser APIs vary by environment | Includes APIs such as filesystem and networking |
Node.js is not a different programming language. It is an environment for executing JavaScript.
251. What is the Node.js event loop?
The Node.js event loop coordinates asynchronous operations and callbacks so the runtime can handle work without blocking unnecessarily.
Node.js uses the event loop along with operating system facilities and its runtime libraries to handle I/O. Some operations may use a thread pool. The event loop processes callbacks according to its phases and scheduling rules.
This allows Node.js to handle many I/O-bound operations efficiently without requiring a separate JavaScript thread for every request.
252. Is Node.js single-threaded?
JavaScript execution on the main Node.js thread is generally single-threaded. However, Node.js itself uses additional threads and runtime mechanisms for some operations.
It supports worker threads for parallel JavaScript execution and can handle asynchronous I/O without blocking the main JavaScript thread.
So, saying “Node.js is single-threaded” is a useful simplification for understanding the main execution model, but it is not the complete description of its runtime architecture.
253. What is npm?
npm is the Node.js package ecosystem and commonly used package manager. It helps developers install, manage and share JavaScript packages.
npm install express
This command installs the Express package into a project.
npm also provides package scripts for running development, testing, building and other tasks.
254. What is package.json?
package.json is a project manifest file that stores information about a JavaScript project.
It commonly contains:
- Project name and version
- Dependencies
- Development dependencies
- Scripts
- Package metadata
- Module configuration
Example:
{
"name": "my-app",
"version": "1.0.0",
"scripts": {
"start": "node index.js"
}
}
255. What is the difference between dependencies and devDependencies?
| dependencies | devDependencies |
|---|---|
| Packages required by the application at runtime | Packages primarily needed during development or build |
Installed with npm install package | Installed with npm install -D package |
| Includes runtime libraries | Includes test tools, linting and build tools |
The distinction depends on the project and deployment setup. Some build-time packages may be needed in production build environments even if they are not runtime dependencies.
256. What is Express.js?
Express is a web framework for Node.js. It provides features for defining routes, handling requests, managing middleware and building web applications or APIs.
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("Hello World");
});
app.listen(3000);
Express is widely used to build REST APIs and backend services.
257. What is middleware in Node.js and Express?
Middleware is a function that runs during the request-response processing flow.
In Express, middleware can access the request, response and next function.
app.use((req, res, next) => {
console.log(req.method, req.url);
next();
});
Middleware is commonly used for:
- Logging
- Authentication
- Authorization
- Parsing request bodies
- Error handling
- Request validation
258. What is the difference between frontend and backend JavaScript?
| Frontend JavaScript | Backend JavaScript |
|---|---|
| Runs in the browser | Runs in a server runtime such as Node.js |
| Interacts with DOM and browser APIs | Interacts with server APIs and system resources |
| Handles UI behavior | Handles business logic, requests and data processing |
| Uses browser security restrictions | Has server-side privileges based on permissions |
JavaScript can be used across both sides of an application, enabling developers to share language knowledge and sometimes code between frontend and backend.
19. JavaScript Coding Interview Questions and Solutions
In a coding interview, explaining a concept is only part of the job. You may be asked to write a function, solve a problem without using a built-in method or explain the time and space complexity of your solution.
These are common JavaScript coding exercises, starting with basic problems and progressing to practical utilities.
259. How do you reverse a string in JavaScript?
Problem: Write a function that reverses a string.
function reverseString(str) {
return str.split("").reverse().join("");
}
console.log(reverseString("hello")); // olleh
How it works:
split("")converts the string into an array of characters.reverse()reverses the array.join("")combines the characters into a string.
Time complexity: O(n). This simple approach does not correctly handle every Unicode grapheme, such as emoji sequences.
260. How do you check whether a string is a palindrome?
A palindrome reads the same forward and backward.
function isPalindrome(str) {
const cleaned = str.toLowerCase().replace(/[^a-z0-9]/g, "");
return cleaned === cleaned.split("").reverse().join("");
}
console.log(isPalindrome("Racecar")); // true
console.log(isPalindrome("JavaScript")); // false
This solution ignores capitalization and non-alphanumeric characters.
261. How do you find the largest number in an array?
function findLargest(numbers) {
return Math.max(...numbers);
}
console.log(findLargest([10, 5, 20, 8])); // 20
For a more interview-friendly implementation without Math.max():
function findLargest(numbers) {
if (numbers.length === 0) return undefined;
let largest = numbers[0];
for (const number of numbers) {
if (number > largest) {
largest = number;
}
}
return largest;
}
Time complexity: O(n).
262. How do you find the smallest number in an array?
function findSmallest(numbers) {
if (numbers.length === 0) return undefined;
let smallest = numbers[0];
for (const number of numbers) {
if (number < smallest) {
smallest = number;
}
}
return smallest;
}
console.log(findSmallest([10, 5, 20, 8])); // 5
263. How do you find the second-largest number in an array?
function secondLargest(numbers) {
const unique = [...new Set(numbers)];
unique.sort((a, b) => b - a);
return unique.length < 2 ? undefined : unique[1];
}
console.log(secondLargest([10, 20, 20, 5, 8])); // 10
This solution removes duplicates and sorts the values. In a coding interview, you may be asked to solve it in O(n) time without sorting.
264. How do you remove duplicate values from an array?
function removeDuplicates(arr) {
return [...new Set(arr)];
}
console.log(removeDuplicates([1, 2, 2, 3, 4, 4]));
// [1, 2, 3, 4]
This preserves the first occurrence order.
265. How do you find duplicate values in an array?
function findDuplicates(arr) {
const seen = new Set();
const duplicates = new Set();
for (const value of arr) {
if (seen.has(value)) {
duplicates.add(value);
} else {
seen.add(value);
}
}
return [...duplicates];
}
console.log(findDuplicates([1, 2, 3, 2, 4, 1]));
// [2, 1]
The output contains each duplicated value once.
266. How do you count the frequency of elements in an array?
function countFrequency(arr) {
const frequency = new Map();
for (const value of arr) {
frequency.set(value, (frequency.get(value) || 0) + 1);
}
return frequency;
}
const result = countFrequency(["apple", "banana", "apple", "orange", "banana", "apple"]);
console.log(result);
The resulting Map stores each unique value and its number of occurrences.
267. How do you count the frequency of characters in a string?
function characterFrequency(str) {
const frequency = {};
for (const char of str) {
frequency[char] = (frequency[char] || 0) + 1;
}
return frequency;
}
console.log(characterFrequency("hello"));
Expected result:
{
h: 1,
e: 1,
l: 2,
o: 1
}
For general-purpose code, a Map is often a better choice for arbitrary keys.
268. How do you check whether two strings are anagrams?
Anagrams contain the same characters in a different order.
function areAnagrams(str1, str2) {
const normalize = str =>
str.toLowerCase().replace(/[^a-z0-9]/g, "").split("").sort().join("");
return normalize(str1) === normalize(str2);
}
console.log(areAnagrams("listen", "silent")); // true
console.log(areAnagrams("hello", "world")); // false
This version ignores capitalization and non-alphanumeric characters.
269. How do you flatten a nested array?
function flattenArray(arr) {
return arr.flat(Infinity);
}
console.log(flattenArray([1, [2, [3, 4]], 5]));
// [1, 2, 3, 4, 5]
An interview may require a recursive solution without using flat().
function flattenArray(arr) {
const result = [];
for (const item of arr) {
if (Array.isArray(item)) {
result.push(...flattenArray(item));
} else {
result.push(item);
}
}
return result;
}
270. How do you find the missing number in an array?
Problem: An array contains numbers from 1 to n, but one number is missing. Find it.
function findMissing(numbers, n) {
const expected = n * (n + 1) / 2;
const actual = numbers.reduce((sum, number) => sum + number, 0);
return expected - actual;
}
console.log(findMissing([1, 2, 4, 5], 5)); // 3
This uses the mathematical sum formula for the integers from 1 to n.Time complexity: O(n). Space complexity: O(1), excluding the input.
271. How do you find two numbers that add up to a target?
This is the classic Two Sum problem.
function twoSum(numbers, target) {
const seen = new Map();
for (let i = 0; i < numbers.length; i++) {
const complement = target - numbers[i];
if (seen.has(complement)) {
return [seen.get(complement), i];
}
seen.set(numbers[i], i);
}
return [];
}
console.log(twoSum([2, 7, 11, 15], 9)); // [0, 1]
The Map stores previously seen numbers and their indices. For each number, the function checks whether its complement has already appeared.Time complexity: O(n) average.
272. How do you check whether a number is prime?
function isPrime(number) {
if (number < 2) return false;
for (let i = 2; i <= Math.sqrt(number); i++) {
if (number % i === 0) {
return false;
}
}
return true;
}
console.log(isPrime(7)); // true
console.log(isPrime(10)); // false
Checking divisors up to the square root is enough because factors occur in pairs.
273. How do you calculate factorial?
Factorial is the product of every positive integer from 1 through a number.
function factorial(number) {
if (number < 0) return undefined;
let result = 1;
for (let i = 2; i <= number; i++) {
result *= i;
}
return result;
}
console.log(factorial(5)); // 120
The recursive solution:
function factorial(number) {
if (number <= 1) return 1;
return number * factorial(number - 1);
}
The iterative solution avoids creating a recursive call stack.
274. How do you generate the Fibonacci sequence?
The Fibonacci sequence begins with 0 and 1. Each subsequent number is the sum of the previous two.
function fibonacci(count) {
const result = [];
let a = 0;
let b = 1;
for (let i = 0; i < count; i++) {
result.push(a);
[a, b] = [b, a + b];
}
return result;
}
console.log(fibonacci(7)); // [0, 1, 1, 2, 3, 5, 8]
275. How do you capitalize the first letter of each word?
function capitalizeWords(str) {
return str
.split(" ")
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(" ");
}
console.log(capitalizeWords("hello world")); // Hello World
This simple implementation assumes space-separated words and does not handle every language-specific capitalization rule.
276. How do you find the longest word in a sentence?
function longestWord(sentence) {
const words = sentence.split(/\s+/);
return words.reduce((longest, word) => {
return word.length > longest.length ? word : longest;
}, "");
}
console.log(longestWord("JavaScript is a programming language"));
// programming
277. How do you check whether an array is sorted?
function isSorted(arr) {
for (let i = 1; i < arr.length; i++) {
if (arr[i] < arr[i - 1]) {
return false;
}
}
return true;
}
console.log(isSorted([1, 2, 3, 4])); // true
console.log(isSorted([1, 3, 2, 4])); // false
This checks whether the array is sorted in ascending order.
278. How do you merge two sorted arrays?
function mergeSortedArrays(a, b) {
const result = [];
let i = 0;
let j = 0;
while (i < a.length && j < b.length) {
if (a[i] <= b[j]) {
result.push(a[i++]);
} else {
result.push(b[j++]);
}
}
return result.concat(a.slice(i), b.slice(j));
}
console.log(mergeSortedArrays([1, 3, 5], [2, 4, 6]));
// [1, 2, 3, 4, 5, 6]
This uses two pointers and takes O(n + m) time.
279. How do you find the intersection of two arrays?
The intersection contains values present in both arrays.
function intersection(a, b) {
const setB = new Set(b);
return [...new Set(a.filter(value => setB.has(value)))];
}
console.log(intersection([1, 2, 3, 4], [3, 4, 5, 6]));
// [3, 4]
This version returns unique common values.
280. How do you group objects by a property?
function groupBy(arr, key) {
return arr.reduce((groups, item) => {
const value = item[key];
if (!groups[value]) {
groups[value] = [];
}
groups[value].push(item);
return groups;
}, {});
}
const employees = [
{ name: "Alex", department: "IT" },
{ name: "Sam", department: "HR" },
{ name: "Jordan", department: "IT" }
];
console.log(groupBy(employees, "department"));
This groups the employees by their department.
281. How do you find the most frequent element in an array?
function mostFrequent(arr) {
const frequency = new Map();
let mostCommon;
let maxCount = 0;
for (const value of arr) {
const count = (frequency.get(value) || 0) + 1;
frequency.set(value, count);
if (count > maxCount) {
maxCount = count;
mostCommon = value;
}
}
return mostCommon;
}
console.log(mostFrequent([1, 2, 2, 3, 3, 3, 4])); // 3
282. How do you implement a debounce function?
function debounce(func, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
This implementation delays execution until the function has not been called again within the specified delay.
283. How do you implement a throttle function?
function throttle(func, delay) {
let lastTime = 0;
return function(...args) {
const now = Date.now();
if (now - lastTime >= delay) {
lastTime = now;
return func.apply(this, args);
}
};
}
This implementation allows the function to run at most once per interval, using a leading-edge approach.
284. How do you implement a custom map() function?
function customMap(arr, callback) {
const result = [];
for (let i = 0; i < arr.length; i++) {
result.push(callback(arr[i], i, arr));
}
return result;
}
console.log(customMap([1, 2, 3], number => number * 2));
// [2, 4, 6]
This is a simplified implementation for ordinary dense arrays. A production-quality version would need to account for sparse arrays, the optional thisArg, callback validation and other specification details.
285. How do you implement a custom filter() function?
function customFilter(arr, callback) {
const result = [];
for (let i = 0; i < arr.length; i++) {
if (callback(arr[i], i, arr)) {
result.push(arr[i]);
}
}
return result;
}
console.log(customFilter([1, 2, 3, 4], number => number > 2));
// [3, 4]
This is a simplified implementation. Native filter() also has defined behavior for sparse arrays and optional callback arguments.
286. How do you implement a custom reduce() function?
function customReduce(arr, callback, initialValue) {
let accumulator = initialValue;
for (let i = 0; i < arr.length; i++) {
accumulator = callback(accumulator, arr[i], i, arr);
}
return accumulator;
}
console.log(customReduce([1, 2, 3, 4], (sum, value) => sum + value, 0));
// 10
This simplified version assumes an initial value is provided and the input is a dense array. Native reduce() handles omitted initial values and sparse arrays according to its specification.
287. How do you implement a counter using closures?
function createCounter() {
let count = 0;
return {
increment() {
return ++count;
},
decrement() {
return --count;
},
getValue() {
return count;
},
reset() {
count = 0;
}
};
}
const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(counter.decrement()); // 1
counter.reset();
console.log(counter.getValue()); // 0
This question tests closures, state management and encapsulation.
288. How do you implement a memoized function?
function memoize(func) {
const cache = new Map();
return function(...args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
const result = func.apply(this, args);
cache.set(key, result);
return result;
};
}
const square = memoize(number => number * number);
console.log(square(5)); // 25
console.log(square(5)); // Cached 25
This example uses JSON serialization for keys, which is suitable only for certain simple argument types. It is not a universal cache-key strategy for objects, circular references or values that serialize ambiguously.
289. How do you implement a promise-based delay function?
function delay(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
async function run() {
console.log("Start");
await delay(1000);
console.log("One second later");
}
run();
This is useful for creating delays in asynchronous workflows.
290. How do you implement a retry function for a failed asynchronous operation?
async function retry(fn, attempts = 3) {
let lastError;
for (let i = 0; i < attempts; i++) {
try {
return await fn();
} catch (error) {
lastError = error;
}
}
throw lastError;
}
This function attempts the operation multiple times before throwing the last error.
A production version may also need a delay between attempts, exponential backoff, cancellation, error classification and safeguards against retrying non-recoverable failures.
291. How do you implement Promise.all() conceptually?
Promise.all() takes an iterable of promises or values and returns a promise that fulfills with an array of results in input order once all inputs fulfill. If one rejects, the returned promise rejects.
A simplified implementation:
function customPromiseAll(promises) {
return new Promise((resolve, reject) => {
const results = [];
let completed = 0;
if (promises.length === 0) {
resolve([]);
return;
}
promises.forEach((promise, index) => {
Promise.resolve(promise)
.then(value => {
results[index] = value;
completed++;
if (completed === promises.length) {
resolve(results);
}
})
.catch(reject);
});
});
}
customPromiseAll([
Promise.resolve(1),
Promise.resolve(2),
Promise.resolve(3)
]).then(console.log); // [1, 2, 3]
This illustrates the basic logic. A fully compliant implementation needs to accept general iterables, handle iteration errors and follow the specification’s details.
292. How do you implement a deep clone?
For supported data types, the simplest modern approach is:
const original = {
name: "Alex",
details: {
age: 25
},
hobbies: ["coding", "reading"]
};
const copy = structuredClone(original);
A common interview follow-up is to implement cloning recursively.
A simplified recursive version:
function deepClone(value) {
if (value === null || typeof value !== "object") {
return value;
}
if (Array.isArray(value)) {
return value.map(deepClone);
}
const result = {};
for (const key of Object.keys(value)) {
result[key] = deepClone(value[key]);
}
return result;
}
This implementation is not production-complete. It does not preserve Date objects, Maps, Sets, prototypes, property descriptors, symbols or circular references.
293. How do you implement a custom bind() function?
Function.prototype.myBind = function(context, ...args) {
const fn = this;
return function(...moreArgs) {
return fn.apply(context, [...args, ...moreArgs]);
};
};
Usage:
function greet(city) {
console.log(`${this.name} lives in ${city}`);
}
const user = { name: "Alex" };
const boundGreet = greet.myBind(user, "Austin");
boundGreet(); // Alex lives in Austin
This is a simplified bind() implementation. A complete polyfill must account for constructor use, function properties and other specification details.
20. JavaScript Output-Based Interview Questions
Output-based questions are designed to test whether you understand how JavaScript actually behaves. Interviewers often combine scope, coercion, closures, promises and execution order into a few lines of code.
Try to predict the output before reading the answer.
294. What will this code print?
console.log(typeof null);
console.log(typeof []);
console.log(typeof NaN);
Answer:
object
object
number
These are longstanding JavaScript behaviors. typeof is not a universal type-identification tool.
295. What will this code print?
console.log(1 + "2" + 3);
console.log(1 + 2 + "3");
console.log("1" + 2 + 3);
Answer:
123
33
123
When string concatenation occurs, the result becomes a string. Evaluation proceeds from left to right, so the position of the string changes the result.
296. What will this code print?
console.log([] == false);
console.log([] === false);
console.log("" == false);
Answer:
true
false
true
The loose equality operator performs type conversion. Strict equality does not.
297. What will this code print?
let a = 10;
function test() {
let a = 20;
console.log(a);
}
test();
console.log(a);
Answer:
20
10
The function has its own local variable that shadows the outer variable.
298. What will this code print?
var x = 1;
function test() {
console.log(x);
var x = 2;
}
test();
Answer:
undefined
The local var x declaration is hoisted within the function, so the local variable is used rather than the global variable. It has not been assigned 2 at the time of the log.
299. What will this code print?
for (var i = 0; i < 3; i++) {
console.log(i);
}
console.log(i);
Answer:
0
1
2
3
var is not block-scoped, so i remains accessible after the loop.
300. What will this code print?
for (let i = 0; i < 3; i++) {
console.log(i);
}
console.log(i);
Answer:
0
1
2
ReferenceError
The last statement attempts to access i outside the loop’s scope.
301. What will this code print?
const user = { name: "Alex" };
const anotherUser = user;
anotherUser.name = "Sam";
console.log(user.name);
Answer:
Sam
Both variables refer to the same object. The object is mutable even though the original variable was declared using const.
302. What will this code print?
console.log("Start");
setTimeout(() => console.log("Timer"), 0);
Promise.resolve().then(() => console.log("Promise"));
console.log("End");
Answer:
Start
End
Promise
Timer
Synchronous code runs first, promise callbacks run at a microtask checkpoint and the timer callback runs later as a task.
303. What will this code print?
async function test() {
console.log("A");
await Promise.resolve();
console.log("B");
}
console.log("C");
test();
console.log("D");
Answer:
C
A
D
B
The code before await runs immediately. The async function then suspends and resumes after the awaited promise settles.
304. What will this code print?
const numbers = [1, 2, 3];
const result = numbers.forEach(number => number * 2);
console.log(result);
Answer:
undefined
forEach() does not return a new array. Use map() if you want an array of transformed values.
305. What will this code print?
console.log([1, 2, 3] == "1,2,3");
console.log([1, 2, 3] === "1,2,3");
Answer:
true
false
Loose equality converts the array to a primitive string for comparison. Strict equality compares different types and returns false.
306. What will this code print?
const a = {};
const b = {};
console.log(a == b);
console.log(a === b);
Answer:
false
false
Objects are compared by identity, not by their contents. These are two separate object instances.
307. What will this code print?
console.log(0 || 10);
console.log(0 ?? 10);
console.log("" || "Default");
console.log("" ?? "Default");
Answer:
10
0
Default
The last result is an empty string. || uses truthiness. ?? only checks for null and undefined.
308. What will this code print?
const user = {
name: "Alex",
greet() {
return this.name;
}
};
const greet = user.greet;
console.log(user.greet());
console.log(greet());
Answer:
Alex
undefined
In non-strict script mode, the second call may instead use the global this value and return the global object’s nameproperty if present. In strict mode, it returns undefined from the function if it simply reads this.name without throwing, or throws if the function accesses a property when this is undefined. For this exact code, accessing this.name in strict mode throws a TypeError.
The important concept is that extracting a method changes how it is called and may change its this value.
309. What will this code print?
const arr = [1, 2, 3];
const result = arr.push(4);
console.log(result);
console.log(arr);
Answer:
4
[1, 2, 3, 4]
push() returns the new length of the array and modifies the original array.
310. What will this code print?
const numbers = [1, 2, 3];
const result = numbers.map(number => {
if (number > 1) return number * 2;
});
console.log(result);
Answer:
[undefined, 4, 6]
The callback for the first element does not return a value, so its result is undefined. map() retains the position of each element in its resulting array.
311. What will this code print?
console.log("5" - 2);
console.log("5" + 2);
console.log("5" * 2);
console.log("5" / 2);
Answer:
3
52
10
2.5
The arithmetic operators other than + generally convert numeric strings to numbers. + can concatenate strings.
312. What will this code print?
const promise = new Promise(resolve => {
console.log("One");
resolve();
});
promise.then(() => console.log("Two"));
console.log("Three");
Answer:
One
Three
Two
The Promise executor runs immediately. The then() callback is scheduled as a microtask.
21. Practical JavaScript Interview Questions
These questions move beyond definitions. They test how you choose an approach, understand trade-offs and write maintainable code.
313. How would you validate a form using JavaScript?
You would collect input values, check them against the required conditions and provide clear feedback to the user.
function validateForm(name, email) {
const errors = [];
if (!name.trim()) {
errors.push("Name is required");
}
if (!email.includes("@")) {
errors.push("Enter a valid email");
}
return {
isValid: errors.length === 0,
errors
};
}
For real applications, email validation needs more than checking whether the string contains an @. Client-side validation should be paired with server-side validation.
314. How would you fetch data from an API?
Use fetch() with asynchronous handling and error checks.
async function getUsers() {
try {
const response = await fetch("https://api.example.com/users");
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
const users = await response.json();
return users;
} catch (error) {
console.error("Unable to fetch users:", error);
throw error;
}
}
This handles HTTP errors and other failures. It also allows the caller to handle errors instead of silently hiding them.
315. How would you prevent duplicate API calls from a search box?
Use debouncing to wait until the user stops typing before making the request.
function debounce(func, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => func(...args), delay);
};
}
const searchInput = document.querySelector("#search");
const search = debounce(async query => {
if (!query.trim()) return;
const response = await fetch(
`/api/search?q=${encodeURIComponent(query)}`
);
if (!response.ok) {
throw new Error("Search failed");
}
const data = await response.json();
console.log(data);
}, 300);
searchInput.addEventListener("input", event => {
search(event.target.value);
});
Debouncing reduces the number of requests. It does not guarantee that an earlier request will finish before a later one. For search interfaces, you may also need cancellation or a way to ignore stale responses.
316. How would you handle API errors in a frontend application?
I would separate network errors, HTTP errors, parsing errors and application-level errors where relevant.
For example:
async function fetchData(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return await response.json();
} catch (error) {
console.error("Data request failed", error);
throw error;
}
}
In a UI, I would also make sure the user sees an appropriate loading, success or error state rather than relying only on the console.
317. How would you improve the performance of a slow JavaScript application?
I would first measure the problem rather than make assumptions.
Possible areas to investigate include:
- Expensive calculations
- Excessive DOM updates
- Large bundles
- Unnecessary rendering
- Too many event listeners
- Repeated API requests
- Memory leaks
- Unoptimized images and assets
- Long-running main-thread tasks
The appropriate solution depends on the actual bottleneck. Tools such as browser Performance and Memory panels can help identify what is causing the slowdown.
318. How would you handle large arrays efficiently?
I would consider:
- Choosing the right data structure
- Avoiding unnecessary copies
- Reducing repeated searches
- Using a
MaporSetfor efficient lookups - Avoiding expensive operations inside loops
- Processing data in batches if necessary
- Using workers for heavy computations that would block the main thread
For example, repeated membership checks using includes() on a large array can be replaced with a Set when that makes sense.
const allowedIds = new Set([10, 20, 30, 40]);
if (allowedIds.has(30)) {
console.log("Allowed");
}
319. How would you make JavaScript code easier to maintain?
I would:
- Use meaningful variable and function names.
- Keep functions focused on one responsibility.
- Avoid unnecessary global variables.
- Separate application logic from UI logic where appropriate.
- Use modules.
- Handle errors intentionally.
- Avoid excessive nesting.
- Write tests for important behavior.
- Use formatting and linting tools consistently.
Readable code is easier to debug and safer to modify.
320. How would you handle an event listener that is no longer needed?
Remove the listener when the element or feature no longer needs it.
function handleClick() {
console.log("Clicked");
}
button.addEventListener("click", handleClick);
// Later
button.removeEventListener("click", handleClick);
The same function reference and matching event listener options must be used when removing a listener.
Anonymous functions can make removal harder if you do not retain their references.
321. How would you safely display user-provided text in a webpage?
Use text-oriented DOM APIs such as textContent rather than inserting untrusted input as HTML.
const message = document.querySelector("#message");
message.textContent = userInput;
If the application needs to render rich HTML, use a reliable sanitization approach and understand the security implications of the HTML being inserted.
322. How would you handle a user changing pages while an API request is still running?
Depending on the application, I would cancel the request with AbortController or ignore its result if the request is no longer relevant.
const controller = new AbortController();
fetch("/api/data", {
signal: controller.signal
});
// When the request is no longer needed:
controller.abort();
In frontend frameworks, cleanup is often performed when a component unmounts or a dependency changes.
323. How would you avoid race conditions in a search interface?
A race condition can occur when several requests are made and an older response arrives after a newer one.
For example, the user searches for “Java” and then “JavaScript”. If the first response arrives last, it could overwrite the newer results.
Possible solutions include:
- Aborting the previous request
- Assigning each request a sequence number
- Only accepting the latest response
- Using a query-management library that handles request lifecycle
22. JavaScript Testing Interview Questions
Testing is an important part of professional JavaScript development. Interviews may ask about unit tests, mocking, test coverage and the tools used to test applications.
324. What is unit testing?
Unit testing verifies a small and isolated part of a program, such as a function or module, to check whether it behaves as expected.
For example, a unit test for a function that adds two numbers would check whether it returns the correct result for several inputs.
325. What is integration testing?
Integration testing verifies whether different parts of an application work together correctly.
For example, it might test whether a frontend service correctly communicates with an API layer or whether multiple backend modules interact as expected.
326. What is end-to-end testing?
End-to-end testing checks an application’s behavior through a complete workflow from the user’s perspective.
For example, a test might verify that a user can open a page, enter data into a form, submit it and see the expected result.
327. What is the difference between unit, integration and end-to-end testing?
| Unit testing | Integration testing | End-to-end testing |
|---|---|---|
| Tests a small isolated component | Tests interactions between components | Tests a complete workflow |
| Usually fast | Broader coverage of interactions | Often slower |
| Finds logic errors | Finds integration problems | Finds user-flow problems |
328. What are Jest and Vitest?
Jest and Vitest are JavaScript testing frameworks.
They provide tools for:
- Writing test cases
- Assertions
- Mocking
- Test isolation
- Running tests
- Measuring coverage
Vitest is designed to integrate closely with Vite. Jest is widely used across JavaScript projects.
329. What is mocking in JavaScript testing?
Mocking replaces a real dependency with a controlled test version.
For example, you might mock an API request so a test does not depend on a real server or network connection.
Mocking helps test success cases, error cases and edge conditions in a predictable environment.
330. What is test coverage?
Test coverage measures how much of a codebase is exercised by tests.
Common measurements include:
- Statement coverage
- Branch coverage
- Function coverage
- Line coverage
High coverage does not automatically mean high-quality testing. Tests also need to check meaningful behavior and edge cases.
331. What is the difference between a mock, stub and spy?
These terms are related and their definitions can vary slightly by testing framework.
| Mock | Stub | Spy |
|---|---|---|
| Simulates a dependency and can verify interactions | Provides predefined behavior or responses | Observes calls to a function |
| Often used to test interactions | Often used to control test inputs | Often used to check how a function was called |
23. JavaScript Interview Questions by Experience Level
Interviewers don’t necessarily ask completely different topics at each level. They often ask the same topic with a different depth of expectation.
JavaScript interview questions for freshers
Freshers are generally expected to demonstrate that they understand the basics and can write simple, correct code.
| Question | Expected knowledge |
|---|---|
| What is JavaScript? | Purpose and basic uses |
| What are data types? | Primitive and object types |
var vs let vs const | Scope and assignment |
== vs === | Type coercion |
| What is hoisting? | Declaration behavior |
| What is a function? | Parameters and return values |
| What is an array? | Indexing and common methods |
| What is an object? | Properties and methods |
| What is a callback? | Passing functions |
| What is a promise? | Basic async behavior |
| What is the DOM? | Webpage interaction |
| What is event bubbling? | Event propagation |
| What is JSON? | Data exchange |
| How do you reverse a string? | Basic coding |
| How do you find duplicates? | Arrays and loops |
JavaScript interview questions for junior developers
Junior developers should know the fundamentals and demonstrate the ability to use JavaScript in practical application development.
| Question | Expected knowledge |
|---|---|
| What is a closure? | Scope and retained state |
| What is the event loop? | Basic asynchronous execution |
How does async/await work? | Promise-based flow |
How does fetch() work? | API requests |
| What is event delegation? | Efficient event handling |
| What is destructuring? | Modern syntax |
| What is the spread operator? | Copying and combining |
How do map(), filter() and reduce() differ? | Array transformation |
| What is shallow copying? | Reference behavior |
| How do you handle errors? | try and catch |
| How do you validate form inputs? | DOM and validation |
| How do you use localStorage? | Browser storage |
JavaScript interview questions for mid-level developers
Mid-level candidates are often expected to understand how JavaScript behaves and how to use it in maintainable applications.
| Question | Expected knowledge |
|---|---|
| How do closures work in practical code? | State, encapsulation, memory |
| How does the event loop work? | Tasks, microtasks, scheduling |
What is the difference between Promise.all() and allSettled()? | Async composition |
| How does prototypal inheritance work? | Property lookup and reuse |
| What is event delegation? | DOM architecture |
| How do you prevent race conditions? | Request lifecycle |
| What is debouncing and throttling? | Performance |
| What causes memory leaks? | Retained references |
| How would you optimize a large dataset? | Algorithms and data structures |
| What is module bundling? | Build process |
| What is tree shaking? | Dead code removal |
| How do you test asynchronous code? | Testing and mocks |
JavaScript interview questions for senior developers
Senior candidates may be expected to explain trade-offs, runtime behavior, architectural decisions and performance or security implications.
| Question | Expected knowledge |
|---|---|
| How does the JavaScript execution model work? | Runtime and scheduling |
| Explain closure memory retention | Lifetime and reachability |
| How do you diagnose a memory leak? | Profiling and retained objects |
| How would you design an async workflow? | Cancellation, retries and errors |
| How do you handle concurrency limits? | Resource control |
| How would you design a reusable event system? | API design |
| How do you optimize rendering performance? | Profiling and bottlenecks |
| How would you design module boundaries? | Maintainability |
| What are the trade-offs between composition and inheritance? | Architecture |
| How do you protect an application against XSS? | Security |
| How do you manage API failures? | Resilience |
| How do you choose data structures for large workloads? | Complexity and performance |
| How would you reduce bundle size? | Splitting and optimization |
| How do you make an application maintainable as it grows? | Engineering practices |
24. JavaScript Interview Questions for Specific Developer Roles
A JavaScript interview may vary depending on the position. A frontend role, React role and Node.js role share language fundamentals but have different additional expectations.
Frontend developer interview questions
- What is the DOM?
- What is event bubbling?
- What is event delegation?
- How do you manipulate DOM elements?
- What is
DOMContentLoaded? - What is the difference between
asyncanddefer? - What is localStorage?
- What is sessionStorage?
- What is CORS?
- How does Fetch work?
- What is debouncing?
- What is throttling?
- How do you improve website performance?
- What is lazy loading?
- What are Web Workers?
- What is responsive web development?
- How does JavaScript interact with CSS?
- How do you validate a form?
React developer interview questions
React interviews usually require JavaScript knowledge along with React-specific concepts.
Common questions include:
- What is React?
- What are components?
- What is JSX?
- What are props?
- What is state?
- What is the difference between props and state?
- What are React hooks?
- What is
useState()? - What is
useEffect()? - What is
useMemo()? - What is
useCallback()? - What is the virtual DOM?
- What is reconciliation?
- What are keys in React?
- What is controlled vs uncontrolled components?
- How does event handling work in React?
- What is lifting state up?
- What is Context?
- How do you prevent unnecessary renders?
React is a separate framework/library topic. This JavaScript guide provides the language foundation, while dedicated React interview questions should cover React’s own APIs and rendering model in depth.
Node.js developer interview questions
- What is Node.js?
- How does the Node.js event loop work?
- What is npm?
- What is package.json?
- What are CommonJS modules?
- What are ES modules?
- What is Express?
- What is middleware?
- How does Node.js handle asynchronous I/O?
- What are streams?
- What is the difference between synchronous and asynchronous file operations?
- What are worker threads?
- What is the difference between
process.nextTick()andsetImmediate()? - What is event-driven architecture?
- How do you handle errors in Express?
- How do you handle authentication and authorization?
- How do you secure a Node.js application?
- How do you manage environment variables?
Full-stack developer interview questions
Full-stack interviews may combine JavaScript language questions with browser, backend and API knowledge.
Typical topics include:
- JavaScript fundamentals
- DOM and browser behavior
- React or another frontend framework
- Node.js
- REST APIs
- HTTP methods and status codes
- JSON
- Authentication
- Database interaction
- Async programming
- Error handling
- Security
- Performance
- Testing
- Git and build tools
25. Common Mistakes Candidates Make in JavaScript Interviews
Knowing JavaScript definitions is not enough. Many candidates lose points because they misunderstand how a concept behaves when used in code.
Mistake 1: Saying const makes an object immutable
Incorrect:
An object declared with const cannot be changed.
Correct:
constprevents reassignment of the variable binding. Object properties can still be modified unless additional restrictions are applied.
const user = { name: "Alex" };
user.name = "Sam"; // Allowed
Mistake 2: Saying JavaScript is entirely synchronous
Incorrect:
JavaScript executes everything one line at a time and cannot handle asynchronous operations.
Correct:
JavaScript executes synchronous code on its current thread, but the runtime coordinates asynchronous operations through APIs and scheduling mechanisms.
Mistake 3: Confusing map() and forEach()
Incorrect:
Both methods return a new array.
Correct:
map()returns a new array of transformed results.forEach()returnsundefined.
Mistake 4: Saying arrow functions are always better
Arrow functions are convenient for callbacks and lexical this. Regular functions remain useful for methods where dynamic this is required, constructors and functions that need their own arguments.
Mistake 5: Saying setTimeout(fn, 0) executes immediately
It schedules a callback to run later. It cannot interrupt the currently executing synchronous code and is not guaranteed to run immediately after the delay.
Mistake 6: Saying promises execute asynchronously
The executor function of new Promise() executes immediately. Promise handlers such as .then() execute later as microtasks.
new Promise(resolve => {
console.log("Executor");
resolve();
}).then(() => {
console.log("Then");
});
console.log("End");
Output:
Executor
End
Then
Mistake 7: Thinking objects are copied when assigned
const a = { value: 1 };
const b = a;
This does not create a new object. Both variables refer to the same object.
Mistake 8: Using sort() without a numeric comparator
[1, 20, 3].sort();
This performs string-based sorting by default.
Use:
[1, 20, 3].sort((a, b) => a - b);
Mistake 9: Thinking fetch() throws on HTTP errors
A 404 or 500 response does not normally reject a fetch promise. Check response.ok or response.status.
Mistake 10: Explaining what instead of why
If the interviewer asks what the code prints, give the output first, then explain the behavior.
A stronger answer is:
It prints 10 because
varis function-scoped. The declaration is available throughout the function but the assignment occurs later.
That demonstrates an understanding of the language rather than memorization.
26. How to Prepare for a JavaScript Interview
If you have limited time, do not try to memorize hundreds of answers in one sitting. Prioritize the topics that are repeatedly used to test language understanding and practical coding ability.
The 7-day JavaScript interview preparation plan
Day 1 — JavaScript fundamentals
Data types, variables, operators, type coercion, var, let, const, scope, hoisting and TDZ.
Day 2 — Functions and closures
Function declarations, arrow functions, callbacks, higher-order functions, closures, recursion, this, call, apply and bind.
Day 3 — Objects and arrays
Destructuring, spread, rest, prototypes, classes, inheritance, array methods, Map, Set and copying.
Day 4 — Asynchronous JavaScript
Callbacks, promises, async and await, event loop, microtasks, tasks, fetch(), promise combinators and cancellation.
Day 5 — Browser and frontend
DOM, events, bubbling, capturing, delegation, browser storage, CORS, API calls and script loading.
Day 6 — Coding practice
Strings, arrays, sorting, searching, duplicates, frequency counts, Two Sum, recursion, debounce, throttle and basic utility implementations.
Day 7 — Mock interview and revision
Review output questions, explain concepts aloud, write code without looking at solutions and practice follow-up questions.
What to do every day
- Answer 15–20 questions aloud.
- Write 3–5 code problems without looking at solutions.
- Predict the output of 5 code snippets.
- Revisit concepts you cannot explain clearly.
- Review the mistakes you made instead of just moving on.
27. JavaScript Interview Revision Checklist
Use this checklist before your interview to identify any gaps.
Track your preparation
Fundamentals
- JavaScript basics and features
- ECMAScript
- Java vs JavaScript vs TypeScript
- Data types
- Primitive vs reference behavior
- null vs undefined
- NaN
- Type coercion
- == vs ===
- Truthy and falsy values
- typeof and instanceof
- var, let and const
- Scope and scope chain
- Hoisting and TDZ
Functions
- Function declarations and expressions
- Arrow functions
- Parameters and arguments
- Default and rest parameters
- Callbacks
- Higher-order functions
- Pure functions
- IIFE
- Recursion
- Currying and composition
- Generators
- Closures
Objects and OOP
- Object creation
- Properties and methods
- Destructuring
- Spread and rest
- Shallow vs deep copy
- Object.assign and structuredClone
- Prototypes and prototype chain
- Constructor functions
- new
- Classes and inheritance
- super
- Method overriding
- Static methods
- Private fields
- Encapsulation, abstraction, polymorphism
- Composition vs inheritance
Arrays and data structures
push(),pop(),shift(),unshift()slice()vssplice()map(),filter(),reduce()find(),some(),every()includes()andindexOf()sort()andreverse()for...invsfor...ofArray.from()andArray.isArray()flat()andflatMap()SetandMapWeakMapandWeakSet- Stacks and queues
Async JavaScript
- Synchronous vs asynchronous
- Callbacks and callback hell
- Promises and states
then(),catch(), andfinally()- Promise chaining
asyncandawaitPromise.all(),Promise.race(),Promise.allSettled(), andPromise.any()- Event loop
- Call stack
- Microtasks and tasks (macrotasks)
- Timers
queueMicrotask()AbortController- Concurrency vs parallelism
Browser
- DOM
- Element selection
- DOM manipulation
innerHTMLvsinnerTextvstextContent- Event handling
- Event bubbling and capturing
- Event delegation
targetvscurrentTargetpreventDefault()vsstopPropagation()DOMContentLoadedvsloadasyncvsdeferlocalStorageandsessionStorage- IndexedDB
- Fetch API
- CORS
- JSON
Professional development
- Error handling
- Custom errors
- Debugging and DevTools
- Source maps
- Transpilation and bundling
- npm and package.json
- CommonJS vs ES modules
- Garbage collection
- Memory leaks
- Debouncing and throttling
- Memoization
- Lazy loading
- Code splitting and tree shaking
- Web Workers
- Performance profiling
Security and testing
- XSS (Cross-Site Scripting)
- CSRF (Cross-Site Request Forgery)
- Content Security Policy (CSP)
- Input validation
- Sanitization
- Secure storage
- Unit, integration, and end-to-end testing
- Mocks, stubs, and spies
- Test coverage
Coding practice
- Reverse a string
- Palindrome check
- Largest and smallest number
- Second-largest number
- Remove duplicates
- Find duplicates
- Frequency count
- Anagrams
- Flatten nested array
- Missing number
- Two Sum
- Prime number
- Factorial
- Fibonacci
- Capitalize words
- Merge sorted arrays
- Array intersection
- Group objects
- Debounce
- Throttle
- Custom
map,filter, andreduce - Counter with closure
- Memoization
- Promise delay
- Retry function
Promise.all()- Deep clone
- Custom
bind()
28. Frequently Asked JavaScript Interview Questions
Is JavaScript easy to learn?
JavaScript is relatively approachable for beginners because it can run directly in a browser and has a flexible syntax. However, understanding closures, asynchronous behavior, prototypes, coercion and the runtime takes time and practice.
How many JavaScript questions should I prepare for an interview?
There is no fixed number. Focus on the concepts behind common questions. Being able to explain and apply 50–100 important concepts is more useful than memorizing hundreds of short answers without understanding them.
What are the most difficult JavaScript interview topics?
Candidates often find these topics challenging:
- Closures
- Scope and hoisting
thisbinding- Type coercion
- Prototypal inheritance
- Event loop
- Promise chaining
- Async and await
- Shallow vs deep copying
- Output-based questions
- Implementing debounce and throttle
- Handling asynchronous errors
Are JavaScript coding questions asked in interviews?
Yes. Depending on the position, interviewers may ask you to solve string, array, object, recursion, sorting, searching and asynchronous problems.
Frontend interviews may also include DOM manipulation and event handling. Experienced interviews may include implementation tasks such as debouncing, throttling, memoization, custom array methods and promise utilities.
Is JavaScript enough for a frontend developer interview?
JavaScript is essential but not sufficient by itself. Most frontend interviews also include HTML, CSS, a framework such as React, browser behavior, accessibility, API integration, performance and testing.
Do JavaScript interviews include DSA?
Yes. JavaScript can be used for Data Structures and Algorithms interviews. Common topics include arrays, strings, hash maps, sets, stacks, queues, recursion, sorting, searching, trees and graphs.
Do I need to know ES6 for a JavaScript interview?
Yes. Modern JavaScript features are part of everyday development. You should understand arrow functions, let, const, template literals, destructuring, spread and rest, classes, modules and promises.
What is the difference between ES5 and ES6?
ES5 was released in 2009. ES6, also called ECMAScript 2015, introduced a major update in 2015 with features such as let, const, arrow functions, classes, promises, template literals, destructuring and modules.
Modern JavaScript includes many features introduced after ES6, so interviews often use “ES6” loosely to refer to modern JavaScript syntax and capabilities.
Which JavaScript version should I prepare for?
Prepare modern JavaScript. Learn the core language and commonly used ES2015+ features while also understanding older patterns you may encounter in existing codebases.
You do not need to memorize every yearly ECMAScript release. Focus on language features that are widely used and relevant to the role.
Can I use ChatGPT or AI to prepare for JavaScript interviews?
AI can help explain concepts, generate practice questions, review your code and create mock interviews. However, you should write and run code yourself. Interviewers may ask follow-up questions that reveal whether you understand the solution or simply memorized it.
How should I answer a JavaScript interview question?
Use this simple approach:
- Give a direct definition.
- Explain how it works.
- Show a small example.
- Mention where it is useful.
- Explain a limitation or common mistake when relevant.
For coding questions:
- Clarify the input and expected output.
- Explain your approach.
- Write the code.
- Test normal and edge cases.
- Discuss time and space complexity.
29. JavaScript Interview Topic Map: Everything You Should Know
Use this as a quick map of the concepts covered in this guide. If a question appears in your interview that is worded differently, it will likely fall into one of these areas.
| Topic | Concepts and entities |
|---|---|
| JavaScript language | JavaScript, ECMAScript, ES5, ES6, ES2015, modern JavaScript, TypeScript |
| Variables and scope | var, let, const, global scope, local scope, block scope, lexical scope, scope chain |
| Execution behavior | Hoisting, Temporal Dead Zone, execution context, call stack |
| Data types | String, Number, Boolean, BigInt, Symbol, undefined, null, Object |
| Type system | Dynamic typing, primitive types, reference types, type coercion |
| Operators | Strict equality, loose equality, logical operators, nullish coalescing, optional chaining, ternary |
| Functions | Function declaration, function expression, arrow function, callback, higher-order function, pure function, IIFE |
| Advanced functions | Closure, recursion, currying, composition, generator, memoization |
this | Dynamic binding, lexical binding, method calls, call, apply, bind |
| Objects | Properties, methods, object literals, destructuring, spread, rest, copying |
| Object-oriented JavaScript | Prototype, prototype chain, prototypal inheritance, constructor, new, classes, extends, super, static, private fields |
| OOP concepts | Encapsulation, abstraction, polymorphism, inheritance, composition |
| Arrays | Array methods, iteration, transformation, searching, sorting, flattening, merging |
| Array methods | map, filter, reduce, forEach, find, some, every, slice, splice, flat, flatMap |
| Data structures | Array, Object, Map, Set, WeakMap, WeakSet, stack, queue |
| Strings | String methods, template literals, split, join, slice, substring, trim, regex |
| Asynchronous programming | Callback, callback hell, Promise, promise chaining, async, await |
| Promise methods | then, catch, finally, all, race, allSettled, any |
| JavaScript concurrency | Event loop, task queue, microtask queue, timers, concurrency, parallelism |
| Browser | DOM, browser events, event listeners, event propagation, browser APIs |
| Event handling | Bubbling, capturing, delegation, target, currentTarget, preventDefault, stopPropagation |
| Web APIs | Fetch, AbortController, Web Workers, requestAnimationFrame, queueMicrotask |
| Browser storage | localStorage, sessionStorage, IndexedDB, cookies |
| Networking | HTTP requests, APIs, JSON, CORS, request errors, REST |
| JavaScript modules | ES Modules, import, export, CommonJS, require, module scope |
| Node.js | Node runtime, event loop, npm, package.json, Express, middleware, Worker Threads |
| Error handling | try, catch, finally, throw, Error, TypeError, ReferenceError, RangeError |
| Tooling | npm, bundlers, transpilers, source maps, Webpack, Vite, Rollup |
| Performance | Garbage collection, memory leaks, debouncing, throttling, lazy loading, code splitting, tree shaking |
| Security | XSS, CSRF, CSP, input validation, sanitization, secure storage |
| Testing | Unit testing, integration testing, end-to-end testing, Jest, Vitest, mocks, stubs, spies, coverage |
| Coding interview | Strings, arrays, frequency counters, Two Sum, Fibonacci, recursion, custom functions, utilities |
This broad coverage is what makes the article useful for more than one type of JavaScript interview. It can serve as a preparation reference for frontend, full-stack and Node.js candidates while allowing readers to jump straight to the topics they need.
30. How to Use This Guide on the Day Before Your Interview
If your interview is tomorrow, don’t start from question one and attempt to read the entire article line by line.
Use this priority order:
High-priority revision
Know these well enough to explain and code
varvsletvsconst- Scope, hoisting and TDZ
- Closures
thisand arrow functionscall,applyandbind==vs===and coercion- Arrays and their methods
- Objects, prototypes and classes
- Promises and
async/await - Event loop and output questions
- DOM and event delegation
- Fetch, error handling and CORS
- Shallow vs deep copy
- Debouncing and throttling
- Coding problems with strings and arrays
Then revise role-specific topics. For example, if you’re applying for a React role, spend extra time on frontend topics and React itself. If you’re applying for a Node.js role, focus on runtime behavior, asynchronous I/O, modules, middleware, streams and API handling.
31. Official Resources for Further JavaScript Study
This guide is designed to be your interview preparation resource, but when you need to understand a concept beyond the interview answer, use technical documentation rather than relying on memorized explanations.
The most useful reference for understanding JavaScript language behavior, browser APIs, syntax and examples.
The language standard and the committee that develops JavaScript features.
Essential for backend JavaScript, runtime APIs, asynchronous operations and server-side development.
Learn JavaScript testing, assertions, mocks and test organization.
Final advice
The best way to prepare for a JavaScript interview is not to memorize the answer to every question. It is to understand how JavaScript behaves well enough to explain unfamiliar code.
When you understand scope, closures, objects, functions, promises and the event loop, many interview questions stop feeling like separate topics. They become different ways of testing the same underlying knowledge.
Keep this guide as your reference. Practice writing the code, predicting outputs and explaining your reasoning. If you can do those three things consistently, you will be much better prepared for your next JavaScript interview.
- JavaScript Interview Questions and Answers: Complete Guide for Beginners and Experienced Developers - November 27, 2026
- GenAI / LLM Interview Questions for Experienced Developers (3 and 5 Years Experience) - November 24, 2026
- Is Prompt Engineering (Natural Language) the New Programming Language? - November 24, 2026








