HTHyperTransformer AI

Study cards › JavaScript & TypeScript

JavaScript & TypeScriptInterview questions and answers

← Topics1 / 100
1 / 100 viewed
Question

What is an execution context in JavaScript?

Answer

An execution context is the environment where a piece of code runs. It holds the variable environment (declared vars/functions), the scope chain (which outer scopes are visible), and the value of 'this'. JS creates a new context for the global code, every function call, and every eval invocation.

Question

What is the call stack?

Answer

The call stack is a LIFO (last-in, first-out) stack of execution contexts. When you call a function, a frame is pushed; when it returns, the frame is popped. If frames pile up faster than they pop (e.g. unbounded recursion), you get a 'Maximum call stack exceeded' error.

Question

What is the event loop?

Answer

The event loop is the mechanism that takes callbacks from the task and microtask queues and pushes them onto the call stack — but only when the stack is empty. This is how single-threaded JavaScript handles async work without blocking: heavy callbacks wait their turn instead of running mid-stack.

Question

Microtasks vs macrotasks?

Answer

Microtasks are queued by promises, queueMicrotask, and MutationObserver. Macrotasks come from setTimeout, setInterval, I/O, and UI events. All pending microtasks drain fully BEFORE the next macrotask runs — which is why promise callbacks always run before a setTimeout(…, 0).

Question

What is a closure?

Answer

A closure is a function that retains access to variables from its outer (lexical) scope even after the outer function has returned. Example: function outer(){ let n=0; return ()=>++n }. Each call to outer() creates a fresh n, captured by the inner function — closures power private state, currying, and memoization.

Question

Practical uses of closures?

Answer

Data privacy (module pattern, hiding implementation), partial application and currying, memoization (caching results in an enclosed map), event handlers that need outer-scope state, and React hooks (useState's setter remembers the slot via closure).

Question

What is hoisting?

Answer

Hoisting is JS's behavior of treating declarations as if they were moved to the top of their scope. 'var' is hoisted and initialized to undefined; function declarations are hoisted with their body; 'let' and 'const' are hoisted but stay in the Temporal Dead Zone until their declaration line.

Question

var vs let vs const?

Answer

var is function-scoped and hoisted as undefined. let is block-scoped and reassignable. const is block-scoped and cannot be reassigned (but objects/arrays it points to can still mutate). Modern code should use const by default, let when you must reassign, and avoid var.

Question

What is the prototype chain?

Answer

Every JS object has an internal link to a prototype object (accessible via Object.getPrototypeOf). When you read a property, JS walks up this chain until it finds the property or hits null. That's how inheritance works in JS — methods you define on a class prototype are shared across instances.

Question

What is a Promise?

Answer

A Promise is an object representing the eventual result of an async operation. It has three states: pending, fulfilled (resolved), and rejected. You chain handlers with .then (success), .catch (failure), and .finally (always). Promises let you compose async code without nested callback hell.

Question

What does async/await do?

Answer

async marks a function so it always returns a promise. Inside, await pauses execution until a promise settles, then unwraps its value (or throws on rejection). It's syntactic sugar over .then chains — same mechanics, much more readable, especially when you have try/catch and loops.

Question

What is Promise.all?

Answer

Promise.all takes an array of promises and returns a new promise that resolves with an array of their values when ALL fulfill — but rejects as soon as ANY rejects. Use it to run independent async operations in parallel: const [user, posts] = await Promise.all([getUser(), getPosts()]).

Question

Promise.allSettled vs Promise.all?

Answer

allSettled waits for every promise regardless of outcome and returns an array of {status, value|reason} — perfect when you want partial results. all short-circuits: one rejection rejects the whole thing immediately, and you lose results from the ones that succeeded.

Question

What is Promise.race?

Answer

Promise.race returns a new promise that settles with the same outcome as the FIRST input promise to settle (fulfill or reject). Common use: race a fetch against a timeout — whichever wins decides the result. Promise.any is similar but only takes the first fulfillment, ignoring rejections.

Question

What is debouncing?

Answer

Debouncing delays a function until N milliseconds have passed since the LAST call. If the user keeps typing, the function never fires; once they pause, it runs. Perfect for search inputs, resize handlers, or anything where you only care about the final value after a burst of activity.

Question

What is throttling?

Answer

Throttling ensures a function runs at most once every N milliseconds, regardless of how often you call it. Good for scroll, mousemove, drag — you want steady updates, not the final value only. Throttle gives you regular feedback; debounce gives you a final-result-only callback.

Question

Debounce vs throttle?

Answer

Debounce waits for inactivity (fires once after the calls stop). Throttle enforces a steady max-rate (fires at intervals during the calls). Use debounce when only the final value matters (search query); use throttle when you want consistent updates while activity continues (scroll position).

Question

What does 'this' refer to in JavaScript?

Answer

It depends on how the function is called: method call (obj.fn() → this is obj), constructor (new Fn() → this is the new instance), arrow function (this is inherited from the enclosing scope), bound function (.bind sets it), and default (undefined in strict mode, global object otherwise).

Question

Arrow functions and 'this'?

Answer

Arrow functions don't have their own 'this'. They inherit it from the surrounding lexical scope at definition time. That's why arrow callbacks inside class methods 'just work' — they see the class instance's this without needing .bind. The flip side: you can't use them as constructors.

Question

What is event delegation?

Answer

Event delegation is attaching ONE listener to a parent element and using event.target to handle events from many children. It saves memory (one listener instead of hundreds), works for dynamically added children, and is the basis of how React's synthetic events used to work (now they're on the root).

