Information Technology
JavaScript Interview Questions & Answers
The native language of the web for client-side interactivity.
ArrayBuffer, TypedArrays & Binary Data
All 10 questionsAn ArrayBuffer is a fixed-length, raw binary data buffer in memory. It has no way to read or write data directly — you need a "view" like a TypedArray or DataView layered on top of…
A TypedArray (like Int32Array, Uint8Array, Float64Array) is a view that lets you read and write numeric values of a specific type directly into an ArrayBuffer's memory, without cop…
Int8Array uses 1 byte per element, Int16Array uses 2, Float64Array uses 8. JS also has Uint8Array, Uint16Array, Int32Array, Uint32Array, Float32Array, and BigInt64Array/BigUint64Ar…
DataView lets you read and write multiple numeric types at arbitrary byte offsets within an ArrayBuffer, and lets you control endianness (byte order). Use it when parsing binary fo…
Use Array.from() or the spread operator; both iterate the TypedArray and produce a standard Array with full array method support (map, filter, etc.), which TypedArrays only partial…
Arrays & Array Methods
All 10 questionsmap() returns a new array built from the return value of the callback for each element; forEach() only runs the callback for its side effects and always returns undefined.
- How does filter() work? Beginner
filter() creates a new array containing only the elements for which the callback returns a truthy value; it doesn't mutate the original array.
reduce() runs a callback that accumulates a single value across the array; its callback arguments are (accumulator, currentValue, index, array), plus an optional initial value for…
- What's the difference between splice() and slice()? Intermediate
splice() mutates the original array by adding or removing elements in place and returns the removed elements; slice() returns a shallow copy of a portion of the array and leaves th…
- How do find() and findIndex() differ from filter()? Intermediate
find() returns the first matching element (or undefined); findIndex() returns its index (or -1); filter() returns ALL matching elements as a new array, even if there's only one mat…
Async Iterators & Streams
All 10 questions- What is an async iterator? Beginner
An async iterator is an object with a next() method that returns a Promise resolving to {value, done}, letting you iterate over values that arrive asynchronously over time, like ch…
Use a for-await-of loop, which automatically awaits each next() call and unwraps the resolved value, pausing the loop until each item is ready.
- How do you write an async generator function? Intermediate
Combine function* with async: async function*. Each yield can await a value first, and calling the generator returns an async iterable you can consume with for-await-of.
- What is the ReadableStream API used for? Intermediate
ReadableStream represents a source of data (like a network response body) that can be read incrementally in chunks, rather than waiting for the entire payload to load into memory a…
- What does return() do on an async iterator? Intermediate
return() is called automatically when a for-await-of loop exits early (via break, return, or an exception), giving the iterator a chance to run cleanup code such as closing a file…
Browser Storage & Web APIs
All 10 questionslocalStorage persists data with no expiration until explicitly cleared, and is shared across all tabs/windows for the same origin. sessionStorage only lasts for the lifetime of a s…
localStorage's API only accepts and returns strings. To store objects or arrays, serialize them with JSON.stringify() before saving and JSON.parse() them back out after reading.
- What is the storage event and when does it fire? Intermediate
The storage event fires on window in OTHER tabs/windows of the same origin whenever localStorage changes — it never fires in the tab that made the change itself. It's useful for ke…
localStorage is typically capped around 5–10MB per origin and is synchronous, which can block the main thread on large reads/writes. IndexedDB supports much larger amounts of data…
IndexedDB is a low-level, transactional NoSQL database built into the browser. It supports structured objects, indexes for fast querying by property, and versioned schema upgrades…
Classes & Class Syntax
All 10 questionsA class is syntactic sugar over JavaScript's existing prototype-based inheritance. It doesn't add a new object model — under the hood, methods still live on the prototype object, j…
constructor() runs automatically when you call new ClassName(...), initializing instance properties. A class can have at most one constructor.
extends sets up prototype-based inheritance between classes, and super() inside the subclass's constructor calls the parent class's constructor to initialize inherited state before…
Class fields let you declare and initialize instance properties directly in the class body, outside the constructor, which runs before the constructor body executes. They reduce bo…
- What does the # syntax mean for class members? Intermediate
The # prefix marks a truly private field or method, accessible only from inside the class body itself — not even subclasses or external code can read or call it, and accessing it f…
Date, Time & Internationalization (Intl API)
All 10 questionsnew Date() with no arguments creates a Date object set to the current date and time, based on the system clock, represented internally as milliseconds since the Unix epoch (Jan 1,…
Date.parse() (and new Date(string)) behavior for non-ISO formats is implementation-defined, so the same string can parse differently across browsers. Only the ISO 8601 format (e.g.…
Intl.DateTimeFormat lets you format dates according to locale conventions and customizable options (weekday, month style, etc.), without needing an external date library for basic…
Subtracting two Date objects (or calling getTime() on each) yields the difference in milliseconds; divide by the number of milliseconds in a day (1000*60*60*24) to get whole days.
Intl.NumberFormat handles locale-aware digit grouping, decimal separators, and currency symbols automatically, avoiding manual and error-prone string manipulation.
Debugging, Testing & Tooling
All 10 questionsInsert a debugger statement in your code, or click in the gutter of the Sources panel to set a breakpoint. When execution reaches that line, DevTools pauses so you can inspect vari…
- What is console.table() useful for? Beginner
console.table() renders an array of objects as a formatted table in the console, making it much easier to scan rows and columns than reading nested console.log() output.
A unit test verifies that a single, isolated piece of code (usually a function) behaves correctly for given inputs. A good unit test is fast, deterministic, tests one behavior at a…
jest.fn() and jest.mock() replace real dependencies (API calls, modules, timers) with controllable fake implementations, so tests can verify how your code calls those dependencies…
Code coverage measures which lines/branches of code ran during tests, expressed as a percentage. High coverage only proves code was *executed*, not that its behavior was *correctly…
Design Patterns in JavaScript
All 10 questionsThe Module pattern uses a function closure (or an ES module) to keep internal variables private and expose only a controlled public API, preventing external code from directly mani…
Singleton ensures only one instance of an object exists across the whole application, typically by exporting a single already-created instance from a module — since ES modules are…
Maintain a list of subscriber callback functions; provide a subscribe() method to add them and a notify() (or emit()) method that loops through and calls each one when an event occ…
- What is the Factory pattern, and how does it differ from calling a class constructor directly? Intermediate
A factory is a function that encapsulates the logic for deciding which class/object to instantiate and how, hiding that complexity from the caller — useful when construction logic…
By wrapping a function or object with another function that adds behavior before/after calling the original, while preserving its original interface — often done with higher-order…
Destructuring, Spread & Rest
All 10 questionsArray destructuring pulls values out by position into named variables using square-bracket syntax on the left side of an assignment.
Object destructuring pulls named properties into variables using curly-brace syntax; the variable names must match the property names unless you rename them.
Spread expands an iterable's elements in place, commonly used to copy an array or merge multiple arrays into a new one without mutating the originals.
Add = defaultValue after the variable name; the default is used only when the corresponding value is undefined (not null or any other falsy value).
- How does the rest parameter differ from the spread operator, even though they use the same '...' syntax? Intermediate
Rest COLLECTS multiple arguments/elements INTO an array (used in function parameters or destructuring patterns); spread EXPANDS an array/iterable OUT into individual elements (used…
DOM & Events
All 10 questions- What is event bubbling? Beginner
Event bubbling means an event fired on an element propagates upward through its ancestors in the DOM tree, triggering any matching event listeners on parents after the target eleme…
- What does event.preventDefault() do? Beginner
It cancels the browser's default action for that event — like following a link's href, submitting a form, or checking a checkbox — while still allowing the event to bubble unless y…
Use document.querySelector() (or similar) to find the element, then set its textContent property to update the text safely without interpreting it as HTML.
Event delegation attaches a single listener to a common ancestor and uses event.target to determine which child triggered it, instead of attaching a separate listener to every chil…
event.target is the actual element that originated the event (e.g., the specific clicked); event.currentTarget is the element the listener is currently attached to and executing on…
Error Handling
All 10 questions- How does a try/catch block work? Beginner
Code inside try runs normally; if it throws an error, execution immediately jumps to the catch block instead of crashing the whole program, letting you handle the error gracefully.
- What does the finally block do? Beginner
finally always runs after try/catch, whether or not an error was thrown or caught, and even if the try block returns early — making it ideal for cleanup code that must always execu…
new Error('message') creates an object with a stack trace and standard .message/.name properties, which DevTools and error-tracking tools understand. Throwing a plain string or obj…
- How do you create a custom error class? Intermediate
Extend the built-in Error class, call super(message) in the constructor to set up the message and stack trace, then add any extra properties specific to your error type.
With .then()/.catch() chains, attach a .catch() at the end to handle rejections from any prior step. With async/await, wrap the awaited calls in a try/catch block — both approaches…
ES Modules
All 10 questionsA module can have any number of named exports (imported with matching names in curly braces), but at most one default export (imported with any name you choose, no braces required)…
Use import * as name from '...' to collect all of a module's named exports into a single object, accessed as name.exportedThing.
ES Modules use static import/export syntax analyzed at parse time (enabling tree-shaking), run in strict mode by default, and support top-level await. CommonJS's require() is dynam…
Tree-shaking is a bundler optimization that removes unused exports from the final bundle. It relies on ES Modules' static, analyzable import/export structure — bundlers can determi…
import() is a function-like expression that returns a Promise resolving to the module, and can be called anywhere at runtime — including conditionally — unlike static import which…
Event Loop & Concurrency
All 10 questionsYes, JavaScript runs on a single main thread, executing one operation at a time. It achieves the appearance of doing multiple things at once through asynchronous callbacks, Promise…
- What is the call stack? Beginner
The call stack tracks which function is currently executing and what called it, growing with each function call and shrinking as functions return — a 'stack overflow' happens when…
Promise callbacks (.then, async/await continuations) go into the microtask queue, which is fully drained after every single macrotask completes. setTimeout, setInterval, and I/O ca…
- How does the event loop decide what to run next? Intermediate
After each synchronous script (or a single macrotask) finishes, the event loop first fully drains the microtask queue, then renders any pending UI updates, then picks up the next m…
Since JS runs on one thread shared with rendering and input handling, any synchronous code that takes a long time to finish prevents the browser from processing clicks, repainting…
Functional Programming
All 10 questions- What is a pure function? Beginner
A pure function always returns the same output for the same input and produces no observable side effects (no mutating external state, no I/O), which makes it predictable, testable…
Immutability means not modifying data after it's created — instead, you produce new data structures with the desired changes. This avoids bugs from shared mutable state and makes i…
- What is a higher-order function? Beginner
A higher-order function either accepts one or more functions as arguments, returns a function, or both — array methods like map, filter, and reduce are common built-in examples.
Composition combines multiple small functions into one, where the output of each becomes the input to the next — typically implemented with a compose() or pipe() helper that reduce…
- What is currying and what problem does it solve? Intermediate
Currying transforms a function taking multiple arguments into a sequence of functions each taking a single argument, allowing you to partially apply some arguments early and reuse…
Iterators & Generators
All 10 questionsAn object is iterable if it implements the Symbol.iterator method, which returns an iterator object with a next() method. This is what powers for...of loops, spread syntax, and des…
Add an asterisk after 'function' to make it a generator; calling it doesn't run the body immediately but returns an iterator, and each yield pauses execution, resuming from that po…
Yes — a generator function's return value is itself an iterable (it implements Symbol.iterator returning itself), so for...of can consume it directly, automatically calling next()…
When a generator hits yield, execution pauses immediately and control returns to the caller with an object { value, done: false } — the generator's internal state (including local…
yield* fully delegates iteration to another iterable (including another generator), yielding each of its values in turn as if they were yielded directly by the outer generator — us…
JSON & Data Serialization
All 10 questionsJSON.stringify() serializes a JavaScript value into a JSON-formatted string, converting objects, arrays, strings, numbers, booleans, and null into their JSON text representation.
JSON.parse() parses a JSON-formatted string and returns the corresponding JavaScript value (object, array, string, number, etc.); it throws a SyntaxError if the string isn't valid…
Functions, undefined, and Symbols are omitted entirely from objects (or converted to null inside arrays); Dates are converted to ISO strings; NaN and Infinity become null — meaning…
- How do you use the replacer parameter of JSON.stringify() to control what gets serialized? Intermediate
The second argument can be an array of allowed key names, or a function called for every key/value pair that returns the value to use (or undefined to omit that key) — giving fine-…
- How does the reviver function in JSON.parse() work? Intermediate
The optional second argument to JSON.parse() is called for every key/value pair as the object is being built, bottom-up, and its return value replaces the original — letting you tr…
Map, Set, WeakMap & WeakSet
All 10 questionsA Map allows keys of ANY type (objects, functions, even NaN), preserves insertion order reliably, has a .size property, and doesn't come with inherited prototype properties that co…
- How does a Set differ from an array? Beginner
A Set only stores unique values — adding a duplicate is a no-op — and lookups with .has() are much faster (O(1) on average) than an array's .includes() (O(n)).
A Map is directly iterable with for...of, yielding [key, value] pairs by default, matching the order items were inserted; you can also use .keys(), .values(), or .entries() explici…
A WeakMap holds its keys weakly, meaning entries don't prevent the garbage collector from reclaiming a key object once there are no other references to it — this makes iteration (o…
- When would you choose a WeakSet over a Set? Intermediate
WeakSet holds object references weakly (like WeakMap), so it's useful for tracking membership (e.g. 'has this object already been processed?') without creating a memory leak by kee…
Memory Management & Garbage Collection
All 10 questionsJavaScript uses automatic garbage collection: an object's memory is reclaimed once it becomes unreachable — meaning no live reference chain from the global scope, active call stack…
A memory leak happens when objects remain reachable (and therefore never collected) even though the program logically no longer needs them — typically because a lingering reference…
If an event listener's callback closes over a large object or a whole DOM subtree, and the listener is never removed even after the associated element is removed from the page, tha…
A closure retains access to its entire enclosing scope, not just the specific variables it uses — so if a large object is declared in the same scope as a function that's kept alive…
- What is the difference between the generational garbage collection strategy's 'young' and 'old' generations? Intermediate
Most objects die young (short-lived, like temporary variables in a function), so V8's generational GC checks a small 'young generation' heap frequently and cheaply; objects that su…
Networking: Fetch, XHR, WebSockets & CORS
All 10 questionsfetch(url) returns a Promise that resolves to a Response object once headers arrive; you then call .json() (or .text(), etc.) — itself also returning a Promise — to read and parse…
Pass an options object as the second argument specifying method: 'POST', a Content-Type header, and a JSON.stringify()'d body — fetch doesn't set the Content-Type header automatica…
fetch() only rejects for network-level failures (DNS errors, no connectivity, CORS block) — any response the server actually sends, including error status codes, resolves successfu…
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that blocks a web page from reading responses from a different origin (domain/port/protocol) unless the server…
- How do you cancel an in-flight fetch() request? Intermediate
Create an AbortController, pass its .signal to fetch()'s options, and call controller.abort() to cancel the request — fetch's Promise then rejects with an AbortError, which you can…
Numbers, Math & BigInt
All 10 questionsJavaScript numbers use the IEEE 754 double-precision floating-point format, which can't represent most decimal fractions exactly in binary — this is a property of floating-point ma…
Number.isInteger(x) returns true only if x is a number with no fractional part (e.g. 5, but not 5.5 or '5'); typeof would just say 'number' for both integers and decimals, without…
Math.round(), Math.floor(), and Math.ceil() handle rounding; Math.max()/Math.min() find extremes among arguments; Math.random() generates a pseudo-random float between 0 (inclusive…
It's 2^53 - 1 (9007199254740991), the largest integer JavaScript's double-precision Number type can represent without losing precision. Beyond it, integers can silently round to a…
- What is BigInt and how do you create one? Intermediate
BigInt is a separate numeric type that can represent arbitrarily large integers exactly, with no upper precision limit like regular Numbers. Create one by appending 'n' to an integ…