JavaScript Interview Preparation: 60 Most Asked Questions (1–10)
Below are the first 10 essential JavaScript interview questions, starting from beginner level,
covering core topics. Each question includes an answer and a detailed explanation. The list will
progress to more advanced topics as you continue.
1. What is JavaScript?
Answer:
JavaScript is a high-level, interpreted programming language primarily used for adding
interactive behavior to web pages. It can also be used for server-side development via
environments like [Link].
Explanation:
JavaScript enables dynamic content, event handling, DOM manipulation, and asynchronous
operations. It's a core technology alongside HTML and CSS for web development. Initially
intended only for browsers, its ecosystem now spans backend, mobile, and desktop app
development.
2. What is the difference between var, let, and const?
Answer:
var: Function-scoped, can be redeclared and updated.
let: Block-scoped, can be updated but not redeclared in the same scope.
const: Block-scoped, cannot be updated or redeclared.
Explanation:
var has function scope (works within the current function), can cause confusion due to hoisting.
let and const are introduced in ES6, have block scope (within {}), and solve issues like
accidental variable redeclarations. const creates a read-only reference (though the object it
refers to can be modified).
3. What is hoisting in JavaScript?
Answer:
Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope
before code execution.
Explanation:
Only declarations (not initializations) are hoisted. With var, variables are undefined until
execution reaches the assignment. Function declarations are fully hoisted, so you can call them
before their definition. However, let and const are hoisted but not initialized, leading to a
"temporal dead zone" before their assignment.
4. Explain the concept of closures in JavaScript.
Answer:
A closure is a function bundled together with its lexical environment—variables from the scope in
which it was created.
Explanation:
Closures allow inner functions to access variables from the outer scope, even after the outer
function has returned. They are fundamental to data privacy and advanced design patterns in
JavaScript (e.g., function factories, modules).
5. What are arrow functions and how are they different from regular functions?
Answer:
Arrow functions are a concise syntax for writing functions, introduced in ES6. They don't have
their own this, arguments, or super.
Explanation:
Unlike traditional functions, arrow functions capture the value of this from their enclosing
context, making them unsuitable as methods or constructors. They're ideal for callbacks or
functions that need lexical scoping for this:
const add = (a, b) => a + b;
6. What is the difference between == and === operators?
Answer:
== : Loose equality. Compares after type coercion.
=== : Strict equality. Compares value and type.
Explanation:
With ==, JavaScript converts the operands to the same type before comparison. With ===, no
conversion happens—both value and type must be the same. Always prefer === to avoid
unexpected bugs.
7. Explain event delegation in JavaScript.
Answer:
Event delegation is a technique of using a single event handler to manage events for multiple
child elements by exploiting event bubbling.
Explanation:
Instead of adding separate handlers to every child, you assign one to a parent and use the
event’s target property to determine which child was interacted with. This improves
performance and simplifies code, especially for dynamic elements.
8. What is the DOM?
Answer:
The Document Object Model (DOM) is a programming interface for HTML and XML documents.
It represents the structure of a document as a tree of objects.
Explanation:
Manipulating the DOM allows JavaScript to add, remove, or modify elements and content
dynamically. DOM manipulation is a foundational aspect of client-side web programming.
9. What are template literals in JavaScript?
Answer:
Template literals are string literals allowing embedded expressions, introduced in ES6, defined
with backticks $ ` $.
Explanation:
They enable multi-line strings and string interpolation:
const name = "John";
[Link](`Hello, ${name}!`);
This provides a more readable and convenient way to construct strings.
10. What is the difference between null and undefined?
Answer:
undefined: Variable declared but not assigned a value.
null: Assignment value representing no value or object.
Explanation:
undefined is the default value of an uninitialized variable. null is explicitly assigned by the
programmer to indicate "no value". They are different types: undefined is a type; null is an
object.
Type "continue" to get the next 10 questions and answers covering deeper and more advanced
JavaScript concepts.
continue
without repetition
Certainly! Here are the next 10 JavaScript interview questions (11–20). These transition from
beginner to intermediate-level concepts. Each question includes a clear answer and a detailed
explanation, with no repetitions from the previous set.
JavaScript Interview Questions: 11–20
11. What is the difference between synchronous and asynchronous JavaScript?
Answer:
Synchronous code runs sequentially—each operation waits for the previous one to finish.
Asynchronous code allows certain tasks (like I/O or timers) to run independently of the
main thread.
Explanation:
JavaScript is single-threaded, but async operations (via callbacks, promises, or async/await) let
it handle multiple tasks without blocking. For example:
[Link]("A");
setTimeout(() => [Link]("B"), 1000);
[Link]("C");
// Output: A, C, B
12. What are Promises in JavaScript?
Answer:
A Promise is an object that represents the eventual completion (or failure) of an asynchronous
operation.
Explanation:
Promises have three states:
Pending
Fulfilled
Rejected
Example:
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Done!"), 1000);
});
[Link](result => [Link](result));
They are used to avoid deeply nested callbacks ("callback hell") and can be chained with
.then() and .catch().
13. What is async/await in JavaScript?
Answer:
async/await is syntactic sugar built on top of Promises that allows writing asynchronous code in
a clearer, synchronous-like fashion.
Explanation:
async functions return a Promise. Inside an async function, await pauses code execution until a
Promise settles.
Example:
async function fetchData() {
let response = await fetch('[Link]
let data = await [Link]();
[Link](data);
}
14. What is the event loop in JavaScript?
Answer:
The event loop is part of the JavaScript runtime that handles asynchronous operations. It pushes
tasks from the callback queue to the call stack when the call stack is empty.
Explanation:
It's how JavaScript handles non-blocking I/O. The loop checks the call stack and task queues,
ensuring smooth execution of callbacks and promises.
15. What is a JavaScript callback function?
Answer:
A callback function is a function passed into another function as an argument and executed
after some operation is completed.
Explanation:
Common in asynchronous code:
function greet(name, callback) {
[Link]("Hello " + name);
callback();
}
function sayBye() {
[Link]("Goodbye!");
}
greet("Alice", sayBye);
16. What is a higher-order function in JavaScript?
Answer:
A higher-order function is a function that either takes a function as an argument or returns
another function.
Explanation:
Functions like map, filter, reduce are examples:
const numbers = [1, 2, 3];
const doubled = [Link](n => n * 2); // [2, 4, 6]
They enable functional programming paradigms in JavaScript.
17. What is the this keyword in JavaScript?
Answer:
this refers to the object that is executing the current function.
Explanation:
Its value depends on how the function is called:
In a global function: refers to the global object (window in browsers)
In a method: refers to the object itself
In strict mode: in global function, this is undefined
In arrow functions: this is lexically scoped
18. What is the difference between 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;
};
Explanation:
Function declarations are hoisted (available before they're declared). Function expressions are
not hoisted and can't be used before being defined.
19. Explain the concept of prototypal inheritance in JavaScript.
Answer:
Prototypal inheritance means objects in JavaScript inherit properties and methods from other
objects via a prototype chain.
Explanation:
Each object has an internal property [[Prototype]] (accessible via __proto__) that points to
another object. This allows property lookup up the chain.
Example:
let parent = { greet() { [Link]("Hello!"); } };
let child = [Link](parent);
[Link](); // Hello!
20. What is a shallow copy vs. deep copy in JavaScript?
Answer:
Shallow copy: Copies only the reference to nested objects; both original and copy share
references.
Deep copy: Recursively copies all levels, creating independent objects.
Explanation:
Shallow:
let a = { x: 1, y: { z: 2 } };
let b = [Link]({}, a);
b.y.z = 5; // a.y.z also becomes 5
Deep (using structuredClone or JSON methods):
let c = structuredClone(a); // Available in modern browsers
🔔 Type "continue" to get the next 10 advanced-level questions (21–30).
Let me know if you want questions from a specific topic (e.g. data structures, DOM, ES6+, etc.).
continue
without repetition
Here are the next 10 JavaScript interview questions (21–30)—moving into intermediate to
advanced concepts. These are carefully selected without repeating previous topics and
continue covering key areas like ES6+, memory management, scopes, and more.
✅ JavaScript Interview Questions: 21–30
21. What are JavaScript modules and how do you use import/export?
Answer:
Modules allow you to split your code into reusable pieces. In ES6, modules are supported
natively via the import and export syntax.
Explanation:
export: exposes functions, objects, or variables from a file.
import: brings them into another file.
// [Link]
export function add(x, y) { return x + y; }
// [Link]
import { add } from './[Link]';
[Link](add(2, 3)); // 5
Modules improve maintainability and scope isolation.
22. What is destructuring in JavaScript?
Answer:
Destructuring allows unpacking values from arrays or properties from objects into variables.
Explanation:
Introduced in ES6, it simplifies variable assignment:
const [a, b] = [1, 2]; // Array destructuring
const { name, age } = { name: "Alice", age: 30 }; // Object destructuring
It can also have default values and nested usage, making code cleaner and more expressive.
23. Explain the concept of the "spread operator" and its use cases.
Answer:
The spread operator (...) expands an iterable (like an array or object) into individual elements.
Explanation:
Common uses:
Cloning arrays/objects
Merging arrays/objects
Pass arguments in functions
const arr = [1, 2];
const newArr = [...arr, 3]; // [1, 2, 3]
const obj1 = { a: 1 };
const obj2 = { ...obj1, b: 2 }; // { a: 1, b: 2 }
24. What are default parameters in JavaScript functions?
Answer:
You can provide default values for parameters in a function definition.
Explanation:
Introduced in ES6:
function multiply(a, b = 1) {
return a * b;
}
[Link](multiply(5)); // 5
It prevents undefined parameters and reduces extra logic.
25. What are the different types of scopes in JavaScript?
Answer:
Global scope: Accessible anywhere.
Function scope: Defined with var, restricted to functions.
Block scope: Defined by let and const, valid within {}.
Lexical scope: Inner functions have access to outer scope variables.
Explanation:
Understanding scope is essential for closures, hoisting, and variable lifetime.
26. What is memory leak in JavaScript? How can you prevent it?
Answer:
A memory leak happens when memory is no longer needed but is not released.
Explanation:
Common causes:
Unremoved event listeners
Forgotten timers/intervals
Detached DOM references
Global variables
Prevention:
Use removeEventListener
clearInterval/clearTimeout
Avoid global vars
Use tools (Chrome DevTools, heap snapshots)
27. What are WeakMap and WeakSet in JavaScript?
Answer:
They are collections with weak references to objects, preventing memory leaks.
Explanation:
WeakMap: Key-value pairs. Keys must be objects.
WeakSet: Collection of object references.
They don't prevent garbage collection, unlike Map/Set.
let wm = new WeakMap();
let obj = {};
[Link](obj, "value");
// If obj is no longer referenced elsewhere, it gets garbage collected.
28. What is debounce and throttle in JavaScript?
Answer:
They are performance techniques used to control how frequently functions are executed in
response to events.
Explanation:
Debounce: Delay execution until after a specified time since the last call.
Throttle: Limit execution to once every fixed interval.
Useful for scroll, resize, or input events.
Example debounce:
function debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
29. What is the difference between call(), apply(), and bind()?
Answer:
All three set the this context explicitly.
Explanation:
call(arg1, arg2, ...): calls function with this and arguments.
apply([arg1, arg2, ...]): same but takes arguments as an array.
bind: returns a new function with bound this.
function greet(greeting) {
[Link](`${greeting}, ${[Link]}`);
}
const person = { name: "John" };
[Link](person, "Hi");
[Link](person, ["Hello"]);
const greetJohn = [Link](person);
greetJohn("Welcome");
30. What is the Temporal Dead Zone (TDZ) in JavaScript?
Answer:
TDZ refers to the period between entering a block and the point where a variable is declared
with let or const.
Explanation:
Accessing the variable in this zone before declaration throws a ReferenceError.
[Link](x); // ReferenceError
let x = 10;
This behavior ensures more predictable and safer code compared to var hoisting.
✅ Type continue for the next 10 advanced-level JavaScript interview questions (31–40)
covering topics like Symbols, Iterators, Generators, Error Handling, and more.
Let me know if you want to focus on a specific topic like classes, async patterns, ES2020+,
testing, etc.
continue
without repetition
Great! Here are the next 10 advanced JavaScript interview questions (31–40). These build on
your previous knowledge and dive deeper into topics like symbols, iterators, generators, error
handling, and more — fully unique and with no repetition.
✅ JavaScript Interview Questions: 31–40
31. What are Symbols in JavaScript and what are they used for?
Answer:
Symbols are a unique and immutable primitive data type introduced in ES6, often used as
unique object property keys.
Explanation:
Symbols avoid property name collisions, which is helpful in scenarios like adding hidden
metadata to objects.
const sym = Symbol('id');
const user = { [sym]: 123 };
[Link](user[sym]); // 123
Symbols are not enumerable (won’t appear in for...in or [Link]()) and are often used in
libraries and internal object properties.
32. What are Iterators in JavaScript?
Answer:
An iterator is an object that defines a sequence and returns a value on each iteration via a
next() method.
Explanation:
An object is iterable if it implements the @@iterator method (using [[Link]]()).
const arr = [1, 2, 3];
const iterator = arr[[Link]]();
[Link]([Link]()); // { value: 1, done: false }
Iterators are the foundation for for...of, spread operators, and custom looping.
33. What are Generators in JavaScript?
Answer:
Generators are special functions defined using function* syntax that can pause and resume
execution using yield.
Explanation:
They produce iterators and are useful for managing lazy evaluation or async flow.
function* generatorFn() {
yield 1;
yield 2;
yield 3;
}
const gen = generatorFn();
[Link]([Link]()); // { value: 1, done: false }
Generators can help model complex data streams or implement state machines.
34. What is the difference between for...in and for...of?
Answer:
Loop Iterates Over Use Case
for...in Enumerable property keys Objects
for...of Values of iterable objects Arrays, strings, maps, sets, etc.
Example:
const arr = ['a', 'b', 'c'];
for (let i in arr) [Link](i); // 0, 1, 2
for (let val of arr) [Link](val); // a, b, c
35. How does error handling work in JavaScript with try...catch?
Answer:
JavaScript uses try...catch blocks for synchronous error handling.
Explanation:
try: Code that may throw an error.
catch: Block that handles the error.
finally: (optional) Executes regardless of error or not.
try {
throw new Error("Something went wrong");
} catch (error) {
[Link]([Link]);
} finally {
[Link]("[Link]");
}
Note: Only works for runtime errors, not for compile-time errors.
36. What is optional chaining and why is it useful?
Answer:
Optional chaining (?.) allows you to safely access object properties that might not exist, without
throwing an error.
Explanation:
const user = { profile: { name: "Alice" } };
[Link]([Link]?.name); // "Alice"
[Link]([Link]?.street); // undefined, doesn't throw error
Prevent crashes on deep property access. Especially useful with APIs or dynamic data.
37. What is nullish coalescing (??) in JavaScript?
Answer:
The ?? operator returns the right-hand operand when the left-hand is null or undefined.
Explanation:
let username = null;
[Link](username ?? 'Guest'); // "Guest"
Unlike ||, it doesn’t treat 0, false, or "" as fallback conditions.
38. What is the difference between [Link]() and [Link]()?
Answer:
Feature [Link]() [Link]()
Add properties ❌ No ❌ No
Delete properties ❌ No ❌ No
Modify values ❌ No ✅ Yes
Writable ❌ All properties non-writable ✅ Writable unless defined otherwise
Example:
const obj = { a: 1 };
[Link](obj);
obj.a = 2; // Won’t change
39. How do Map and Object differ in JavaScript?
Answer:
Feature Map Object
Key Types Any (object, function, etc.) Only strings or symbols
Order Ordered Unordered (mostly)
Iteration Easy via .forEach(), .entries() Harder without conversion
Feature Map Object
Performance Better for dynamic key/value Better for static structures
Use Map if:
You need keys of any type
You need guaranteed order
Frequent add/delete operations
40. What is tail call optimization (TCO)?
Answer:
TCO is a technique where the JavaScript engine reuses stack frames for tail-recursive function
calls, improving performance.
Explanation:
A call is in tail position if it’s the last action a function performs.
function factorial(n, acc = 1) {
if (n === 0) return acc;
return factorial(n - 1, acc * n); // Tail call
}
📝 Note: TCO is supported in strict mode, but not widely implemented in browsers yet.
✅ Type continue to get questions 41–50, covering even more advanced topics like proxy, meta-
programming, async patterns, immutability, testing, and performance optimization.
Or let me know if you'd like to focus on specific topics like DOM, testing, [Link], or JavaScript
engines.
continue
without repetition
Here’s the next set of 10 JavaScript interview questions (41–50). These questions explore
advanced JS features such as proxies, reflection, async patterns, immutability, security, testing,
and performance enhancements—building on concepts without repeating what we’ve already
covered.
✅ JavaScript Interview Questions: 41–50
41. What is a Proxy in JavaScript?
Answer:
A Proxy is an object that wraps another object and intercepts operations like reading, writing,
and function invocation using handler functions (traps).
Explanation:
Proxies allow for meta-programming—modifying fundamental behaviors dynamically:
const user = { name: "John" };
const proxy = new Proxy(user, {
get(target, prop) {
return prop in target ? target[prop] : "Property not found";
},
});
[Link]([Link]); // John
[Link]([Link]); // Property not found
Use cases: validation, logging, access control, reactive frameworks ([Link] uses proxies).
42. What is the Reflect API in JavaScript?
Answer:
Reflect is a built-in object that exposes methods corresponding to the default behavior of
various object operations, often used with Proxies for consistency.
Explanation:
const obj = { name: "Alice" };
[Link](obj, 'age', 25);
[Link]([Link](obj, 'age')); // 25
Reflect provides a cleaner, function-based alternative to Object methods and is often used inside
proxy traps to avoid recursion or maintain original behavior.
43. What is the [Link]() method used for?
Answer:
It allows defining or modifying a property on an object with more control over enumerability,
writability, and configurability.
Explanation:
let obj = {};
[Link](obj, 'x', {
value: 42,
writable: false
});
obj.x = 100; // Won’t change because writable is false
[Link](obj.x); // 42
Frequently used in creating read-only properties, getters/setters, and controlling object
structure.
44. How does asynchronous iteration work with for await...of ?
Answer:
for await...of allows you to loop over async iterables (objects implementing
[[Link]]), commonly used with data streams or API calls.
Explanation:
async function* asyncGen() {
yield "A";
yield "B";
}
(async () => {
for await (const val of asyncGen()) {
[Link](val);
}
})();
It’s especially useful with async data sources (e.g. streams, paginated APIs).
45. What is immutability in JavaScript, and how do you enforce it?
Answer:
Immutability means data cannot be changed after it’s created. In JavaScript, immutability avoids
side effects and improves predictability.
Explanation:
Ways to enforce immutability:
Use [Link]() to freeze objects
Return new objects using spread/rest
Prefer functions like map, filter which don’t mutate
Use libraries like Immer, [Link]
Example:
const original = { a: 1 };
const updated = { ...original, a: 2 }; // Doesn’t mutate original
46. What security considerations exist when executing JavaScript in the browser?
Answer:
Key concerns:
XSS (Cross-Site Scripting): Unsanitized user input injected into DOM or scripts.
CSRF (Cross-Site Request Forgery): Forged requests with logged-in identity.
Clickjacking: Overlaying content with hidden frames.
Prevention tools/methods:
Use Content Security Policy (CSP)
Sanitize inputs (e.g. DOMPurify)
Escape outputs
Use modern HTTP headers
Avoid eval() and innerHTML when possible
47. What is the purpose of Service Workers in JavaScript?
Answer:
A Service Worker is a script that runs in the background of a browser and enables features like
offline caching, push notifications, and networking control.
Explanation:
It acts as a programmable network proxy.
[Link]('fetch', event => {
[Link](fetch([Link]));
});
Used in Progressive Web Apps (PWAs) to enhance performance and offline experience.
48. What is tree shaking in JavaScript bundlers like Webpack?
Answer:
Tree shaking is a technique used during bundling to eliminate unused (dead) code from the
final output.
Explanation:
Works only with ES6 modules (import/export).
Helps reduce bundle size and improve load time.
Example: Only used parts of a library like Lodash can be imported:
import debounce from 'lodash/debounce'; // instead of whole lodash
49. What are the benefits of using unit testing frameworks like Jest or Mocha in
JavaScript?
Answer:
Assertions for correctness
Test coverage tracking
Helps catch regressions
Speeds up debugging
Supports mocking and async testing
Example Jest test:
test('adds 1 + 2 = 3', () => {
expect(1 + 2).toBe(3);
});
Testing is key for maintaining long-term code quality.
50. How do you improve performance in large-scale JavaScript applications?
Answer:
Common optimizations include:
Code splitting: Lazy-load only what's needed
Debounce/throttle for event-heavy interactions
Memoization for expensive operations
Minification & compression (gzip, brotli)
Service Workers for caching
Virtual DOM diffing (React)
Web Workers for non-blocking background tasks
Tooling like Lighthouse, DevTools, Webpack Analyzer can help identify bottlenecks.
✅ Type continue to get the final batch (51–60) covering
very advanced/modern JavaScript
concepts like memory models, module patterns, real-world coding pitfalls, [Link] integration,
and ECMAScript future features.
Let me know if you'd like a PDF export or topic-specific deep dives.
continue
Absolutely! Let’s complete your JavaScript interview prep with the final set of 10 advanced-
level questions (51–60). This batch covers important topics like module patterns, runtime
engines, event behavior, [Link], and practical debugging techniques — with no repeats from
earlier sets.
✅ JavaScript Interview Questions: 51–60
51. What is an Immediately Invoked Function Expression (IIFE)?
Answer:
An IIFE is a function that runs immediately after it is defined.
Explanation:
It creates a new scope and avoids polluting the global namespace.
(function () {
[Link]("Executed immediately!");
})();
Useful for:
Encapsulation
Initializing logic without global variables
Creating private scopes (before let/const existed)
52. What is the Module Pattern in JavaScript?
Answer:
The module pattern is a design pattern that uses closures and IIFE to create private/public
encapsulation.
Explanation:
const Counter = (function () {
let count = 0; // private
return {
increment() {
return ++count;
},
getCount() {
return count;
},
};
})();
[Link](); // 1
[Link](); // 1
Common prior to ES6 modules, reduces global references and adds information hiding.
53. What is event bubbling and event capturing in the DOM?
Answer:
They refer to two phases of event propagation in the DOM:
Capturing: Event is captured from root down to the target.
Bubbling: Event bubbles from the target back up the DOM tree.
Explanation:
[Link]('click', handler, true); // Capturing
[Link]('click', handler, false); // Bubbling
By default, events bubble. You can stop propagation with [Link]() and cancel
default actions using [Link]().
54. What are microtasks and macrotasks in the event loop?
Answer:
Task Type Examples Timing
Microtask [Link], MutationObserver Runs after current task, before next macrotask
Macrotask setTimeout, setInterval, I/O Enqueued after all microtasks
Explanation:
[Link]("Start");
setTimeout(() => [Link]("Macrotask"), 0);
[Link]().then(() => [Link]("Microtask"));
[Link]("End");
// Output: Start → End → Microtask → Macrotask
Understanding task queues is crucial for debugging timing issues and UI delay bugs.
55. How does [Link] differ from browser JavaScript environments?
Answer:
Feature [Link] Browser
API Access File system, OS, network DOM, Web APIs, localStorage
Global Object global window
Module System CommonJS or ES Modules ES Modules
Explanation:
Node is designed for server-side scripting and runs on Google’s V8 engine. It lacks browser-
specific objects (like document) but adds server-side tools.
56. What is a memory heap and call stack in JavaScript?
Answer:
Memory heap: Where objects, functions, and variables are allocated.
Call stack: Data structure that tracks function calls.
Explanation:
function a() {
b();
}
function b() {
[Link]("Call stack trace");
}
a(); // a -> b -> log
When the call stack grows too large (like unbounded recursion), it triggers a “stack overflow.”
57. What is the difference between shallow equality (==) and deep equality?
Answer:
== or ===: Compare primitives or object references.
Deep equality: Checks if values/properties inside objects are the same.
Example:
const a = { x: 1 };
const b = { x: 1 };
[Link](a === b); // false (different references)
// Deep equality using JSON
[Link](a) === [Link](b); // true
Libraries like [Link]() are often used for deep comparison.
58. How can you debug JavaScript efficiently in the browser?
Answer:
Use [Link](), [Link](), [Link]()
Use breakpoints in Chrome DevTools
Observe live changes in the Sources > Watch expressions
Audit with Performance and Memory tabs
Use debugger; statement to pause execution
Bonus Tip:
Use Preserve Log in the console to track errors across reloads.
59. What’s the difference between soft and hard binding in JavaScript?
Answer:
Soft binding: Allows fallback but still flexible.
Hard binding: Forces function to always use a specific this.
Example:
function greet() {
[Link]([Link]);
}
const person = { name: "Alice" };
const hardBound = [Link](person); // permanently bound
hardBound(); // "Alice"
Soft binding often used in dynamic contexts (e.g., event handlers with fallback).
60. What upcoming features in JavaScript (from ECMAScript proposals) should
you know?
Answer:
Records & Tuples: Immutable value-based structures
Pattern Matching: Similar to switch statements but more expressive
Type Annotations (via decorators/TS integration)
AsyncContext / AsyncScoped: For managing async state
Pipeline Operator (|>): Functional chaining syntax
Example:
// Potential future syntax
const result = value
|> doubler
|> increment;
Stay current with proposals at: [Link]
✅ Congratulations! That completes all 60 JavaScript interview questions.
Let me know if you want:
A PDF summary of all 60 Q&As
A topic-wise breakdown
A lightning revision sheet
Or prep for JavaScript coding rounds and challenges
🧠 Ready for anything from frontend frameworks (React, Vue) to backend with Node or full-stack
system design!
also give questions on code snippets
with exact code and outputs
no errors. please
Absolutely! Let's now focus on JavaScript code snippet-based interview questions —
complete with code, correct outputs, and clear explanations. These are extremely common in
interviews and coding rounds.
We’ll keep everything clean, working (no errors), realistic, and insightful.
✅ JavaScript Code Snippet Interview Questions (Set 1: 1–10)
1. What will be the output of the following code?
let a = 1;
let b = a++;
[Link](a, b);
Output:
2 1
Explanation:
a++ increments a after returning its value. So b gets 1, then a becomes 2.
2. What does this array code print?
const arr = [1, 2, 3];
arr[10] = 5;
[Link]([Link]);
Output:
11
Explanation:
Setting arr creates a sparse array. The length becomes 10 + 1 = 11.
3. What’s the result of this function + coercion?
function add(a, b) {
return a + b;
}
[Link](add("5", 3));
Output:
53
Explanation:
JavaScript converts number 3 to a string "3" and concatenates with "5" ⇒ "53".
4. What does this scoping example print?
let x = 10;
function test() {
let x = 20;
[Link](x);
}
test();
[Link](x);
Output:
20
10
Explanation:
x inside the function shadows the outer x. Global and function scopes are separate.
5. What does this closure return?
function outer() {
let count = 0;
return function () {
count++;
return count;
};
}
const next = outer();
[Link](next());
[Link](next());
Output:
1
2
Explanation:
Closures preserve the count variable across calls to next() even after outer() returns.
6. What does this object mutation code display?
const obj1 = { a: 1 };
const obj2 = obj1;
obj2.a = 5;
[Link](obj1.a);
Output:
Explanation:
Objects are assigned by reference, so obj1 and obj2 point to the same memory.
7. What is the output of this arrow function and this context?
const obj = {
name: "Sam",
greet: () => {
[Link](`Hello, ${[Link]}`);
}
};
[Link]();
Output:
Hello, undefined
Explanation:
Arrow functions do not bind their own this. Here, this refers to the global object, not obj.
8. What will this setTimeout output be?
[Link]("Start");
setTimeout(() => [Link]("Timeout"), 0);
[Link]("End");
Output:
Start
End
Timeout
Explanation:
setTimeout is asynchronous. It runs after current call stack (event loop behavior).
9. What does this loop + let output?
for (let i = 0; i < 3; i++) {
setTimeout(() => [Link](i), 100);
}
Output:
0
1
2
Explanation:
Because of let, each i is block-scoped. So each setTimeout gets its own copy of i.
10. What is the result of spreading a string?
const str = "hello";
const chars = [...str];
[Link](chars);
Output:
['h', 'e', 'l', 'l', 'o']
Explanation:
Strings are iterable. The spread operator splits them into arrays of single characters.
✅ Next Steps:
Type "continue" for the next batch of 10 code snippet questions (11–20).
Or, ask for topic-specific code quizzes like:
Closures
Async patterns
DOM manipulation
Array methods
Let me know how you'd like to proceed.
more
Here are the next 10 JavaScript code snippet interview questions (11–20). As before, each has
exact code, expected output, and a clear explanation—always error-free.
✅ JavaScript Code Snippet Interview Questions (11–20)
11. What’s the output of this map example?
const nums = [1, 2, 3];
const result = [Link](x => x * 2);
[Link](result);
Output:
[2, 4, 6]
Explanation:
map creates a new array by multiplying each element by 2.
12. What does this short-circuiting code print?
let x = 0;
[Link](x || 42);
[Link](x && 42);
Output:
42
0
Explanation:
x || 42 gives 42 because x is falsy.
x && 42 gives 0 because x is falsy, so evaluation stops there.
13. What’s the output—== vs. ===?
[Link](false == 0);
[Link](false === 0);
Output:
true
false
Explanation:
false == 0 is true (type coercion).
false === 0 is false (strict comparison, no type conversion).
14. What does this array method output?
const arr = [5, 10, 15, 20];
const sum = [Link]((acc, val) => acc + val, 0);
[Link](sum);
Output:
50
Explanation:
reduce accumulates the sum: 5 + 10 + 15 + 20 = 50.
15. What will be logged by this destructuring code?
const obj = {a: 1, b: 2};
const { b, a } = obj;
[Link](a, b);
Output:
1 2
Explanation:
Order in destructuring doesn’t matter; properties are matched by name.
16. What’s the value of typeof null ?
[Link](typeof null);
Output:
object
Explanation:
This is a long-standing quirk in JavaScript—null is considered an object by typeof.
17. What gets printed here with default parameters?
function greet(name = "Guest") {
[Link](`Hello, ${name}`);
}
greet();
greet("Alice");
Output:
Hello, Guest
Hello, Alice
Explanation:
If no argument is passed, name defaults to "Guest".
18. What does this print regarding const and arrays?
const arr = [1, 2];
[Link](3);
[Link](arr);
Output:
[1, 2, 3]
Explanation:
const prevents rebinding, not mutation, so you can still push to the array.
19. What will this string slice code log?
const str = "JavaScript";
[Link]([Link](0, 4));
Output:
Java
Explanation:
[Link](0,4) returns substring from index 0 up to (not including) 4.
20. What is logged by this logical NOT chaining?
[Link](!!"hello");
[Link](!!0);
Output:
true
false
Explanation:
!!"hello" coerces the string to boolean (true), then double-negates to true.
!!0 becomes false.
✅ Next steps:
Type "more" to keep going with another set of 10 code snippet questions (21–30), or specify a
topic for focus (e.g., promises, arrow functions, objects).
continue
Here are 10 more JavaScript code snippet interview questions (21–30), each featuring code,
output, and a concise explanation—no errors and all practical!
✅ JavaScript Code Snippet Interview Questions (21–30)
21. What does this template literal output?
const a = 2, b = 3;
[Link](`Sum: ${a + b}`);
Output:
Sum: 5
Explanation:
Template literals interpolate the result of a + b inside the string.
22. What’s the output of this for...in loop on arrays?
const arr = [7, 8, 9];
for (let i in arr) {
[Link](i);
}
Output:
0
1
2
Explanation:
for...in loops over array indices (as strings), not values.
23. What value does this ternary operation give?
let age = 18;
let status = age >= 18 ? "adult" : "minor";
[Link](status);
Output:
adult
Explanation:
Ternary chooses "adult" since age is 18.
24. What will this code log (function as argument)?
function run(fn) {
fn();
}
run(() => [Link]("Hello!"));
Output:
Hello!
Explanation:
Passing a function as an argument calls it inside run.
25. What’s logged by this find usage?
const list = [4, 5, 6];
[Link]([Link](x => x > 4));
Output:
Explanation:
find returns the first item matching the predicate (x > 4), which is 5.
26. What will this code print (object methods)?
const obj = {
x: 10,
getX() {
return this.x;
}
};
[Link]([Link]());
Output:
10
Explanation:
getX correctly refers to the property x using this.
27. What’s the result when an array is joined?
const items = ["red", "green", "blue"];
[Link]([Link](" | "));
Output:
red | green | blue
Explanation:
join combines array elements into a string with " | " as separator.
28. What does this block-scoping example print?
if (true) {
let z = 10;
[Link](z);
}
// [Link](z); // Would cause error, but is commented out
Output:
10
Explanation:
z is accessible only inside the block.
29. What will this includes call display?
const colors = ['yellow', 'blue'];
[Link]([Link]('blue'));
Output:
true
Explanation:
includes checks for the presence of 'blue' in the array.
30. What is the result of this string method?
const text = "hello world";
[Link]([Link]());
Output:
HELLO WORLD
Explanation:
toUpperCase() transforms all characters in the string to uppercase.
Type "continue" for 10 more code questions (31–40), or specify your favorite topic (arrays,
async, objects, etc.) for tailored snippet challenges!
coding problems in js asked interview to execute
and explain approach
Here are some classic JavaScript coding problems commonly asked in interviews. Each
problem includes the exact code, expected output, and a detailed explanation of the approach
—so you can learn both how to write and how to reason about the solutions.
1. Reverse a String
function reverseString(str) {
return [Link]('').reverse().join('');
}
[Link](reverseString("hello"));
Output:
olleh
Approach:
split('') turns the string into an array of characters.
reverse() reverses the array in place.
join('') joins the reversed array back into a string [1] [2] .
2. Check if a String is a Palindrome
function isPalindrome(str) {
return str === [Link]('').reverse().join('');
}
[Link](isPalindrome("racecar")); // true
[Link](isPalindrome("hello")); // false
Output:
true
false
Approach:
A string is a palindrome if it reads the same backwards. This solution reverses the string and
compares it to the original [3] [1] .
3. Find the Maximum Number in an Array
function findMax(arr) {
return [Link](...arr);
}
[Link](findMax([3, 7, 1, 9]));
Output:
Approach:
The spread operator ...arr expands the array so [Link] can compare all its elements [3] [4] [1] .
4. Sum All Numbers in an Array
function sumArray(arr) {
return [Link]((sum, num) => sum + num, 0);
}
[Link](sumArray([1, 2, 3, 4, 5]));
Output:
15
Approach:
reduce() walks the array, adding each value to an accumulator to produce the total sum [3] [1] [5] .
5. Check if a Number is Prime
function isPrime(num) {
if (num <= 1) return false;
for (let i = 2; i <= [Link](num); i++) {
if (num % i === 0) return false;
}
return true;
}
[Link](isPrime(7)); // true
[Link](isPrime(10)); // false
Output:
true
false
Approach:
Check divisibility from 2 up to sqrt(num). If num is divisible by any in-between, it's not prime [3] [1] .
6. Flatten a Nested Array
function flattenArray(arr) {
return [Link](Infinity);
}
[Link](flattenArray([1, [2, 3], [4, [5, 6]]]));
Output:
[1, 2, 3, 4, 5, 6]
Approach:
flat(Infinity) recursively flattens all nested arrays; alternate is to use recursion [1] .
7. Move Zeros to the End of an Array
function moveZeros(arr) {
const nonZero = [Link](x => x !== 0);
const zeros = [Link](x => x === 0);
return [...nonZero, ...zeros];
}
[Link](moveZeros([0, 1, 0, 3, 12]));
Output:
[1, 3, 12, 0, 0]
Approach:
Separate the non-zeros and zeros, then concat—efficient for interviews, clear logic [5] .
8. Find the First Non-Repeating Character in a String
function firstUniqueChar(str) {
for (let char of str) {
if ([Link](char) === [Link](char)) return char;
}
return null;
}
[Link](firstUniqueChar("aabbcdd")); // 'c'
Output:
c
Approach:
Loop through each char; if its first and last occurrence is the same, it’s unique [5] .
9. Reverse an Array
function reverseArray(arr) {
return [Link]().reverse();
}
[Link](reverseArray([1, 2, 3]));
Output:
[3, 2, 1]
Approach:
Use slice() to copy (avoid mutating original), then reverse [6] .
10. Implement a Debounce Function
function debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => [Link](this, args), delay);
}
}
Approach:
Each time the wrapper runs, clears the timer and sets it again.
fn runs only after the last call’s delay.
Used to limit the rate of calls to functions like API requests or UI updates [3] .
How to Approach These in Interviews
Clarify input/output with the interviewer.
Explain your approach before you code.
Write clean code with clear variable names.
Discuss edge cases out loud: empty arrays, null inputs, very large numbers, etc.
Optimize only if prompted (start with clarity over brevity).
If you need more problems with code execution and step-by-step reasoning, let me know the
topics or difficulty, and I’ll provide more examples!
⁂
more 5
Here are 5 more JavaScript coding problems that are commonly asked in interviews. Each
includes the code, expected output, and an explanation of the approach.
11. Remove Duplicates from an Array
function removeDuplicates(arr) {
return [...new Set(arr)];
}
[Link](removeDuplicates([1, 2, 2, 3, 4, 4, 5]));
Output:
[1, 2, 3, 4, 5]
Approach:
Convert the array to a Set (which only allows unique values), then spread it back to an array.
12. Fibonacci Sequence up to N Terms
function fibonacci(n) {
let arr = [0, 1];
for (let i = 2; i < n; i++) {
arr[i] = arr[i - 1] + arr[i - 2];
}
return [Link](0, n);
}
[Link](fibonacci(6));
Output:
[0, 1, 1, 2, 3, 5]
Approach:
Start the sequence, then compute each new value as the sum of the previous two.
13. Count the Occurrence of Each Character in a String
function charCount(str) {
const count = {};
for (let char of str) {
count[char] = (count[char] || 0) + 1;
}
return count;
}
[Link](charCount("aabbc"));
Output:
{ a: 2, b: 2, c: 1 }
Approach:
Iterate through the string, updating a count for each character in an object.
14. Capitalize the First Letter of Each Word
function capitalizeWords(str) {
return str
.split(' ')
.map(word => word[0].toUpperCase() + [Link](1))
.join(' ');
}
[Link](capitalizeWords("hello world javascript"));
Output:
Hello World Javascript
Approach:
Split the string into words, capitalize the first letter of each, then join them back together.
15. Find the Intersection of Two Arrays
function intersection(arr1, arr2) {
return [Link](item => [Link](item));
}
[Link](intersection([1, 2, 3], [2, 3, 4]));
Output:
[2, 3]
Approach:
Filter the first array by checking which elements also exist in the second array.
Let me know if you want even more coding problems, solutions for specific topics (recursion,
strings, objects), or detailed step-by-step walkthroughs!
DSA level from arrays any 5 most asked
Here are 5 most asked JavaScript DSA (Data Structures and Algorithms) interview problems
on arrays, along with the problem statement, approach, and code snippet for clarity. These are
commonly tested in interviews for evaluating your array manipulation and algorithmic skills.
1. Find the Second Largest Number in an Array
Problem:
Find the second largest unique number in an unsorted array.
Approach:
Initialize two variables to track the largest and second largest numbers.
Iterate once and update them accordingly.
Handle duplicates to ensure the second largest is unique.
function secondLargest(arr) {
let max = -Infinity, secondMax = -Infinity;
for (let num of arr) {
if (num > max) {
secondMax = max;
max = num;
} else if (num > secondMax && num !== max) {
secondMax = num;
}
}
return secondMax === -Infinity ? null : secondMax;
}
[Link](secondLargest([10, 5, 9, 10, 12, 12])); // 10
2. Rotate Array by K Steps
Problem:
Rotate the array to the right by k steps.
Approach:
Use a reversal algorithm:
1. Reverse the whole array.
2. Reverse the first k elements.
3. Reverse the remaining elements.
function rotateArray(arr, k) {
k = k % [Link];
reverse(arr, 0, [Link] - 1);
reverse(arr, 0, k - 1);
reverse(arr, k, [Link] - 1);
return arr;
}
function reverse(arr, start, end) {
while (start < end) {
[arr[start], arr[end]] = [arr[end], arr[start]];
start++; end--;
}
}
[Link](rotateArray([1, 2, 3, 4, 5, 6, 7], 3)); // [5, 6, 7, 1, 2, 3, 4]
3. Remove Duplicates from Sorted Array
Problem:
Given a sorted array, remove duplicates in-place and return the new length.
Approach:
Use two pointers: one to iterate, other to track unique elements.
Overwrite duplicates with next unique element.
function removeDuplicates(arr) {
if ([Link] === 0) return 0;
let i = 0;
for (let j = 1; j < [Link]; j++) {
if (arr[j] !== arr[i]) {
i++;
arr[i] = arr[j];
}
}
return i + 1; // new length
}
let nums = [1,1,2,2,3,4];
[Link](removeDuplicates(nums)); // 4
[Link]([Link](0, 4)); // [1, 2, 3, 4]
4. Move All Zeros to the End
Problem:
Move all zeros in the array to the end while maintaining the order of non-zero elements.
Approach:
Keep an index for non-zero elements.
Iterate, move non-zero elements forward.
Fill the remainder with zeros.
function moveZeros(arr) {
let insertPos = 0;
for (let num of arr) {
if (num !== 0) arr[insertPos++] = num;
}
while (insertPos < [Link]) {
arr[insertPos++] = 0;
}
return arr;
}
[Link](moveZeros([0, 1, 0, 3, 12])); // [1, 3, 12, 0, 0]
5. Find the Maximum Subarray Sum (Kadane’s Algorithm)
Problem:
Find the contiguous subarray with the maximum sum.
Approach:
Use Kadane’s algorithm:
Track current sum and reset to 0 if negative.
Track max sum found so far.
function maxSubArray(nums) {
let maxSum = nums[^12_0];
let currentSum = 0;
for (let num of nums) {
currentSum += num;
if (currentSum > maxSum) maxSum = currentSum;
if (currentSum < 0) currentSum = 0;
}
return maxSum;
}
[Link](maxSubArray([-2,1,-3,4,-1,2,1,-5,4])); // 6 (subarray [4,-1,2,1])
If you want, I can provide detailed step-by-step explanations or more problems on arrays or
other DSA topics. Just ask!
⁂
1. [Link]
2. [Link]
082ed55d
3. [Link]
4. [Link]
5. [Link]
4d17
6. [Link]