Question

What is currying?

Answer

Currying transforms a function of N arguments into a chain of N functions each taking one argument. fn(a, b, c) becomes fn(a)(b)(c). It's mostly used for partial application — you can fix the first arg and pass the resulting unary function around, which composes nicely in functional pipelines.

Question

What is partial application?

Answer

Partial application is pre-filling some of a function's arguments to create a new function with fewer arguments. e.g. const double = (x) => multiply(2, x). Currying is one way to do partial application; you can also do it ad hoc with closures or Function.prototype.bind.

Question

What does Function.prototype.bind do?

Answer

bind returns a NEW function whose 'this' is fixed to a given value, optionally with some arguments pre-filled. Useful for callbacks where you need to preserve a specific context: button.addEventListener('click', this.handle.bind(this)). With arrow functions in classes, you rarely need bind anymore.

Question

Shallow vs deep copy?

Answer

Shallow copy duplicates only the top level — { ...obj } or Object.assign. Nested objects are still shared by reference. Deep copy recursively clones every level — use structuredClone (modern), or JSON.parse(JSON.stringify(x)) for simple data (loses Dates, Maps, functions).

Question

== vs === in JavaScript?

Answer

== performs type coercion before comparing — '5' == 5 is true. === checks both type and value — '5' === 5 is false. Always prefer === unless you have a specific reason to allow coercion; == has surprising rules that have caused countless bugs.

Question

What are JavaScript's falsy values?

Answer

false, 0, -0, 0n (BigInt zero), '' (empty string), null, undefined, and NaN. Everything else is truthy — including '0', 'false', [], and {}. This matters in if statements and short-circuit operators (||, &&), where empty strings and zero might be valid values.

Question

What does Array.prototype.map do?

Answer

map returns a NEW array where each element has been transformed by the callback you provide. It doesn't mutate the original. arr.map(x => x*2) doubles every number. The callback receives (element, index, array), and the result array is always the same length as the input.

Question

Map vs forEach?

Answer

map returns a new array of transformed values; forEach returns undefined and is purely for side effects. Use map when you need the result. Don't 'use map for side effects' — that's confusing and often a bug magnet. forEach signals 'I'm doing something, not building something'.

Question

What does Array.reduce do?

Answer

reduce aggregates an array into a single value by repeatedly applying a reducer: (acc, current) => newAcc. You provide an initial accumulator. Used for sums, counts, grouping into objects, building strings, flattening arrays — basically any 'fold' operation. Hard to read when overused; sometimes a loop is clearer.

