Below is a practical JavaScript interview guide covering fundamentals, ES6+, asynchronous programming, DOM, browser APIs, advanced concepts, performance, and modern JavaScript patterns.
1. JavaScript Fundamentals
1. What is JavaScript?
Answer:
JavaScript is a high-level, dynamically typed programming language primarily used to build interactive web applications. It runs in browsers and also on servers through runtimes such as Node.js.
Key characteristics:
- Dynamically typed
- Prototype-based
- First-class functions
- Garbage collected
- Single-threaded execution model
- Supports asynchronous programming
- Event-driven
2. Is JavaScript compiled or interpreted?
Answer:
Modern JavaScript engines use JIT (Just-In-Time) compilation.
For example, the V8 engine used by Chrome and Node.js:
- Parses JavaScript.
- Generates an AST.
- Produces bytecode.
- Executes bytecode.
- Optimizes frequently executed code using JIT compilation.
So saying JavaScript is simply “interpreted” is an oversimplification.
3. What are JavaScript’s primitive data types?
Answer:
JavaScript has seven primitive types traditionally:
string
number
bigint
boolean
undefined
symbol
null
Modern JavaScript therefore has 7 primitive types.
Everything else is an object.
const name = "Bill"; // string
const age = 55; // number
const active = true; // boolean
const value = undefined; // undefined
const empty = null; // null
const id = Symbol("id"); // symbol
const big = 123n; // bigint
4. What is the difference between primitive and reference values?
Answer:
Primitive values are immutable values:
let x = 10;
let y = x;
y = 20;
console.log(x); // 10
Objects are reference values:
const a = { name: "Bill" };
const b = a;
b.name = "John";
console.log(a.name); // John
Both a and b reference the same object.
5. What is the difference between var, let, and const?
Answer:
| Feature | var | let | const |
|---|---|---|---|
| Function scoped | Yes | No | No |
| Block scoped | No | Yes | Yes |
| Redeclaration | Yes | No | No |
| Reassignment | Yes | Yes | No |
| Hoisted | Yes | Yes\* | Yes\* |
let and const are in the Temporal Dead Zone (TDZ) before initialization.
console.log(x); // undefined
var x = 10;
But:
console.log(y); // ReferenceError
let y = 10;
6. What is hoisting?
Answer:
Hoisting is the behavior where declarations are processed before code execution within their scope.
console.log(x); // undefined
var x = 10;
Function declarations are also hoisted:
sayHello();
function sayHello() {
console.log("Hello");
}
let and const are hoisted too, but cannot be accessed before initialization because of the TDZ.
7. What is the Temporal Dead Zone?
Answer:
The TDZ is the period between entering a scope and initializing a let, const, or class declaration.
{
console.log(x); // ReferenceError
let x = 10;
}
The variable exists in the lexical environment but cannot be accessed until initialization.
8. What is the difference between == and ===?
Answer:
== performs type coercion.
=== checks both type and value without implicit conversion.
5 == "5"; // true
5 === "5"; // false
Generally, prefer:
JavaScript
===
because it avoids unexpected coercion.
9. What is type coercion?
Answer:
Type coercion is converting one data type into another.
Implicit coercion:
JavaScript
"5" + 2; // "52"
Explicit coercion:
Number("5"); // 5
String(10); // "10"
Boolean(1); // true
10. What is NaN?
Answer:
NaN means Not-a-Number and represents an invalid numeric result.
JavaScript
Number("hello"); // NaN
Interestingly:
JavaScript
typeof NaN; // "number"
Use:
JavaScript
Number.isNaN(value)
to reliably test for NaN.
2. Scope, Functions & Closures
11. What is scope?
Answer:
Scope determines where variables can be accessed.
JavaScript has:
- Global scope
- Function scope
- Block scope
- Module scope
Example:
{
let x = 10;
}
console.log(x); // ReferenceError
12. What is lexical scope?
Answer:
Lexical scope means variable accessibility is determined by where code is written, not where it is called.
const x = 10;
function outer() {
function inner() {
console.log(x);
}
inner();
}
outer();
inner() can access x because of lexical scope.
13. What is a closure?
Answer:
A closure occurs when a function retains access to variables from its outer lexical scope even after the outer function has returned.
function counter() {
let count = 0;
return function () {
return ++count;
};
}
const increment = counter();
console.log(increment()); // 1
console.log(increment()); // 2
Closures are commonly used for:
- Data encapsulation
- Factory functions
- Callbacks
- Memoization
- Function currying
14. What is a callback function?
Answer:
A callback is a function passed to another function to be executed later.
function processUser(name, callback) {
callback(name);
}
processUser("Bill", name => {
console.log(name);
});
15. What is a higher-order function?
Answer:
A higher-order function either:
- Accepts a function as an argument, or
- Returns a function.
Examples:
JavaScript
[1, 2, 3].map(x => x * 2);
map() is a higher-order function.
16. What is an IIFE?
Answer:
IIFE means Immediately Invoked Function Expression.
(function () {
console.log("Executed immediately");
})();
Historically, IIFEs were commonly used to create private scopes before ES modules became standard.
17. What is a pure function?
Answer:
A pure function:
- Produces the same output for the same input.
- Has no observable side effects.
function add(a, b) {
return a + b;
}
This is pure.
18. What is function currying?
Answer:
Currying converts a function with multiple arguments into a sequence of functions.
const add = a => b => c => a + b + c;
console.log(add(1)(2)(3)); // 6
19. What is function composition?
Answer:
Function composition combines multiple functions so the output of one becomes the input of another.
const double = x => x * 2;
const square = x => x * x;
const compose = (f, g) => x => f(g(x));
console.log(compose(square, double)(3)); // 36
20. What is the difference between a function declaration and function expression?
Answer:
Function declaration:
function add(a, b) {
return a + b;
}
Function expression:
const add = function(a, b) {
return a + b;
};
Function declarations are hoisted with their function body. Function expressions follow the initialization rules of the variable holding them.
3. this, Objects & Prototypes
21. What is this in JavaScript?
Answer:
this refers to a context determined primarily by how a function is called.
const user = {
name: "Bill",
sayHello() {
console.log(this.name);
}
};
user.sayHello(); // Bill
For regular functions, the call site determines this.
Arrow functions behave differently: they capture this lexically from the surrounding scope.
22. How does this behave in an arrow function?
Answer:
Arrow functions do not have their own this.
const user = {
name: "Bill",
sayHello: () => {
console.log(this.name);
}
};
The arrow function inherits this from its surrounding lexical scope.
Therefore, arrow functions are generally not appropriate as object methods when you need dynamic method this.
23. What are call, apply, and bind?
Answer:
All three can control this.
function greet(city) {
console.log(this.name, city);
}
const user = { name: "Bill" };
greet.call(user, "London");
greet.apply(user, ["London"]);
const bound = greet.bind(user);
bound("London");
Difference:
| Method | Arguments | Execution |
|---|---|---|
call | Individual | Immediate |
apply | Array-like | Immediate |
bind | Individual | Returns new function |
24. What is a prototype?
Answer:
A prototype is an object from which another object can inherit properties and methods.
const person = {
greet() {
console.log("Hello");
}
};
const user = Object.create(person);
user.greet();
JavaScript uses prototype-based inheritance.
25. What is the prototype chain?
Answer:
When JavaScript cannot find a property on an object, it looks up the object’s prototype, then that prototype’s prototype, and so on.
object
↓
prototype
↓
prototype's prototype
↓
null
This is called the prototype chain.
26. What is the difference between __proto__ and prototype?
Answer:
prototype is a property found on constructor functions.
function Person() {}
console.log(Person.prototype);
__proto__ historically exposes an object’s prototype.
const person = {};
console.log(person.__proto__);
Modern code should generally prefer:
Object.getPrototypeOf()
Object.setPrototypeOf()
27. What are JavaScript classes?
Answer:
Classes provide syntactic sugar over JavaScript’s prototype-based inheritance.
class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hello ${this.name}`;
}
}
Methods are stored on the class prototype.
28. What is inheritance in JavaScript?
Answer:
Using classes:
class Animal {
speak() {
console.log("Animal sound");
}
}
class Dog extends Animal {
bark() {
console.log("Woof");
}
}
Dog inherits from Animal.
29. What does super do?
Answer:
super accesses the parent class.
class Dog extends Animal {
speak() {
super.speak();
console.log("Woof");
}
}
It can also be used to invoke the parent constructor.
30. What is object destructuring?
Answer:
const user = {
name: "Bill",
age: 55
};
const { name, age } = user;
It extracts properties into variables.
You can also rename:
JavaScript
const { name: userName } = user;
4. Arrays & Objects
31. What is the difference between map() and forEach()?
Answer:
map() returns a new array.
JavaScript
const result = [1, 2, 3].map(x => x * 2);
forEach() does not return a transformed array.
JavaScript
[1, 2, 3].forEach(x => console.log(x));
Use map() when transforming data.
32. What does filter() do?
Answer:
filter() returns a new array containing elements that satisfy a condition.
const numbers = [1, 2, 3, 4];
const even = numbers.filter(n => n % 2 === 0);
console.log(even); // [2, 4]
33. What does reduce() do?
Answer:
reduce() accumulates an array into a single result.
const total = [1, 2, 3, 4]
.reduce((sum, n) => sum + n, 0);
console.log(total); // 10
It can produce:
- Numbers
- Objects
- Arrays
- Maps
- Complex structures
34. What is the difference between find() and filter()?
Answer:
find() returns the first matching element.
JavaScript
users.find(u => u.id === 10);
filter() returns all matching elements.
JavaScript
users.filter(u => u.active);
35. What is the difference between some() and every()?
Answer:
some() checks whether at least one element satisfies a condition.
JavaScript
[1, 2, 3].some(x => x > 2); // true
every() checks whether all elements satisfy it.
JavaScript
[1, 2, 3].every(x => x > 0); // true
36. What is the spread operator?
Answer:
The spread operator ... expands iterable values or object properties.
const a = [1, 2];
const b = [...a, 3, 4];
console.log(b); // [1, 2, 3, 4]
Objects:
const user = { name: "Bill" };
const updated = {
...user,
age: 55
};
37. What is the rest operator?
Answer:
Rest collects remaining values.
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
The syntax is the same ..., but its meaning depends on context.
38. What is shallow copying?
Answer:
A shallow copy copies only the top-level properties.
const original = {
name: "Bill",
address: {
city: "London"
}
};
const copy = { ...original };
copy.address still references the same nested object.
39. How do you deep clone an object?
Answer:
For structured cloneable data, modern JavaScript provides:
JavaScript
const copy = structuredClone(original);
This is generally preferable to:
JavaScript
JSON.parse(JSON.stringify(obj))
because JSON serialization loses or changes several JavaScript values and cannot represent cyclic structures.
40. What is optional chaining?
Answer:
Optional chaining ?. safely accesses nested properties.
JavaScript
const city = user?.address?.city;
If an intermediate value is null or undefined, evaluation stops and returns undefined.
5. ES6+ Features
41. What are template literals?
Answer:
Template literals use backticks:
const name = "Bill";
const message = `Hello ${name}`;
They support:
- String interpolation
- Multiline strings
- Tagged templates
42. What are default parameters?
Answer:
function greet(name = "Guest") {
return `Hello ${name}`;
}
If no argument is provided, "Guest" is used.
43. What are JavaScript modules?
Answer:
ES modules allow code to be split into reusable files.
// math.js
export function add(a, b) {
return a + b;
}
Then:
JavaScript
import { add } from "./math.js";
Modules provide their own scope and support static imports/exports.
44. What is the difference between named and default exports?
Answer:
Named export:
JavaScript
export function add() {}
Import:
JavaScript
import { add } from "./math.js";
Default export:
JavaScript
export default function add() {}
Import:
JavaScript
import add from "./math.js";
A module can have multiple named exports but only one default export.
45. What is a Symbol?
Answer:
A Symbol is a unique primitive value.
const id = Symbol("id");
const user = {
[id]: 123
};
Symbols are commonly used for unique object property keys.
46. What is a BigInt?
Answer:
BigInt represents integers larger than the safe range of JavaScript’s Number.
JavaScript
const value = 9007199254740993n;
You cannot directly mix BigInt and Number in arithmetic.
JavaScript
1n + 1; // TypeError
47. What is the nullish coalescing operator?
Answer:
?? provides a fallback only when the left side is null or undefined.
JavaScript
const name = user.name ?? "Guest";
Unlike ||, it does not treat values such as 0, false, or "" as missing.
48. What is the logical OR assignment operator?
Answer:
let name = "";
name ||= "Guest";
It assigns "Guest" because the current value is falsy.
Related operators include:
||=
&&=
??=
49. What is Object.freeze()?
Answer:
Object.freeze() prevents modifications to an object’s own properties.
const user = Object.freeze({
name: "Bill"
});
user.name = "John";
console.log(user.name); // Bill
It is shallow, not recursive.
50. What is Object.seal()?
Answer:
Object.seal() prevents adding or removing properties but allows modification of existing writable properties.
const user = {
name: "Bill"
};
Object.seal(user);
user.name = "John"; // allowed
user.age = 55; // not allowed
6. Asynchronous JavaScript
51. Why is JavaScript called single-threaded?
Answer:
JavaScript execution traditionally uses a single main execution thread with one call stack.
However, JavaScript environments can perform asynchronous work through runtime facilities such as:
- Timers
- Network APIs
- File-system APIs in Node.js
- Web Workers
- Worker Threads
The event loop coordinates asynchronous completion with JavaScript execution.
52. What is the event loop?
Answer:
The event loop coordinates synchronous execution with queued asynchronous callbacks/jobs.
Conceptually:
Call Stack
↓
Microtask Queue
↓
Task Queue
↓
Event Loop
The exact scheduling rules are more nuanced, but a key interview point is:
Microtasks are generally processed before the next task is taken from the task queue.
53. What is the call stack?
Answer:
The call stack tracks currently executing function calls.
function a() {
b();
}
function b() {
console.log("Hello");
}
a();
Conceptually:
a()
↓
b()
↓
console.log()
When a function completes, its stack frame is removed.
54. What is a Promise?
Answer:
A Promise represents the eventual completion or failure of an asynchronous operation.
States:
pending
fulfilled
rejected
Example:
const promise = fetch("/api/users");
promise
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
55. What is async/await?
Answer:
async/await provides syntax for working with Promises.
async function getUsers() {
const response = await fetch("/api/users");
return response.json();
}
An async function always returns a Promise.
56. Does await block JavaScript?
Answer:
await suspends execution of the current async function, not the entire JavaScript runtime.
async function test() {
await fetch("/api");
console.log("done");
}
Other JavaScript tasks can continue while the asynchronous operation is pending.
57. What is Promise.all()?
Answer:
Promise.all() waits for all Promises to fulfill.
const results = await Promise.all([
fetch("/users"),
fetch("/orders"),
fetch("/products")
]);
If one rejects, the returned Promise rejects.
It is useful for independent operations that can run concurrently.
58. What is Promise.allSettled()?
Answer:
Promise.allSettled() waits for every Promise regardless of success or failure.
const results = await Promise.allSettled([
task1(),
task2(),
task3()
]);
It returns results such as:
{
status: "fulfilled",
value: ...
}
or:
{
status: "rejected",
reason: ...
}
59. What is Promise.race()?
Answer:
Promise.race() settles as soon as the first input Promise settles.
const result = await Promise.race([
fetch("/api"),
timeout(5000)
]);
It can be useful for implementing timeouts.
60. What is Promise.any()?
Answer:
Promise.any() fulfills when the first Promise fulfills.
const result = await Promise.any([
fetchFromServer1(),
fetchFromServer2(),
fetchFromServer3()
]);
It rejects only when all input Promises reject, with an AggregateError.
7. Event Loop & Async Interview Questions
61. What is the difference between microtasks and macrotasks?
Answer:
Microtasks include:
Promise.then()
queueMicrotask()
Tasks/macrotasks commonly include:
setTimeout()
setInterval()
A simplified ordering is:
Synchronous code
↓
Microtasks
↓
Next task
↓
Microtasks
↓
Next task
62. What is the output?
console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("D");
Answer:
A
D
C
B
Why?
- Synchronous code runs first.
- Promise callback is a microtask.
setTimeoutcallback is a later task.
63. What is callback hell?
Answer:
Callback hell occurs when asynchronous operations become deeply nested.
getUser(id, user => {
getOrders(user, orders => {
getPayment(orders, payment => {
// ...
});
});
});
Promises and async/await improve readability and error handling.
64. How do you handle errors with async/await?
Answer:
async function loadData() {
try {
const response = await fetch("/api");
return await response.json();
} catch (error) {
console.error(error);
throw error;
}
}
65. What happens if an async function throws an error?
Answer:
The returned Promise is rejected.
async function test() {
throw new Error("Failed");
}
test().catch(error => {
console.error(error.message);
});
66. How do you run asynchronous operations concurrently?
Answer:
Instead of:
const a = await taskA();
const b = await taskB();
if the operations are independent:
const [a, b] = await Promise.all([
taskA(),
taskB()
]);
This can reduce total waiting time.
67. What is AbortController?
Answer:
AbortController allows certain asynchronous operations, especially fetch, to be cancelled.
const controller = new AbortController();
fetch("/api/data", {
signal: controller.signal
});
controller.abort();
This is useful for:
- Cancelling HTTP requests
- Search-as-you-type
- Component cleanup
- Avoiding unnecessary work
68. What is debouncing?
Answer:
Debouncing delays execution until a period of inactivity has passed.
Common use case:
User types:
H
He
Hel
Hell
Hello
↓
wait
↓
API request
Useful for search inputs and resize handlers.
69. What is throttling?
Answer:
Throttling limits how frequently a function can execute.
For example:
scroll events:
████████████████████
handler:
█ █ █ █
Useful for:
- Scroll events
- Mouse movement
- Window resize
- High-frequency browser events
70. What is the difference between debounce and throttle?
Answer:
| Debounce | Throttle |
|---|---|
| Waits for inactivity | Limits execution frequency |
| Good for search | Good for scrolling |
| Executes after events stop | Executes at controlled intervals |
8. DOM & Browser
71. What is the DOM?
Answer:
DOM means Document Object Model.
The browser represents an HTML document as a tree of objects that JavaScript can manipulate.
JavaScript
document.querySelector("#app");
72. What is event bubbling?
Answer:
An event propagates from the target element upward through its ancestors.
button
↑
div
↑
body
↑
document
73. What is event capturing?
Answer:
Capturing is the earlier phase of event propagation where the event travels from the document toward the target.
document
↓
body
↓
div
↓
button
74. What is event delegation?
Answer:
Event delegation attaches one handler to a parent instead of many child elements.
list.addEventListener("click", event => {
if (event.target.matches("li")) {
console.log(event.target.textContent);
}
});
Benefits:
- Fewer event handlers
- Works well with dynamically created elements
- Can reduce memory usage
75. What is preventDefault()?
Answer:
It prevents the browser’s default action.
form.addEventListener("submit", event => {
event.preventDefault();
});
76. What is stopPropagation()?
Answer:
It prevents an event from continuing through the propagation path.
JavaScript
event.stopPropagation();
It does not necessarily prevent other listeners on the same element from executing.
77. What is localStorage?
Answer:
localStorage stores string key/value data persistently in the browser.
localStorage.setItem("name", "Bill");
const name = localStorage.getItem("name");
Data survives browser restarts until removed.
78. What is sessionStorage?
Answer:
sessionStorage also stores string key/value data, but it is scoped to the browser page session.
JavaScript
sessionStorage.setItem("token", "abc");
It is generally cleared when the page session ends.
79. What are cookies?
Answer:
Cookies are small pieces of data associated with a web origin/domain and can be sent with HTTP requests depending on their attributes.
Important attributes include:
HttpOnly
Secure
SameSite
Domain
Path
Expires / Max-Age
For sensitive authentication tokens, HttpOnly cookies can prevent JavaScript from directly reading the cookie.
80. What is CORS?
Answer:
CORS stands for Cross-Origin Resource Sharing.
Browsers enforce same-origin restrictions. CORS allows a server to explicitly permit certain cross-origin requests through HTTP response headers.
Example:
http
Access-Control-Allow-Origin: https://example.com
9. Advanced JavaScript
81. What is garbage collection?
Answer:
JavaScript engines automatically reclaim memory that is no longer reachable.
A common conceptual model is mark-and-sweep:
GC Roots
↓
Reachable objects
↓
Unreachable objects → garbage
Developers don’t manually free ordinary JavaScript objects.
82. What causes memory leaks in JavaScript?
Answer:
Common causes include:
- Forgotten event listeners
- Long-lived closures
- Global references
- Timers that aren’t cleared
- Detached DOM nodes
- Unbounded caches
- Subscriptions that aren’t cleaned up
Example:
const timer = setInterval(() => {
// ...
}, 1000);
// Later:
clearInterval(timer);
83. What is a WeakMap?
Answer:
WeakMap stores key/value pairs where keys must be objects.
const cache = new WeakMap();
const user = {};
cache.set(user, "metadata");
WeakMap keys do not prevent garbage collection when the key becomes unreachable.
84. What is a WeakSet?
Answer:
WeakSet stores objects weakly.
const processed = new WeakSet();
processed.add(user);
It is useful for tracking objects without preventing their garbage collection.
85. What is a Map?
Answer:
Map is a collection of key/value pairs.
const map = new Map();
map.set("name", "Bill");
map.set("age", 55);
console.log(map.get("name"));
Unlike ordinary objects, Map keys can be values of different types, including objects.
86. What is the difference between Map and Object?
Answer:
| Map | Object |
|---|---|
| Arbitrary key types | Property keys are strings/symbols |
Has .size | No direct .size |
| Designed as key/value collection | General-purpose object |
| Built-in iteration | Different property enumeration APIs |
| Useful for dynamic dictionaries | Useful for structured records |
87. What is an iterator?
Answer:
An iterator is an object implementing:
JavaScript
next()
which returns:
{
value: ...,
done: ...
}
Example:
const iterator = [1, 2, 3][Symbol.iterator]();
console.log(iterator.next());
88. What is a generator?
Answer:
A generator is a special function that can pause and resume execution.
function* numbers() {
yield 1;
yield 2;
yield 3;
}
const generator = numbers();
console.log(generator.next());
Generators are useful for lazy sequences and custom iteration.
89. What is Symbol.iterator?
Answer:
Symbol.iterator defines how an object is iterated.
Objects implementing it can work with:
JavaScript
for...of
and:
JavaScript
const values = [...object];
Arrays, strings, Maps, and Sets are iterable.
90. What is a Proxy?
Answer:
Proxy allows interception of operations performed on an object.
const user = new Proxy({}, {
get(target, property) {
console.log(`Reading ${property}`);
return target[property];
}
});
Proxies can intercept operations such as:
- Property access
- Assignment
- Function calls
- Property deletion
in- Object construction
10. Modern JavaScript & Practical Interview Questions
91. What is optional chaining combined with nullish coalescing?
Answer:
JavaScript
const city = user?.address?.city ?? "Unknown";
This safely accesses nested properties and provides a fallback only when the result is null or undefined.
92. What is the difference between || and ???
Answer:
const a = 0 || 10;
// 10
const b = 0 ?? 10;
// 0
|| checks for falsiness.
?? checks specifically for:
null
undefined
93. What is memoization?
Answer:
Memoization caches the result of a function based on its inputs.
function memoize(fn) {
const cache = new Map();
return function (x) {
if (cache.has(x)) {
return cache.get(x);
}
const result = fn(x);
cache.set(x, result);
return result;
};
}
Useful when a function is expensive and receives repeated inputs.
94. What is lazy evaluation?
Answer:
Lazy evaluation means delaying computation until the result is actually needed.
Generators are a common JavaScript mechanism for producing values lazily.
function* numbers() {
let i = 0;
while (true) {
yield i++;
}
}
Values are generated only when requested.
95. What is immutability?
Answer:
Immutability means avoiding modification of existing data structures.
Instead of:
JavaScript
user.name = "John";
you might create a new object:
const updatedUser = {
...user,
name: "John"
};
Immutability is especially useful in state management and predictable application architecture.
96. What is strict mode?
Answer:
Strict mode enables stricter JavaScript semantics.
JavaScript
"use strict";
For example, assigning to an undeclared variable becomes an error.
ES modules automatically execute in strict mode.
97. What is the difference between null and undefined?
Answer:
undefined generally means a value has not been assigned or is absent.
let x;
console.log(x); // undefined
null is an explicit representation of “no value.”
JavaScript
const user = null;
98. What is the difference between typeof and instanceof?
Answer:
typeof identifies a broad JavaScript type:
typeof "hello"; // "string"
typeof 10; // "number"
instanceof checks whether an object’s prototype chain contains a constructor’s prototype.
const arr = [];
arr instanceof Array; // true
99. How would you improve JavaScript application performance?
Answer:
Common techniques include:
- Reduce unnecessary DOM operations.
- Minimize JavaScript bundle size.
- Use code splitting.
- Lazy-load modules.
- Cache expensive computations.
- Avoid unnecessary re-renders.
- Debounce/throttle high-frequency events.
- Optimize network requests.
- Use browser caching effectively.
- Avoid memory leaks.
- Use Web Workers for suitable CPU-intensive work.
- Profile before optimizing.
The key interview principle is:
Measure first, then optimize the actual bottleneck.
100. What are the most important JavaScript concepts for a senior developer?
Answer:
For a senior-level JavaScript interview, you should be able to explain much more than syntax.
Focus on:
1. Scope & closures
2. this
3. Prototype chain
4. Event loop
5. Microtasks vs tasks
6. Promises
7. async/await
8. Error handling
9. Concurrency
10. DOM & event delegation
11. Modules
12. Immutability
13. Memory management
14. Garbage collection
15. Performance
16. Security
17. Browser APIs
18. Node.js fundamentals
19. Testing
20. Architecture
A strong senior candidate should also be able to reason about real production problems, for example:
“Why is this API request happening three times?”
“Why does this closure cause a memory leak?”
“Why does this Promise execute before
setTimeout(..., 0)?”
“Why does this React/Angular component keep re-rendering?”
“Why does this code work locally but fail under production load?”
“How would you design a scalable JavaScript/TypeScript frontend?”
⭐ 20 JavaScript Questions You Should Absolutely Master
If you’re preparing for a Senior/Lead Software Engineer interview, I would prioritize these:
| # | Topic | Difficulty |
|---|---|---|
| 1 | var vs let vs const | ⭐ |
| 2 | Hoisting & TDZ | ⭐⭐ |
| 3 | Closures | ⭐⭐⭐ |
| 4 | this | ⭐⭐⭐ |
| 5 | call / apply / bind | ⭐⭐⭐ |
| 6 | Prototype chain | ⭐⭐⭐⭐ |
| 7 | Classes & inheritance | ⭐⭐⭐ |
| 8 | Event loop | ⭐⭐⭐⭐ |
| 9 | Microtasks vs tasks | ⭐⭐⭐⭐ |
| 10 | Promises | ⭐⭐⭐ |
| 11 | async/await | ⭐⭐⭐ |
| 12 | Promise.all / allSettled / race / any | ⭐⭐⭐⭐ |
| 13 | Debouncing vs throttling | ⭐⭐⭐ |
| 14 | Event delegation | ⭐⭐⭐ |
| 15 | Shallow vs deep copy | ⭐⭐⭐ |
| 16 | Map / Set / WeakMap | ⭐⭐⭐ |
| 17 | Garbage collection & memory leaks | ⭐⭐⭐⭐ |
| 18 | Generators & iterators | ⭐⭐⭐⭐ |
| 19 | Modules & modern ES features | ⭐⭐⭐ |
| 20 | JavaScript performance & architecture | ⭐⭐⭐⭐⭐ |
Interview tip
For a senior Java/Full-Stack developer, don’t prepare JavaScript as a collection of definitions. Interviewers increasingly test whether you can predict runtime behavior and explain trade-offs.
For example, this tiny question can reveal a lot:
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
console.log("4");
A senior candidate should immediately explain:
1
4
3
2
and, more importantly, explain why: synchronous execution completes first, Promise reactions are processed as microtasks, and the timer callback runs in a later task.