40 questions / 10 random questions
Random questions, instant feedback, and review for missed questions.
View recommended Practical JavaScript & TypeScript resources →
An API ID may be a string or a number and the types must remain distinct. Which JavaScript operator is appropriate?
Answer: The strict equality operator ===
Strict equality compares type and value without coercion, so string "1" and number 1 remain distinct. Normalizing types at boundaries is also useful.
Zero is a valid configuration value, and a default should apply only for null or undefined. Which operator is appropriate?
Answer: value ?? defaultValue
Nullish coalescing uses the right operand only when the left is null or undefined. Logical OR also replaces zero, empty string, and false.
Asynchronous callbacks created in a loop must retain each iteration's index. Which declaration is appropriate?
Answer: Declare the for-loop index with let
A let binding is created for each loop iteration, so each closure retains that iteration's value. var shares a single function-scoped binding.
A method uses setTimeout and needs to preserve the method call's this value. Which approach is appropriate?
Answer: Pass an arrow function to setTimeout
Arrow functions do not define their own this and lexically capture the surrounding method context. A normal function's this depends on how it is called.
Synchronous code, Promise.then, and setTimeout(fn, 0) are scheduled together. What is the usual execution order?
Answer: Synchronous code, Promise microtask, then timer task
After the current call stack completes, the microtask queue is drained before moving to the next task such as a timer. Long microtask chains can delay rendering and tasks.
Three independent APIs should run concurrently, and all outcomes must be inspected even if one fails. Which method is appropriate?
Answer: Promise.allSettled()
allSettled returns every fulfilled or rejected outcome. Promise.all is preferable when the aggregate operation requires every input to succeed.
When search input changes, the previous fetch should be canceled so only the latest result is shown. Which approach is appropriate?
Answer: Pass an AbortController signal to fetch and abort it on the next input
Passing an AbortSignal to fetch cancels obsolete network and follow-up work. Handle AbortError separately from failures and optionally track the latest request identity.
A fetch call should treat HTTP 404 as an application error. Which handling is appropriate?
Answer: Check Response.ok or status and explicitly handle unexpected status codes as errors
Fetch rejects on network failures, while HTTP responses such as 404 and 500 normally fulfill. Evaluate status according to the API contract.
Which retry implementation is appropriate for transient errors in an async function?
Answer: Limit eligible errors and attempts, add backoff and jitter, and throw the final failure
Retries should be limited to transient failures and safe operations with bounded attempts and duration. Preserve the final error for the caller.
A large response body should be processed incrementally to limit memory usage. Which approach is appropriate?
Answer: Read chunks from a ReadableStream and process them incrementally with backpressure
Streaming processes data without retaining the whole payload in memory. Handle decoder boundaries, errors, cancellation, and producer-consumer speed differences.
A nested state object needs an independent copy. Why is object spread alone insufficient?
Answer: Spread is shallow and shares references to nested objects
Object spread copies top-level properties, but nested arrays and objects retain the same references. Use structuredClone for supported data or a domain-specific copy.
Cloneable data includes Date, Map, and circular references. Which deep-copy approach is appropriate?
Answer: Use structuredClone()
structuredClone handles many built-in types and circular references supported by the structured clone algorithm. Functions and some host objects remain unsupported.
Which collection suits arbitrary object keys with frequent insertion, deletion, and iteration?
Answer: Map
Map supports arbitrary key types including objects and provides explicit size, iteration, insertion, and deletion APIs. Plain objects remain suitable for string-keyed records.
Data should be associated with DOM elements without preventing garbage collection after an element is discarded. Which collection is appropriate?
Answer: Use a WeakMap keyed by the element
WeakMap keys are weakly held and do not prevent collection of otherwise unreachable objects. Because entries are not enumerable, use Map when listing all entries is required.
A large list needs click handling that also works for items added later. Which approach is appropriate?
Answer: Attach one listener to the parent and identify the item with event.target.closest()
Event delegation uses bubbling so one parent listener handles current and future children. Verify that the matched target belongs to the intended container.
User input must be displayed as text in the DOM, not interpreted as HTML. Which approach is appropriate?
Answer: Assign it to textContent
textContent treats the input as text rather than parsing markup. Rich HTML requires a trusted sanitizer and context-specific defenses.
An object merge accepts external keys. Which control helps prevent prototype pollution?
Answer: Allow only schema-defined keys and reject dangerous keys such as __proto__, constructor, and prototype
Dynamic paths from external input require allowlisting and schema validation. Object.create(null) or Map can provide additional defenses depending on the use case.
A window event listener keeps referencing a component after it is destroyed. What is the appropriate fix?
Answer: Remove the same listener reference or use an AbortSignal tied to the component lifecycle
Listeners on long-lived targets can retain short-lived objects. Design cleanup at registration time and also dispose timers and observers.
ES modules have a cycle that causes access to a binding before initialization. What is an appropriate improvement?
Answer: Move shared contracts to a separate module with one-way dependencies and remove mutual top-level initialization
ES module imports are live bindings, but cyclic top-level evaluation can expose initialization-order problems. Refactor dependency direction and initialization ownership.
A search API should run once after the user stops typing rather than on every keystroke. Which technique is appropriate?
Answer: Debounce by canceling the previous timer on each new input
Debouncing runs after events remain quiet for a period. Throttling is appropriate when ongoing events such as scrolling should still produce periodic updates.
Which TypeScript type is appropriate at the boundary for safely handling a JSON.parse result?
Answer: Receive it as unknown and narrow it with schema validation or type guards
TypeScript types do not validate runtime input. unknown requires narrowing before use, allowing a validator to establish structure before producing a domain type.
What is required before calling a string method on a string | number value?
Answer: Narrow with typeof value === 'string'
A typeof check aligns runtime behavior with control-flow analysis and narrows the branch to string. An assertion does not protect against a number at runtime.
Which type safely represents loading, success, and failure states with their corresponding data?
Answer: A discriminated union with a state literal
A discriminated union narrows data after checking state === 'success' and prevents many impossible combinations from being represented.
How can an unhandled switch case become a compile error when a new discriminated-union variant is added?
Answer: Assign the remaining value to never in the default branch
After every variant is handled, the remaining value narrows to never. An unhandled new variant is not assignable to never, producing an exhaustiveness error.
Which generic constraint is appropriate for a function that reads id from any type containing that property?
Answer: T extends { id: string }
A structural constraint guarantees the required id while preserving the caller's specific type T including additional properties.
Which type operator restricts an argument to property names that exist on object type T?
Answer: keyof T
keyof creates a union of known property keys. Combined with K extends keyof T and T[K], it models a type-safe property accessor.
Which utility type creates an update DTO where every property of User is optional?
Answer: Partial<User>
Partial is a mapped type that makes each property optional. Use Pick or a dedicated DTO when only specific fields should be mutable.
A configuration object should be checked against Record<string, string> while preserving literal inference for its properties. Which feature is appropriate?
Answer: The satisfies operator
satisfies checks assignability to a target type while preserving the expression's more specific inferred type. It is not runtime validation.
An HTTP method array should infer as an immutable literal tuple. Which construct is appropriate?
Answer: ['GET', 'POST'] as const
A const assertion infers the array as a readonly tuple with string literal elements. It does not deeply freeze the value at runtime.
What is the main effect of enabling strictNullChecks?
Answer: Treat null and undefined as distinct types and require explicit handling where needed
With strictNullChecks, possible absence appears in unions and requires checks or optional chaining. Runtime validation of external data is still necessary.
Which tsconfig option reflects that reading a missing key from Record<string, User> may return undefined?
Answer: noUncheckedIndexedAccess
noUncheckedIndexedAccess adds undefined to unchecked indexed reads and encourages existence checks. It does not change the runtime data structure.
After catching an unknown thrown value, how should code safely obtain an error message?
Answer: Check value instanceof Error and handle other values separately, such as with String(value)
JavaScript can throw values other than Error. Narrowing from unknown enables safe access to Error.message while preserving handling for other values.
A reusable runtime check isUser should narrow its argument to User for callers. Which return type is appropriate?
Answer: A type predicate value is User
A function returning a type predicate narrows the argument in the true branch. Its implementation must genuinely validate the required properties.
validateConfig throws on failure and should make its argument a Config afterward. Which signature is appropriate?
Answer: asserts value is Config
An assertion function tells the compiler that the condition holds after a normal return. Returning without genuine validation breaks soundness.
UserId and OrderId are both strings, but accidental interchange should be prevented. Which type design is appropriate?
Answer: Create separately branded string types through validated boundary factories
Because TypeScript is structurally typed, plain string aliases remain interchangeable. Intersected brands created by validated factories reduce accidental mixing.
An import used only as a type should not remain in generated JavaScript. Which syntax is appropriate?
Answer: import type { User } from './types'
import type is restricted to type positions and is erased during emit, clearly separating runtime and type dependencies.
An existing JavaScript package lacks type definitions. What is an appropriate way to add minimal typing?
Answer: Provide a .d.ts declare module matching the actual public API
A declaration file describes runtime shape to the compiler without implementing it. Keep it synchronized with the implementation version and manage it with the package or a type package when possible.
A large repository needs separated TypeScript projects with dependency-ordered incremental builds. Which feature is appropriate?
Answer: Use project references with composite projects
Project references declare project boundaries and dependencies, enabling dependency-ordered incremental builds through tsc --build. Output directories should remain separate.
A function accepts string or string[] and always returns number. Which signature design is appropriate?
Answer: Use a string | string[] parameter and narrow inside the function
A union is clearer when input variants share one return type. Overloads are useful when call signatures express distinct input-output relationships.
Why is runtime validation still needed for an API response even when TypeScript type checking passes?
Answer: Type annotations are erased and do not enforce the actual shape of an external response
TypeScript types disappear when emitted as JavaScript. Validate schemas at trust boundaries such as network, storage, and user input, then produce typed data after success.