Question

What is destructuring?

Answer

Destructuring extracts values from arrays or objects into named variables in one line. const { name, age } = user. const [first, ...rest] = arr. You can rename ({ a: x } = obj) and provide defaults ({ name = 'guest' } = obj). It makes function signatures and assignments much more readable.

Question

Spread vs rest?

Answer

Spread (...) expands an iterable in place: [...arr1, ...arr2] merges arrays; { ...obj1, ...obj2 } merges objects. Rest collects remaining items into a single parameter: function fn(first, ...others). Same syntax, opposite directions — spread unpacks, rest packs.

Question

What is optional chaining?

Answer

obj?.a?.b returns undefined if any link in the chain is null or undefined, instead of throwing 'Cannot read property of undefined'. Works with property access, function calls (fn?.()), and array access (arr?.[0]). Cleaner than long && chains for navigating possibly-missing data.

Question

What is nullish coalescing?

Answer

a ?? b returns b ONLY when a is null or undefined. Unlike ||, it doesn't treat 0, '', or false as 'fallback-worthy'. Example: count ?? 10 keeps 0 as 0; count || 10 would replace 0 with 10. Use ?? when zero or empty string are valid values you want to keep.

Question

What are Symbols?

Answer

Symbol is a primitive that creates unique values, even when given the same description: Symbol('id') !== Symbol('id'). They're used as collision-free object keys (libraries can add hidden properties safely) and to implement well-known protocols like Symbol.iterator for custom iterables.

Question

What is a generator function?

Answer

function* defines a generator — a function that can pause via yield and resume later. Calling it returns an iterator: each .next() runs until the next yield and returns { value, done }. Useful for lazy sequences (infinite ranges), state machines, and as the basis of async iterators.

Question

What are WeakMap and WeakSet?

Answer

WeakMap/WeakSet hold WEAK references to their key objects — meaning if no other reference exists, the GC can collect them. They're perfect for attaching metadata to objects without preventing cleanup (e.g. caches keyed by DOM nodes). Keys must be objects, and you can't iterate them.

Question

What is a Proxy?

Answer

Proxy wraps an object and lets you intercept fundamental operations (get, set, has, deleteProperty…) via a handler. It powers reactivity systems (Vue 3 uses Proxy), validation layers, logging wrappers, and any 'observe what happens to this object' use case. Very powerful, slightly slower than direct access.

Question

What's the modern JS module system?

Answer

ES Modules (import/export) — static, asynchronous, tree-shakeable, the standard everywhere from browsers to Node 22+. CommonJS (require, module.exports) is Node's legacy system, still widely used. New code should default to ESM; only fall back to CJS for compatibility with old tooling.

Question

What is event.preventDefault?

Answer

preventDefault stops the browser's default action for that event — e.g. preventing form submission, link navigation, or context menus. It does NOT stop the event from bubbling up. Use it for custom form handling, custom drag-and-drop, or any time you want to intercept native behavior.

Question

What is event.stopPropagation?

Answer

stopPropagation halts the event from bubbling up to parent elements (or from capturing down). Use it when a child shouldn't trigger a parent's handler — but be careful, it can break event delegation patterns elsewhere. Often a sign that the handlers should be restructured.

Question

What does JSON.stringify's replacer do?

Answer

The optional second argument to JSON.stringify is either a function (called for each key-value pair, return undefined to skip) or an array of keys to keep. Useful for filtering out sensitive fields like passwords or for serializing custom types that JSON doesn't natively support.

Question

What does Object.freeze do?

Answer

Object.freeze makes an object's top-level properties immutable — assignments silently fail (or throw in strict mode), and you can't add or remove keys. It's SHALLOW: nested objects are still mutable. For deep immutability you need to recurse, or use a library like Immer.

Question

What is the Temporal Dead Zone?

Answer

The TDZ is the period from entering a scope to the line where a let/const variable is declared. Accessing the variable during this window throws ReferenceError, even though the declaration has been hoisted. It's why you can use a var before declaring it, but not a let.

Question

How does garbage collection work in JS?

Answer

Modern engines use mark-and-sweep: starting from roots (globals, current stack), they mark every reachable object, then sweep away the unmarked ones. You don't manage memory directly. Leaks happen when references stay alive accidentally — globals, forgotten timers, detached DOM nodes held by closures.

Question

What causes memory leaks in JS apps?

Answer

Common culprits: global variables you forgot to clean up, timers (setInterval) you never clear, event listeners on detached DOM, closures holding large data that's no longer needed, and caches that grow unboundedly. Chrome DevTools' Memory panel and heap snapshots help track them down.

Question

What is a TypeScript interface?

Answer

An interface is a named shape describing the structure of an object: interface User { id: string; name: string }. Interfaces support declaration merging (you can re-open them) and 'extends' for composition. They're a compile-time concept — they don't exist at runtime.

Question

Interface vs type alias?

Answer

Both describe shapes. Interfaces support declaration merging and feel ergonomic for object types and class contracts. Type aliases can also describe unions, intersections, tuples, and primitives — anything. For plain object shapes the difference is mostly stylistic; pick a convention and stick to it.

Question

What is a generic in TypeScript?

Answer

A generic is a type variable that lets you write reusable, type-safe code: function identity<T>(x: T): T { return x }. The caller's type flows through automatically — identity('hi') returns string. Generics power containers (Array<T>), promises (Promise<T>), and most utility types.

Question

What is a utility type?

Answer

Built-in generics that transform existing types: Partial<T> makes all fields optional, Required<T> the opposite, Pick<T, K> selects keys, Omit<T, K> removes them, Readonly<T> freezes them. They're the LEGO bricks of TypeScript — combine them instead of re-declaring shapes.

Question

What is a mapped type?

Answer

A type that creates a new type by iterating over the keys of another: { [K in keyof T]: SomeTransform<T[K]> }. It's how Partial, Required, Readonly, and Pick are all implemented. Mapped types let you keep many types in sync — change the source, all derived shapes update.

Question

What is a conditional type?

Answer

T extends U ? X : Y — picks one of two types based on whether T is assignable to U. It's the basis for ReturnType, Exclude, Extract, and many advanced utilities. Combined with 'infer', it can pull pieces out of types (like extracting the parameters of a function).

Question

What are TS enums?

Answer

Enums are sets of named constants — numeric (default, with auto-increment) or string. They generate runtime code (an object). Many teams prefer 'as const' object literals instead: { RED: 'red', BLUE: 'blue' } as const — better tree-shaking and stricter literal inference.

Question

What is a discriminated union?

Answer

A union where each member shares a literal 'tag' field (e.g. type: 'success' | 'error'). Inside a switch on that tag, TypeScript narrows the type automatically: in the 'success' branch it knows the rest of the fields. Backbone of typed reducers, API responses, and state machines.

Question

What is type narrowing?

Answer

Narrowing is TS refining a variable's type inside a block based on a check: typeof, instanceof, 'in' operator, equality checks, and custom type guards all narrow. Inside if (typeof x === 'string') { … } the compiler knows x is string and gives you string methods.

Question

What is a type guard?

Answer

A function returning 'x is T' (a type predicate) that tells the compiler to narrow the type inside if/else branches. e.g. function isUser(x: unknown): x is User { … }. Use them whenever you need to safely check shapes from untrusted sources like API responses or localStorage.

Question

What's the difference between unknown and any?

Answer

unknown is the safe top type — you must narrow it (typeof, instanceof, type guard) before you can use it. any disables type checking entirely. Treat 'any' as a hole in your type safety: useful as an escape hatch, dangerous as a default. Prefer 'unknown' when you genuinely don't know the type.

Question

What is 'never'?

Answer

never is the type with NO possible values. It's the return type of functions that throw or loop forever, the type of the impossible branch, and the basis of exhaustive checks. If a variable ends up never-typed, you've handled every case — the compiler will yell if you miss one.

Question

How do you type a React functional component?

Answer

function Foo(props: FooProps) { return <div /> } — explicit return type usually inferred, no need for React.FC unless you want implicit children. For arrow components, just type the props: const Foo: React.FC<FooProps> = (props) => …. Modern convention leans toward function declarations.

Question

How do you type useState?

Answer

Usually just rely on inference: useState(0) is useState<number>. For null/undefined unions or arrays starting empty, supply the generic explicitly: useState<User | null>(null), useState<string[]>([]). Otherwise TS infers based on the initial value and may guess too narrowly.

Question

How do you type useRef for a DOM element?

Answer

useRef<HTMLDivElement>(null) — then ref.current is HTMLDivElement | null. You attach with <div ref={ref} />. Always check for null before using ref.current — the ref isn't set until after mount, and TypeScript enforces this with the union type.

Question

How do you type event handlers?

Answer

Use React's synthetic event generics, parameterized by the element. React.ChangeEvent<HTMLInputElement>, React.MouseEvent<HTMLButtonElement>, React.FormEvent<HTMLFormElement>. Or let inference do the work by writing the handler inline in JSX: <input onChange={(e) => …}> — e is typed automatically.

Question

How do you type API responses?

Answer

Define an interface or type for each payload, then assert/validate when parsing: const data: User = await res.json(). For real safety, validate at runtime with a schema library like Zod or io-ts — the schema also produces the TS type, so they never drift apart.

Question

What is Zod?

Answer

Zod is a TypeScript-first schema-validation library. You define schemas (z.object({ id: z.string(), age: z.number() })) and get both runtime validation (z.parse) AND a derived TS type (z.infer<typeof Schema>). One source of truth for shape AND validation — eliminates a whole class of bugs.

Question

What does TypeScript's 'strict' mode enable?

Answer

strict turns on all strict family flags: strictNullChecks (null/undefined are separate types you must handle), noImplicitAny (every variable must be typed), strictFunctionTypes, strictBindCallApply, and more. Always enable strict in new projects — it catches enormous categories of bugs.

Question

What does 'as const' do?

Answer

It tells TS to treat a literal as the narrowest possible immutable type. 'red' becomes the type 'red' (not string), [1,2,3] becomes readonly [1,2,3]. Crucial for tuples, lookup objects, and any case where you want literal-precise types instead of widened ones.

Question

Difference between 'interface I {}' and 'type T = {}'?

Answer

Both describe object shapes and behave nearly identically. Interfaces support declaration merging (multiple declarations combine) and extends syntax. Type aliases can also do unions, primitives, tuples — anything in the type space. For pure object types, pick one and be consistent in your codebase.

Question

Why prefer composition of types over inheritance?

Answer

Composing with intersections (A & B) and utility types gives you flexibility without coupling. Deep extension chains become rigid and hard to refactor. With composition, each piece is reusable and changes are localized. It's the same logic as 'composition over inheritance' in OOP, applied to types.

Question

What is the 'satisfies' operator?

Answer

satisfies checks that a value matches a type WITHOUT widening its inferred type. Example: const config = { mode: 'dev' } satisfies Config — config.mode is still 'dev' (literal), but TS verifies it fits Config. Best of both: validation + precise literal types preserved.

Question

What is 'keyof'?

Answer

keyof produces a union of an object type's property keys: keyof { a: 1; b: 2 } is 'a' | 'b'. It's the bridge between values and types — fundamental to writing functions that take a known key of some object, like a typed lodash.get.

Question

What is typeof in TypeScript types?

Answer

Inside the type space, typeof reads the type of a value. const user = { id: 1, name: 'a' }; type User = typeof user. This is how you derive types from data — say, when you have a config object and want a type that matches it automatically.

Question

What is an indexed access type?

Answer

T[K] gets the type of property K from type T. User['id'] gives the type of id. You can index by unions: User['id' | 'name'] gives id-or-name's type. Indexed access is critical for utility types and for keeping derived types in sync with their sources.

Question

Pick vs Omit?

Answer

Pick<T, K> keeps only the keys in K from T. Omit<T, K> removes those keys. Both produce new object types from existing ones, so changing the source automatically propagates. Use Omit to exclude server-only fields, Pick to select a small public shape.

Question

What does ReturnType<T> do?

Answer

ReturnType<T> extracts the return type from a function type T. Pairs with Parameters<T>, which returns a tuple of the argument types. These are how you derive types from existing functions (e.g. inferring a hook's return shape) so you don't have to redeclare them by hand.

Question

What is module resolution in TS?

Answer

It's how TS turns import 'foo' into an actual file. 'node' (legacy default) walks node_modules. 'bundler' (modern bundlers) is more permissive. 'nodenext' enforces ESM rules strictly. Pick the mode matching your build tool, otherwise imports will resolve in editor but fail at runtime.

Question

What is declaration merging?

Answer

When TS sees multiple declarations with the same name (interfaces, namespaces, modules), it merges them into one. This is how libraries augment the DOM or how you can add fields to Express's Request type. It's powerful but should be used sparingly — surprises future readers.

Question

Class vs interface in TS?

Answer

A class generates runtime code (a constructor function) AND a type. An interface is purely compile-time — no runtime footprint at all. Use a class when you need actual instances with methods; use an interface for type-only contracts that any object can satisfy.

Question

What is 'never' used for in exhaustive checks?

Answer

In a switch over a discriminated union, the default case assigns the variable to a never-typed helper: const _exhaustive: never = x. If you ever add a new variant and forget to handle it, the compiler errors because the new variant isn't never. Forces you to update every switch.

Question

What are template literal types?

Answer

String types built from templates: type Greeting = `hello ${string}`. They can combine other unions: `${'on' | 'off'}-${'left' | 'right'}` produces all four combinations. Used for typed event names, CSS routes, query strings, and any string with structure.

Question

unknown vs object?

Answer

object excludes primitives but allows ANY non-primitive (arrays, functions, plain objects). unknown allows everything, including primitives, and requires narrowing before use. unknown is safer for genuinely-unknown values; object is useful when you know it's at least a reference type.

Question

How do you type a higher-order function?

Answer

Use generics to preserve the inner function's type: function wrap<T extends (...args: any[]) => any>(fn: T): T. Now whatever you pass in, the returned wrapped function has the same signature. Combined with Parameters/ReturnType, you can model adapters, decorators, and middleware faithfully.

Question

What does the !! operator do?

Answer

Double-NOT coerces any value to its boolean equivalent — !!value is true if value is truthy, false otherwise. It's a concise way to convert to boolean when comparing or returning a flag. Equivalent to Boolean(value), but shorter (and slightly less readable for newcomers).

Question

What does 'delete' do on an object property?

Answer

delete obj.prop removes the property entirely from the object — it's no longer in Object.keys, in operator, or for-in. Returns true unless the property is non-configurable. Performance note: delete can deoptimize hot objects in V8 — for hot paths, prefer setting to undefined.

Question

How do you check if a value is an array?

Answer

Array.isArray(value). Don't use typeof (returns 'object' for arrays) or instanceof Array (fails across iframes/realms). isArray is the correct and reliable check.

Question

Object.keys vs for…in?

Answer

Object.keys returns OWN enumerable string keys as an array — safe for objects. for…in iterates own AND inherited enumerable string keys, which can pull in stuff you didn't expect (especially with prototype pollution). For plain dict-like objects, prefer Object.keys + forEach or for…of.

Question

What's the iterator protocol?

Answer

An iterator is an object with a .next() method returning { value, done }. Done becomes true when exhausted. It's the standard way to lazily produce a sequence — enables for…of, spread, destructuring. You usually consume iterators rather than write them by hand.

Question

What's the iterable protocol?

Answer

An iterable is any object that implements [Symbol.iterator]() returning an iterator. Arrays, Maps, Sets, and strings are iterables out of the box. Implement Symbol.iterator on your own class and you get for…of and spread support for free.

Question

Map vs Object?

Answer

Map lets keys be ANY type (objects, functions), preserves insertion order, has .size, and is optimized for frequent add/remove. Object keys are strings/symbols only, and inherited members can collide with your data. Use Map when keys aren't strings or when you need to add/delete frequently.

Question

Set vs Array for uniqueness?

Answer

Set has O(1) add and has() — great for membership checks or de-duplicating. Array's includes() is O(n). When you only need to know if something is in a collection, reach for Set. Convert to an array with [...set] when you need indexing or order.

Question

What is structuredClone?

Answer

structuredClone is a built-in deep clone supporting most types: plain objects, arrays, Map, Set, Date, ArrayBuffer, even Blob. It replaces the awkward JSON.parse(JSON.stringify(x)) trick, which loses Dates, Maps, functions, and undefined values. Available in browsers and modern Node.

Question

What does Object.freeze NOT do?

Answer

It doesn't deep-freeze. Object.freeze({ a: { b: 1 } }) freezes the outer object, but obj.a is still mutable. For true immutability you must recursively freeze, or use a library like Immer that gives you immutable updates without manual recursion.

Question

What is short-circuit evaluation?

Answer

Logical operators stop evaluating once the result is determined. a && b only evaluates b if a is truthy. a || b only evaluates b if a is falsy. Used for safe access (user && user.name) and defaults (name || 'guest'). Be careful with falsy-but-valid values like 0 — use ?? for those.

Question

Tagged template literals — what are they?

Answer

A function called with template literal pieces: tag`hello ${name}`. The function receives the static strings and the interpolated values separately. Used by libraries like styled-components (for CSS), sql-template-strings (safe SQL), and graphql-tag (parsing queries at build time).

Question

What is BigInt?

Answer

BigInt is a primitive for arbitrarily large integers, written with the n suffix: 9007199254740993n. Use it when numbers exceed Number.MAX_SAFE_INTEGER (about 9 quadrillion). You can't mix BigInt and Number freely — you must convert explicitly to avoid silent precision loss.

Question

When would you implement Symbol.iterator?

Answer

When you want your custom class or object to work with for…of, spread (...), Array.from, and destructuring. Add a [Symbol.iterator]() method that returns an iterator. Useful for custom collections, paginated wrappers, infinite sequences, and tree traversals.

Question

What is ArrayBuffer?

Answer

ArrayBuffer is a fixed-length binary buffer — raw bytes. You access it through typed array views (Uint8Array, Float32Array, etc.) or DataView. Used for binary protocols, file parsing, WebGL textures, audio buffers, and anywhere you need byte-level performance.

Question

What is the Reflect API?

Answer

Reflect is a namespace mirroring object operations: Reflect.get, Reflect.set, Reflect.has, Reflect.construct. It's designed to pair with Proxy handlers (which have the same method names). Reflect.has(obj, 'x') is the functional equivalent of 'x' in obj.

Question

How does Object.is differ from ===?

Answer

Object.is treats NaN as equal to NaN, and distinguishes +0 from -0. Everywhere else, it behaves like ===. React uses Object.is for its setState bailout check. For 99% of code, === is what you want; Object.is matters for low-level numeric work.

Question

What is a polyfill?

Answer

A polyfill is code that implements a feature in environments that lack it — like a fetch polyfill for old browsers, or core-js providing Promise/Array.includes in IE. Modern toolchains (Babel + targets) inject polyfills only for the platforms you support.

Question

What is transpilation?

Answer

Transpilation converts code from one form to another at build time — TypeScript → JavaScript, modern JS → older JS for browser support, JSX → React.createElement. Tools: Babel, esbuild, swc, tsc. Different from compilation (machine code), but the word is used loosely for both.

Question

What is ESM/CJS interop?

Answer

Node supports both ES Modules (import/export) and CommonJS (require/module.exports), but mixing them has rules. ESM can default-import CJS, but require()-ing ESM is async and must use dynamic import(). When using TS or bundlers, pick a target (nodenext, bundler) that matches your runtime.

Practise JavaScript & TypeScript in the app
Track your progress, flag tricky cards and write your own answers.

Open in the app

More topics: React & Frontend Backend Engineering Databases System Design AI & Agentic AI DevOps & Cloud Security Testing DSA Coding Problems (Python)