InterviewTreedInterviewTreed

InterviewTreed Question Bank

JavaScript & TypeScript Interview Questions and Answers

Prepare for modern JavaScript and TypeScript development, including language fundamentals, asynchronous programming, DOM manipulation, advanced concepts, and type-safe application development.

Total Questions

100

Beginner

30

Intermediate

35

Advanced

35

Beginner Questions

Foundational concepts, terminology, and core ideas.

Q2JavaScript fundamentals

What is the difference between let, const, and var?

Interview question about what is the difference between let, const, and var?.

Answer

let and const are block-scoped; var is function-scoped. let can be reassigned, const cannot be rebound, but const objects can still be mutated.

Syntax

let count = 0;
count++;
const user = { name: 'Asha' };
user.name = 'Mina';

Key Points

  • Prefer const by default
  • Use let for reassignment
  • Avoid var in modern code
Q3JavaScript fundamentals

What are JavaScript primitive types?

Interview question about what are javascript primitive types?.

Answer

The primitive types are string, number, bigint, boolean, undefined, symbol, and null. Objects, arrays, and functions are reference values.

Syntax

const title = 'Engineer';
const score = 9.5;
const big = 123n;
const active = true;
const absent = null;

Key Points

  • typeof null is historically object
  • Primitives are immutable values
  • Use bigint for large integers
Q4JavaScript fundamentals

What is the difference between == and ===?

Interview question about what is the difference between == and ===?.

Answer

== may coerce types before comparison; === compares without type conversion. Strict equality is usually more predictable.

Syntax

5 == '5';  // true
5 === '5'; // false

Key Points

  • Prefer === and !==
  • Know coercion in legacy code
  • NaN !== NaN
Q5JavaScript fundamentals

What are truthy and falsy values?

Interview question about what are truthy and falsy values?.

Answer

Falsy values include false, 0, -0, 0n, empty string, null, undefined, and NaN. Empty arrays and empty objects are truthy.

Syntax

if (items.length) console.log('Has items');
const label = input ?? 'Default';

Key Points

  • Empty arrays are truthy
  • ?? only defaults null/undefined
  • 0 and empty string can be valid values
Q6JavaScript fundamentals

What is type coercion?

Interview question about what is type coercion?.

Answer

Type coercion converts values between types. It can happen implicitly through operators or explicitly with Number, String, and Boolean.

Syntax

Number('42'); // 42
String(42); // '42'
'5' + 2; // '52'

Key Points

  • + may concatenate strings
  • Validate conversion results
  • Prefer explicit conversion
Q7JavaScript fundamentals

How are null and undefined different?

Interview question about how are null and undefined different?.

Answer

undefined often indicates a missing or uninitialized value; null is commonly assigned intentionally to represent absence. Use each consistently in your application.

Syntax

let result;
console.log(result); // undefined
const selectedUser = null;

Key Points

  • Optional properties may be undefined
  • JSON handles them differently
  • Use domain-specific states when useful
Q8JavaScript fundamentals

What is NaN and how do you test for it?

Interview question about what is nan and how do you test for it?.

Answer

NaN represents an invalid numeric result. It is not equal to itself, so use Number.isNaN for reliable checking without coercion.

Syntax

const value = Number('hello');
Number.isNaN(value); // true

Key Points

  • Number.isNaN does not coerce
  • Global isNaN does
  • Validate external input
Q9JavaScript fundamentals

What are template literals?

Interview question about what are template literals?.

Answer

Template literals use backticks and support interpolation and multiline text. They do not automatically sanitize HTML or SQL.

Syntax

const name = 'Asha';
const greeting = `Hello, ${name}!`;

Key Points

  • Use ${} for expressions
  • Do not interpolate untrusted input into SQL
  • HTML output still needs safe handling
Q10JavaScript functions

What are arrow functions?

Interview question about what are arrow functions?.

Answer

Arrow functions provide concise syntax and capture this lexically. They have no own this or arguments and cannot be used as constructors.

Syntax

const double = n => n * 2;
const greet = name => `Hi ${name}`;

Key Points

  • Useful for callbacks
  • Not always suitable for object methods
  • Cannot be called with new
Q11JavaScript functions

What are default parameters?

Interview question about what are default parameters?.

Answer

Default parameters apply when an argument is omitted or undefined, not when it is null, false, zero, or an empty string.

Syntax

function greet(name = 'Guest') { return `Hi ${name}`; }
greet(); // Hi Guest

Key Points

  • Defaults can be expressions
  • null does not trigger the default
  • Use ?? for nullish fallback
Q12JavaScript functions

What is a callback?

Interview question about what is a callback?.

Answer

A callback is a function passed to another function to be called later or during an operation. Callbacks can be synchronous or asynchronous.

Syntax

function run(task, done) { done(task()); }
run(() => 2 + 3, value => console.log(value));

Key Points

  • Common in events and array methods
  • Legacy Node APIs use error-first callbacks
  • Promises help flatten async flows
Q13JavaScript arrays

How do map, filter, and forEach differ?

Interview question about how do map, filter, and foreach differ?.

Answer

map transforms every item and returns an array; filter returns matching items; forEach performs side effects and returns undefined.

Syntax

const nums = [1, 2, 3];
nums.map(n => n * 2);
nums.filter(n => n > 1);
nums.forEach(console.log);

Key Points

  • map/filter do not mutate the source
  • Avoid side effects in map
  • for...of supports break
Q14JavaScript arrays

What are destructuring and spread syntax?

Interview question about what are destructuring and spread syntax?.

Answer

Destructuring extracts values from arrays or objects. Spread expands iterable items or enumerable object properties; copies are shallow.

Syntax

const [first, ...rest] = [10, 20, 30];
const next = { ...user, active: false };

Key Points

  • Nested references remain shared
  • Later spread properties override earlier ones
  • Useful for immutable updates
Q15JavaScript objects

What is optional chaining?

Interview question about what is optional chaining?.

Answer

Optional chaining ?. stops a property access or call when the left side is null or undefined and returns undefined rather than throwing.

Syntax

const city = response?.user?.address?.city;
const label = city ?? 'Unknown';

Key Points

  • Useful for optional data
  • Does not validate required fields
  • Combine with nullish coalescing
Q16JavaScript scope

What is lexical scope?

Interview question about what is lexical scope?.

Answer

Lexical scope means variables are resolved based on where code is written. Inner functions can access variables from enclosing scopes.

Syntax

function makeGreeting(name) {
  return () => `Hello ${name}`;
}

Key Points

  • Scope follows source structure
  • Closures retain lexical bindings
  • Avoid accidental globals
Q17JavaScript scope

What is a closure?

Interview question about what is a closure?.

Answer

A closure is a function that retains access to variables in its surrounding scope even after the outer function returns.

Syntax

function counter() { let n = 0; return () => ++n; }
const next = counter();
next(); // 1

Key Points

  • Useful for encapsulation
  • Retains bindings, not frozen snapshots
  • Can keep referenced data alive
Q18JavaScript modules

What are ES modules?

Interview question about what are es modules?.

Answer

ES modules use import and export to define dependencies and expose values. Module scope is separate from global scope.

Syntax

export const PI = 3.14;
export function area(r) { return PI * r * r; }
import { area } from './math.js';

Key Points

  • Named and default exports differ
  • Use consistent conventions
  • Runtime configuration affects module loading
Q19JavaScript errors

How do try, catch, and finally work?

Interview question about how do try, catch, and finally work?.

Answer

try wraps potentially failing code, catch handles thrown errors, and finally runs regardless of success or failure.

Syntax

try { riskyOperation(); }
catch (error) { console.error(error); }
finally { cleanup(); }

Key Points

  • Catch errors you can handle
  • Do not silently swallow errors
  • Use finally for cleanup
Q20JavaScript JSON

How do JSON.stringify and JSON.parse work?

Interview question about how do json.stringify and json.parse work?.

Answer

stringify converts supported values to JSON text; parse converts JSON text back into JavaScript values. JSON does not preserve all JavaScript types.

Syntax

const text = JSON.stringify({ name: 'Mina' });
const data = JSON.parse(text);

Key Points

  • Validate untrusted parsed data
  • BigInt is not serializable by default
  • Functions and undefined properties are omitted
Q21TypeScript fundamentals

What is TypeScript?

Interview question about what is typescript?.

Answer

TypeScript adds a static type system and tooling to JavaScript. Its types are erased from emitted JavaScript and do not validate runtime data automatically.

Syntax

type User = { id: number; name: string };
const user: User = { id: 1, name: 'Asha' };

Key Points

  • Type-checking is primarily compile-time
  • Runtime validation is separate
  • Can target different JS versions
Q22TypeScript fundamentals

How do you type function parameters and returns?

Interview question about how do you type function parameters and returns?.

Answer

Parameter annotations define accepted inputs; return annotations document and check outputs. Inference can reduce unnecessary annotations.

Syntax

function add(a: number, b: number): number { return a + b; }

Key Points

  • Avoid any when possible
  • Use inference for local values
  • Public APIs benefit from clear contracts
Q23TypeScript fundamentals

How do any and unknown differ?

Interview question about how do any and unknown differ?.

Answer

any disables most checking; unknown can hold any value but must be narrowed before use. Prefer unknown for untrusted data.

Syntax

let input: unknown = JSON.parse(raw);
if (typeof input === 'string') console.log(input.toUpperCase());

Key Points

  • any spreads unsafety
  • Narrow unknown with guards
  • Validate external data
Q24TypeScript fundamentals

What are union types?

Interview question about what are union types?.

Answer

A union allows a value to match one of several types. Narrow it before accessing members not shared by every variant.

Syntax

type Id = string | number;
function formatId(id: Id) { return typeof id === 'number' ? `#${id}` : id.toUpperCase(); }

Key Points

  • Use discriminated unions for states
  • Narrow with runtime checks
  • Avoid unnecessarily broad unions
Q25TypeScript fundamentals

What is the difference between interface and type?

Interview question about what is the difference between interface and type?.

Answer

Interfaces primarily describe object contracts and can merge declarations; type aliases can describe unions, tuples, primitives, and object shapes.

Syntax

interface User { id: number; name: string }
type Status = 'pending' | 'done';

Key Points

  • Both use structural typing
  • Interfaces can be extended
  • Choose consistent project conventions
Q26TypeScript fundamentals

What is type inference?

Interview question about what is type inference?.

Answer

TypeScript infers types from initializers, expressions, and context. Explicit annotations are useful at public boundaries or when inference is too broad.

Syntax

const count = 3; // number
const names = ['Asha', 'Mina']; // string[]

Key Points

  • Avoid needless annotations
  • Annotate public contracts
  • Check inference for empty arrays
Q27TypeScript fundamentals

What are optional and readonly properties?

Interview question about what are optional and readonly properties?.

Answer

Optional properties may be absent; readonly properties cannot be reassigned through that type. readonly is a compile-time restriction and is shallow by default.

Syntax

type Config = { readonly id: string; timeoutMs?: number };

Key Points

  • Compiler options affect undefined semantics
  • Readonly is not deep immutability
  • Use optional only when absence is meaningful
Q28TypeScript configuration

What is tsconfig.json?

Interview question about what is tsconfig.json?.

Answer

tsconfig.json controls compiler options such as target, module format, strictness, included files, and path aliases.

Syntax

{
  "compilerOptions": { "target": "ES2022", "module": "ESNext", "strict": true, "noEmit": true }
}

Key Points

  • Enable strict checks for new projects
  • Build tools may transpile without type checking
  • Align config with runtime
Q29JavaScript objects

What are Map and Set?

Interview question about what are map and set?.

Answer

Map stores key-value pairs with keys of any type; Set stores unique values. Both preserve insertion order.

Syntax

const scores = new Map(); scores.set('Asha', 95);
const ids = new Set([1, 1, 2]);

Key Points

  • Map is designed for key-value lookup
  • Set stores unique values
  • Plain objects suit record-like string keys
Q30JavaScript language

What is the difference between slice and splice?

Interview question about what is the difference between slice and splice?.

Answer

slice returns a shallow selected copy without mutating the array; splice mutates the array by removing, replacing, or inserting items.

Syntax

const a = [1, 2, 3, 4];
a.slice(1, 3); // [2,3]
a.splice(1, 1, 9); // changes a

Key Points

  • slice end index is exclusive
  • splice mutates source
  • Use immutable updates when appropriate
Q31JavaScript language

What are primitive and reference values?

Interview question about what are primitive and reference values?.

Answer

Primitive values represent single immutable values; objects are accessed through references. Assigning an object variable copies the reference, not the object.

Syntax

const a = { count: 1 };
const b = a;
b.count = 2;
console.log(a.count); // 2

Key Points

  • Multiple variables can reference one object
  • Shallow copies retain nested references
  • Mutation can affect other consumers

Intermediate Questions

Implementation details, practical patterns, and common workflows.

Q1JavaScript fundamentals

What is JavaScript?

Interview question about what is javascript?.

Answer

JavaScript is a programming language used in browsers and runtimes such as Node.js. ECMAScript defines core language behavior, while each runtime supplies host APIs.

Syntax

const message = 'Hello, JavaScript';
console.log(message);

Key Points

  • Runs in browsers and servers
  • Language and host APIs are distinct
Q32JavaScript execution

What is hoisting?

Interview question about what is hoisting?.

Answer

Declarations are processed before execution. Function declarations can generally be called before their text; var is initialized to undefined; let/const remain inaccessible in the temporal dead zone until initialized.

Syntax

sayHi();
function sayHi() { console.log('Hi'); }
console.log(value); // undefined
var value = 1;

Key Points

  • Avoid depending on hoisting
  • let/const have a temporal dead zone
  • Function expressions follow binding rules
Q33JavaScript execution

What is the temporal dead zone?

Interview question about what is the temporal dead zone?.

Answer

It is the interval between entering a scope and initializing a let or const binding. Accessing the binding during that interval throws ReferenceError.

Syntax

console.log(status); // ReferenceError
let status = 'ready';

Key Points

  • Binding exists but cannot yet be accessed
  • Helps catch use-before-initialization
  • Applies to block-scoped declarations
Q34JavaScript objects

What is the prototype chain?

Interview question about what is the prototype chain?.

Answer

Objects can inherit from another object through their prototype. Property lookup continues up the chain if a property is not found directly.

Syntax

const base = { greet() { return 'hello'; } };
const child = Object.create(base);
child.greet();

Key Points

  • Classes use prototypes underneath
  • Object.create sets prototype explicitly
  • Avoid modifying built-in prototypes
Q35JavaScript objects

How does this differ in regular and arrow functions?

Interview question about how does this differ in regular and arrow functions?.

Answer

In regular functions, this depends on how the function is called. Arrow functions capture this from the surrounding lexical scope.

Syntax

const user = { name: 'Asha', later() { return () => this.name; } };

Key Points

  • Detached methods may lose receiver
  • bind can set this for regular functions
  • Arrow functions have no own this
Q36JavaScript objects

What do call, apply, and bind do?

Interview question about what do call, apply, and bind do?.

Answer

call invokes a function with a chosen this and separate arguments; apply takes an argument array-like; bind returns a function with this and optional arguments fixed.

Syntax

function greet(prefix) { return `${prefix} ${this.name}`; }
const user = { name: 'Mina' };
greet.call(user, 'Hi');
const bound = greet.bind(user, 'Hello');

Key Points

  • Arrow-function this cannot be rebound
  • bind is useful for callbacks
  • Closures may be simpler
Q37JavaScript arrays

What do some, every, find, and reduce do?

Interview question about what do some, every, find, and reduce do?.

Answer

some checks if any item matches; every checks all; find returns the first match; reduce combines items into one accumulator.

Syntax

const nums = [1,2,3,4];
nums.some(n => n > 3);
nums.every(n => n > 0);
nums.find(n => n % 2 === 0);
nums.reduce((sum,n) => sum+n, 0);

Key Points

  • reduce should have a clear accumulator
  • find returns undefined if absent
  • Avoid unnecessary complexity
Q38JavaScript async

What is a Promise?

Interview question about what is a promise?.

Answer

A Promise represents an eventual result and settles once as fulfilled or rejected. then transforms results and catch handles rejection.

Syntax

fetch('/api/users').then(r => { if (!r.ok) throw new Error('HTTP error'); return r.json(); }).catch(console.error);

Key Points

  • then returns a new promise
  • Check HTTP status for fetch
  • Handle network and parsing errors
Q39JavaScript async

How does async/await work?

Interview question about how does async/await work?.

Answer

An async function always returns a Promise. await pauses that function until a promise settles, yielding its value or throwing its rejection reason.

Syntax

async function load(id) {
  const response = await fetch(`/api/users/${id}`);
  if (!response.ok) throw new Error('Request failed');
  return response.json();
}

Key Points

  • await does not block the whole thread
  • Use try/catch for recovery
  • Check HTTP status
Q40JavaScript async

How do Promise.all and Promise.allSettled differ?

Interview question about how do promise.all and promise.allsettled differ?.

Answer

Promise.all rejects when an input rejects and fulfills when all fulfill. Promise.allSettled waits for every input and returns each outcome.

Syntax

const outcomes = await Promise.allSettled([fetch('/a'), fetch('/b')]);
const values = await Promise.all([loadA(), loadB()]);

Key Points

  • all is for jointly required results
  • allSettled supports partial outcomes
  • Neither automatically cancels siblings
Q41JavaScript async

How do Promise.race and Promise.any differ?

Interview question about how do promise.race and promise.any differ?.

Answer

race settles with the first promise to settle; any fulfills with the first fulfillment and rejects with AggregateError if all reject.

Syntax

const fastest = await Promise.race([primary(), backup()]);
const firstSuccess = await Promise.any([regionA(), regionB()]);

Key Points

  • race does not cancel losers
  • any is useful for redundant providers
  • Handle all-failed cases
Q42JavaScript async

What is the event loop?

Interview question about what is the event loop?.

Answer

The event loop coordinates synchronous execution and scheduled work. Promise reactions run as microtasks; timers and many I/O callbacks run through host task mechanisms.

Syntax

console.log('A');
setTimeout(() => console.log('timer'), 0);
Promise.resolve().then(() => console.log('promise'));
console.log('B');
// A, B, promise, timer

Key Points

  • Long synchronous code blocks the thread
  • Microtasks run at defined checkpoints
  • Host runtime details differ
Q43JavaScript async

What is a microtask versus a task?

Interview question about what is a microtask versus a task?.

Answer

Promise reactions and queueMicrotask callbacks are microtasks. Timers and many event callbacks are tasks; microtasks are typically drained before the next task.

Syntax

queueMicrotask(() => console.log('microtask'));
setTimeout(() => console.log('task'), 0);

Key Points

  • Avoid endlessly adding microtasks
  • Synchronous work still blocks
  • Rendering and Node phases add details
Q44JavaScript async

How do you run async tasks sequentially or in parallel?

Interview question about how do you run async tasks sequentially or in parallel?.

Answer

Await sequentially when later work depends on earlier results. Start independent operations together and await Promise.all to reduce latency.

Syntax

const user = await loadUser();
const orders = await loadOrders(user.id);
const [products, categories] = await Promise.all([loadProducts(), loadCategories()]);

Key Points

  • Parallelize only independent tasks
  • Limit concurrency for large batches
  • Decide how partial failures behave
Q45JavaScript async

Why can async code have race conditions?

Interview question about why can async code have race conditions?.

Answer

At await points, other operations can modify shared state before a function resumes. Use sequencing, atomic server operations, version checks, or locks when correctness requires it.

Syntax

let balance = 100;
async function spend(amount) { const current = balance; await verify(); balance = current - amount; }

Key Points

  • Operations interleave across awaits
  • Prefer atomic server-side invariants
  • Prevent stale UI updates
Q46TypeScript types

What is a discriminated union?

Interview question about what is a discriminated union?.

Answer

A union of object types sharing a literal property lets TypeScript narrow the type by checking that property.

Syntax

type Result = { status: 'ok'; data: string } | { status: 'error'; message: string };
function show(r: Result) { return r.status === 'ok' ? r.data : r.message; }

Key Points

  • Use literal discriminants
  • Exhaustive checks catch missing variants
  • Good for UI states
Q47TypeScript types

What are generics?

Interview question about what are generics?.

Answer

Generics parameterize functions and types while preserving relationships between inputs and outputs.

Syntax

function first<T>(items: T[]): T | undefined { return items[0]; }
const name = first(['Asha', 'Mina']);

Key Points

  • Inference often determines type arguments
  • Use extends for constraints
  • Avoid needless generic complexity
Q48TypeScript types

What are keyof and indexed access types?

Interview question about what are keyof and indexed access types?.

Answer

keyof produces a union of property keys; T[K] retrieves the type of a property selected by key K.

Syntax

type User = { id: number; name: string };
type Key = keyof User;
type Name = User['name'];

Key Points

  • Constrain keys with keyof T
  • Useful for safe property helpers
  • Index signatures affect key types
Q49TypeScript types

What are Partial, Pick, Omit, and Readonly?

Interview question about what are partial, pick, omit, and readonly?.

Answer

These utility types transform an existing type: Partial makes fields optional, Pick selects keys, Omit removes keys, and Readonly prevents reassignment at type-check time.

Syntax

type User = { id: number; name: string; passwordHash: string };
type Update = Partial<Pick<User, 'name'>>;
type PublicUser = Omit<User, 'passwordHash'>;

Key Points

  • Compile-time only
  • Readonly is shallow
  • Use explicit API DTOs
Q50TypeScript types

What is a type guard?

Interview question about what is a type guard?.

Answer

A type guard is a runtime check that narrows a variable's type. Built-in examples include typeof, instanceof, in, and custom predicates.

Syntax

function isString(value: unknown): value is string { return typeof value === 'string'; }

Key Points

  • Checks must be logically correct
  • Use schemas for complex input
  • A cast is not validation
Q51TypeScript types

What is the difference between type assertion and runtime validation?

Interview question about what is the difference between type assertion and runtime validation?.

Answer

An assertion tells TypeScript to trust a type without checking the value at runtime. Runtime validation inspects the actual value and verifies its shape.

Syntax

const data = JSON.parse(text) as User; // no runtime validation
if (!isUser(data)) throw new Error('Invalid payload');

Key Points

  • Never treat a cast as validation
  • Validate network data
  • Assertions can document known facts
Q52TypeScript config

What is strictNullChecks?

Interview question about what is strictnullchecks?.

Answer

strictNullChecks treats null and undefined as distinct types, forcing code to handle their possible absence rather than assuming every value exists.

Syntax

const names: string[] = [];
const first = names[0];
if (first !== undefined) console.log(first.toUpperCase());

Key Points

  • Improves correctness
  • noUncheckedIndexedAccess adds checks for indexed reads
  • Enable strict options deliberately
Q53JavaScript modules

How do CommonJS and ES modules differ?

Interview question about how do commonjs and es modules differ?.

Answer

CommonJS uses require and module.exports; ES modules use import and export. Resolution and interoperability depend on package and runtime configuration.

Syntax

// CommonJS
const fs = require('node:fs');
module.exports = { run };
// ESM
import fs from 'node:fs';
export { run };

Key Points

  • Check package.json type
  • Avoid accidental mixed module formats
  • Interop defaults can differ
Q54JavaScript async

How do you handle errors with async/await?

Interview question about how do you handle errors with async/await?.

Answer

Use try/catch when the current function can recover or add context. Otherwise propagate the rejection to a boundary that can handle it.

Syntax

async function load() { try { return await fetchData(); } catch (error) { logger.error({ error }); throw error; } }

Key Points

  • Do not swallow errors
  • Preserve error causes
  • Handle failures at application boundaries
Q55JavaScript async

Does fetch reject for HTTP 404?

Interview question about does fetch reject for http 404?.

Answer

Usually no: fetch fulfills with a Response for HTTP errors such as 404 or 500. Check response.ok; fetch rejects for network-level failures and similar errors.

Syntax

const response = await fetch('/api/items');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const items = await response.json();

Key Points

  • Transport and HTTP errors differ
  • Response body is usually consumed once
  • Validate parsed response shape
Q56JavaScript async

How does AbortController cancel fetch?

Interview question about how does abortcontroller cancel fetch?.

Answer

Pass its signal to fetch and call abort to cancel client-side waiting and supported work. The server may already have started processing.

Syntax

const controller = new AbortController();
const request = fetch('/api/search', { signal: controller.signal });
controller.abort();

Key Points

  • Handle AbortError separately
  • Cancellation is cooperative
  • Clean up controllers with component lifecycles
Q57JavaScript async

How do you limit concurrency for many tasks?

Interview question about how do you limit concurrency for many tasks?.

Answer

Use a concurrency limiter or batches instead of starting thousands of promises at once. Decide how errors and result ordering should work.

Syntax

async function batches(items, size, worker) {
 const out = [];
 for (let i=0; i<items.length; i+=size) out.push(...await Promise.all(items.slice(i,i+size).map(worker)));
 return out;
}

Key Points

  • Protect downstream services
  • Batching can delay later tasks
  • A limiter handles uneven task durations
Q58TypeScript types

What is structural typing?

Interview question about what is structural typing?.

Answer

TypeScript generally considers types compatible based on their members rather than declared names. This is flexible but can mix semantically different values with identical shapes.

Syntax

type Point = { x: number; y: number };
const value = { x: 1, y: 2, label: 'origin' };
const point: Point = value;

Key Points

  • Excess-property checks apply in some contexts
  • Use branded types for distinct IDs
  • Runtime validation is separate
Q59TypeScript types

What are enums and alternatives?

Interview question about what are enums and alternatives?.

Answer

Enums provide named constants and may emit runtime code. Literal unions and as-const objects are common alternatives with strong integration into TypeScript's type system.

Syntax

type Direction = 'north' | 'south' | 'east' | 'west';
const Status = { Active: 'active', Disabled: 'disabled' } as const;

Key Points

  • Understand emitted output
  • Literal unions are lightweight
  • Use object constants when runtime lookup is needed
Q60JavaScript language

What is immutability?

Interview question about what is immutability?.

Answer

Immutability means treating values as unchanged after creation. Copy-based updates make state transitions easier to reason about, but shallow copies keep nested references.

Syntax

const user = { name: 'Asha', active: true };
const next = { ...user, active: false };

Key Points

  • Spread is shallow
  • Object.freeze is shallow by default
  • Immutability reduces shared-state bugs
Q61JavaScript async

What is top-level await?

Interview question about what is top-level await?.

Answer

Top-level await lets an ES module await an asynchronous result during module evaluation. It can simplify initialization but may delay dependent modules.

Syntax

const config = await loadConfig();
export { config };

Key Points

  • Requires ES module support
  • Not traditional CommonJS syntax
  • Avoid unnecessary startup blocking
Q62JavaScript async

How do you stream or iterate async results?

Interview question about how do you stream or iterate async results?.

Answer

Async iterators produce values over time, and for-await-of consumes them one at a time. They suit streams and paginated APIs.

Syntax

async function* pages() { yield await fetchPage(1); yield await fetchPage(2); }
for await (const page of pages()) processPage(page);

Key Points

  • Can reduce memory use
  • Handle cancellation and cleanup
  • Backpressure depends on producer design
Q63JavaScript execution

Explain the call stack and event loop together.

Interview question about explain the call stack and event loop together..

Answer

The call stack tracks active function calls. Once synchronous execution yields, the host event loop coordinates tasks and microtask checkpoints. Async APIs schedule future callbacks; they do not make long synchronous work non-blocking.

Syntax

Call stack → microtask queue → host task queue
Main() → Promise reactions → timer / I/O callbacks

Key Points

  • Long CPU work blocks the thread
  • Microtasks can delay tasks
  • Browser and Node scheduling differ
Q64JavaScript execution

How do concurrency and parallelism differ?

Interview question about how do concurrency and parallelism differ?.

Answer

Concurrency means operations overlap in progress; parallelism means work runs simultaneously on separate execution resources. A single thread can coordinate concurrent I/O while workers run CPU tasks in parallel.

Syntax

Main thread schedules I/O
Worker thread computes in parallel
Messages transfer results

Key Points

  • Async I/O is not necessarily CPU parallelism
  • Workers have communication costs
  • Use workers for suitable CPU-heavy work
Q65JavaScript async

How do you prevent stale async search results?

Interview question about how do you prevent stale async search results?.

Answer

Older requests may finish after newer requests. Abort previous requests where possible and use a sequence identifier so only the latest result updates the UI.

Syntax

let latest = 0;
async function search(q) { const id = ++latest; const data = await fetchResults(q); if (id === latest) render(data); }

Key Points

  • Cancellation alone may not be enough
  • Debouncing reduces requests
  • Track component lifecycle

Advanced Questions

Architecture, optimization, and design trade-offs.

Q66JavaScript async

How should retries for a flaky API be designed?

Interview question about how should retries for a flaky api be designed?.

Answer

Retry only transient failures and operations safe to repeat. Use bounded exponential backoff with jitter, respect retry guidance, and set a total deadline.

Syntax

delay = Math.min(maxDelay, baseDelay * 2 ** attempt) * jitter;

Key Points

  • Do not retry validation errors by default
  • Use idempotency keys for writes
  • Retries can amplify outages
Q67JavaScript async

What is structured concurrency?

Interview question about what is structured concurrency?.

Answer

Structured concurrency scopes concurrent tasks to a parent operation with clear cancellation and error propagation. JavaScript code can approximate it with AbortController and explicit Promise coordination.

Syntax

const controller = new AbortController();
try { await Promise.all(tasks.map(t => t({ signal: controller.signal }))); }
catch (e) { controller.abort(); throw e; }

Key Points

  • Promise.all does not cancel siblings
  • Propagate cancellation
  • Define partial-success behavior
Q68TypeScript advanced

What are conditional types?

Interview question about what are conditional types?.

Answer

Conditional types select a type based on whether one type extends another. They can distribute across unions when the checked type is a naked type parameter.

Syntax

type Element<T> = T extends (infer U)[] ? U : T;
type A = Element<string[]>; // string

Key Points

  • Can become difficult to read
  • Use helper aliases
  • Tuple wrapping can control distribution
Q69TypeScript advanced

What does infer do in a conditional type?

Interview question about what does infer do in a conditional type?.

Answer

infer declares a type variable within a conditional pattern so TypeScript can extract part of a type, such as a function return type.

Syntax

type ReturnOf<T> = T extends (...args: any[]) => infer R ? R : never;
type R = ReturnOf<() => Promise<number>>;

Key Points

  • Use ReturnType where suitable
  • Inference follows the matched structure
  • Keep utilities readable
Q70TypeScript advanced

What are mapped types?

Interview question about what are mapped types?.

Answer

Mapped types iterate over keys of a type to transform properties. Utility types such as Partial and Readonly use this mechanism.

Syntax

type Optional<T> = { [K in keyof T]?: T[K] };
type Flags<T> = { [K in keyof T]: boolean };

Key Points

  • Key remapping is possible
  • Compile-time only
  • Avoid excessive type-level complexity
Q71TypeScript advanced

What are template literal types?

Interview question about what are template literal types?.

Answer

Template literal types build string literal unions using template syntax. They can model event names, route keys, and naming conventions.

Syntax

type EventName<T extends string> = `${T}Changed`;
type E = EventName<'name' | 'email'>;

Key Points

  • No runtime validation
  • Large unions can slow type checking
  • Useful with mapped types
Q72TypeScript advanced

What are branded types?

Interview question about what are branded types?.

Answer

Branded types intersect a base type with a marker so semantically distinct values are not freely interchangeable at compile time. They do not validate runtime values.

Syntax

type UserId = string & { readonly __brand: 'UserId' };
function makeUserId(s: string): UserId { if (!s) throw Error(); return s as UserId; }

Key Points

  • Validate when creating the brand
  • Brands are compile-time conventions
  • Avoid unchecked casts everywhere
Q73TypeScript advanced

How do you type API responses safely?

Interview question about how do you type api responses safely?.

Answer

Treat parsed network data as unknown and validate it at runtime before using a TypeScript response type. Static annotations cannot prove what a server actually returned.

Syntax

const raw: unknown = await response.json();
const parsed = UserSchema.safeParse(raw);
if (!parsed.success) throw Error('Invalid response');
const user = parsed.data;

Key Points

  • Network data is untrusted
  • Runtime schemas validate shape
  • Keep shared schemas aligned
Q74TypeScript advanced

What are declaration files?

Interview question about what are declaration files?.

Answer

A .d.ts file describes types for JavaScript modules or globals without implementing runtime behavior. Incorrect declarations can hide actual errors.

Syntax

declare module 'legacy-widget' { export function mount(el: HTMLElement): void; }

Key Points

  • Prefer official types
  • Declaration files emit no runtime code
  • Keep declarations synchronized with actual library
Q75TypeScript advanced

What are type-only imports and exports?

Interview question about what are type-only imports and exports?.

Answer

import type and export type mark symbols used only during type checking, clarifying module intent and avoiding unnecessary runtime imports in suitable configurations.

Syntax

import type { User } from './types.js';
export type { User };

Key Points

  • Check compiler module settings
  • Some symbols are needed at runtime
  • Align with bundler conventions
Q76JavaScript performance

How do you diagnose a JavaScript memory leak?

Interview question about how do you diagnose a javascript memory leak?.

Answer

Reproduce the leak, compare heap snapshots, and inspect retaining paths. Common causes include listeners, timers, unbounded caches, detached DOM nodes, and closures holding large objects.

Syntax

Baseline heap → repeat workflow → capture heap → compare retained objects → inspect references

Key Points

  • Look at trends
  • Clean up subscriptions and timers
  • Bound caches
Q77JavaScript performance

How would you optimize CPU-heavy JavaScript?

Interview question about how would you optimize cpu-heavy javascript?.

Answer

Profile first, improve algorithmic complexity, reduce allocations, chunk work for responsiveness, or move CPU work to a worker thread.

Syntax

Main thread → postMessage(data) → Worker computes → postMessage(result)

Key Points

  • Workers add overhead
  • Chunking must yield to the event loop
  • Optimize measured bottlenecks
Q78JavaScript performance

How do debounce and throttle differ?

Interview question about how do debounce and throttle differ?.

Answer

Debounce runs after calls stop for a delay; throttle limits how frequently a function runs over time. Debounce suits search input; throttle suits scroll updates.

Syntax

function debounce(fn, delay) { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); }; }

Key Points

  • Clean up timers
  • Throttle can be leading or trailing
  • Neither replaces server rate limits
Q79JavaScript security

What is prototype pollution?

Interview question about what is prototype pollution?.

Answer

Prototype pollution happens when unsafe object merging or path assignment lets attacker-controlled keys affect prototypes or inherited properties. Validate keys and use safer data structures.

Syntax

const dictionary = Object.create(null);
// Reject dangerous keys in unsafe recursive merge logic

Key Points

  • Audit deep-merge helpers
  • Map suits arbitrary keys
  • Avoid mutating built-in prototypes
Q80JavaScript security

How can JavaScript cause cross-site scripting?

Interview question about how can javascript cause cross-site scripting?.

Answer

XSS occurs when untrusted content is interpreted as executable markup or script. Prefer textContent for text and use a vetted sanitizer when rich HTML is required.

Syntax

element.textContent = userSuppliedText;

Key Points

  • Context-aware output handling matters
  • CSP is defense in depth
  • Client validation does not make data trusted
Q81TypeScript architecture

How would you design types for a shared library?

Interview question about how would you design types for a shared library?.

Answer

Keep public types explicit and minimal, separate public contracts from implementation details, test type examples, and version breaking changes deliberately.

Syntax

export interface Page<T> { items: T[]; nextCursor?: string }
export type SortDirection = 'asc' | 'desc';

Key Points

  • Use generics for real relationships
  • Document runtime guarantees separately
  • Test emitted declarations
Q82TypeScript architecture

How do you reduce any in a legacy TypeScript codebase?

Interview question about how do you reduce any in a legacy typescript codebase?.

Answer

Replace any at boundaries with unknown, add runtime guards, and introduce precise types incrementally. Enable strict checks module by module.

Syntax

function parseInput(value: unknown): string { if (typeof value !== 'string') throw TypeError(); return value; }

Key Points

  • Prioritize risky boundaries
  • Avoid blanket casts
  • Use lint rules to prevent regressions
Q83JavaScript async

How would you design a resilient client-side data layer?

Interview question about how would you design a resilient client-side data layer?.

Answer

Centralize request construction, cancellation, response validation, error normalization, and auth behavior. Add caching and deduplication only with clear freshness rules, and prevent stale responses from updating state.

Syntax

UI → typed API client → fetch/AbortSignal → validate → cache/state → UI

Key Points

  • Handle auth errors distinctly
  • Prevent duplicate refresh races
  • Avoid cross-user private caching
Q84JavaScript async

How do you avoid unhandled promise rejections?

Interview question about how do you avoid unhandled promise rejections?.

Answer

Await promises or attach rejection handlers. A synchronous try/catch does not catch a rejection that happens later in an unawaited promise.

Syntax

button.addEventListener('click', () => { saveChanges().catch(showError); });

Key Points

  • Do not ignore fire-and-forget promises
  • Use runtime diagnostics
  • Keep errors observable
Q85JavaScript language

What are iterables and iterators?

Interview question about what are iterables and iterators?.

Answer

An iterable has a Symbol.iterator method returning an iterator. The iterator's next method returns an object with value and done fields.

Syntax

const iterable = { *[Symbol.iterator]() { yield 'a'; yield 'b'; } };
for (const item of iterable) console.log(item);

Key Points

  • Arrays and strings are iterable
  • Plain objects are not iterable by default
  • Generators simplify iterator creation
Q86JavaScript language

What is a generator function?

Interview question about what is a generator function?.

Answer

A generator returns an iterator and pauses at yield until the next iteration step. It supports lazy sequences and custom iteration.

Syntax

function* ids() { let id = 1; while (id <= 3) yield id++; }
const iterator = ids();
iterator.next();

Key Points

  • Execution is lazy
  • Can be closed early
  • Async generators support async sequences
Q87JavaScript language

What is shallow versus deep cloning?

Interview question about what is shallow versus deep cloning?.

Answer

A shallow clone copies top-level properties but shares nested references. structuredClone deeply clones many supported data types, with limits for functions and some host objects.

Syntax

const original = { profile: { city: 'Delhi' } };
const shallow = { ...original };
const deep = structuredClone(original);

Key Points

  • JSON clone loses unsupported values
  • Know structuredClone limits
  • Immutable updates may avoid deep cloning
Q88JavaScript language

What are WeakMap and WeakSet?

Interview question about what are weakmap and weakset?.

Answer

WeakMap stores values keyed by objects without keeping keys alive solely because of the map; WeakSet stores objects weakly. They are not enumerable.

Syntax

const metadata = new WeakMap();
const node = {};
metadata.set(node, { visited: true });

Key Points

  • No iteration or size property
  • Useful for object-associated metadata
  • Use only when weak-key semantics help
Q89JavaScript modules

How do circular ES module imports affect initialization?

Interview question about how do circular es module imports affect initialization?.

Answer

Circular imports can make initialization order difficult. ES modules use live bindings, but reading a binding before initialization can fail; extracting shared contracts often reduces coupling.

Syntax

A.ts → B.ts → A.ts
// Consider moving shared types or orchestration to a third module

Key Points

  • Cycles do not always fail
  • Avoid initialization side effects
  • Inspect dependency graphs
Q90TypeScript advanced

What does satisfies do?

Interview question about what does satisfies do?.

Answer

satisfies checks that an expression conforms to a type while preserving its more specific inferred type. It is useful for validated configuration maps.

Syntax

type Route = 'home' | 'settings';
const routes = { home: '/', settings: '/settings' } satisfies Record<Route, string>;

Key Points

  • Compile-time only
  • Does not validate runtime data
  • Good for exhaustive configuration
Q91JavaScript testing

How do you test async code reliably?

Interview question about how do you test async code reliably?.

Answer

Await promises, mock external dependencies, and use fake timers only for timer behavior. Test success, rejection, cancellation, timeout, and races without arbitrary sleeps.

Syntax

it('loads data', async () => { const result = await loadData(); expect(result).toEqual({ ok: true }); });

Key Points

  • Await test promises
  • Restore timers and mocks
  • Prefer deterministic synchronization
Q92TypeScript architecture

How would you model a multi-state asynchronous workflow?

Interview question about how would you model a multi-state asynchronous workflow?.

Answer

Use a discriminated union so each state carries only valid fields. This prevents contradictory boolean combinations and enables exhaustive transitions.

Syntax

type State<T> = { status: 'idle' } | { status: 'loading' } | { status: 'success'; data: T } | { status: 'error'; error: Error };

Key Points

  • Avoid impossible state combinations
  • Use exhaustive switches
  • Keep transitions testable
Q93JavaScript performance

How do you prevent event-listener leaks?

Interview question about how do you prevent event-listener leaks?.

Answer

Register listeners within a clear lifecycle and remove them when finished. AbortSignal-based event listeners can simplify cleanup.

Syntax

const controller = new AbortController();
window.addEventListener('resize', onResize, { signal: controller.signal });
controller.abort();

Key Points

  • Clean timers and observers too
  • Stable handler references matter
  • Test repeated mount/unmount cycles
Q94JavaScript async

How would you stream large API data safely?

Interview question about how would you stream large api data safely?.

Answer

Use streams or paginated async iterators to process bounded chunks. Respect backpressure, cancellation, and cleanup when processing stops early.

Syntax

const reader = response.body.getReader();
try { while (true) { const { value, done } = await reader.read(); if (done) break; await processChunk(value); } }
finally { reader.releaseLock(); }

Key Points

  • Chunks may not align to records
  • Support differs by runtime
  • Propagate cancellation
Q95TypeScript advanced

How do strictNullChecks and noUncheckedIndexedAccess help?

Interview question about how do strictnullchecks and nouncheckedindexedaccess help?.

Answer

strictNullChecks makes null and undefined distinct types; noUncheckedIndexedAccess adds undefined to many indexed reads so missing array or dictionary entries must be handled.

Syntax

const values: string[] = [];
const first = values[0];
if (first !== undefined) console.log(first.toUpperCase());

Key Points

  • Enable strict checks
  • Handle missing elements explicitly
  • Compiler flags may expose assumptions
Q96JavaScript security

How do you safely handle untrusted localStorage data?

Interview question about how do you safely handle untrusted localstorage data?.

Answer

Storage can be missing, malformed, outdated, or modified by same-origin scripts. Parse inside error handling and validate against a runtime schema before use; avoid storing secrets accessible to injected scripts.

Syntax

let parsed: unknown;
try { parsed = JSON.parse(localStorage.getItem('settings') ?? 'null'); }
catch { parsed = null; }
const settings = SettingsSchema.safeParse(parsed);

Key Points

  • Storage is not a trusted database
  • Version persisted schemas
  • XSS can access same-origin localStorage
Q97JavaScript architecture

When should you use promises, callbacks, or event emitters?

Interview question about when should you use promises, callbacks, or event emitters?.

Answer

Promises fit one eventual result; callbacks represent continuations or legacy APIs; event emitters represent repeated notifications. Choose based on lifecycle, cancellation, errors, and whether multiple values occur.

Syntax

Promise: one result
Callback: continuation
Emitter: event A → event B → event C

Key Points

  • Unsubscribe from event streams
  • Keep error conventions consistent
  • Async iterators can consume repeated events
Q98TypeScript advanced

How would you type a safe event emitter?

Interview question about how would you type a safe event emitter?.

Answer

Map event names to payload types and constrain emit calls so the payload corresponds to the selected event. Runtime code still needs listener storage and cleanup.

Syntax

type Events = { saved: { id: string }; failed: { message: string } };
type EventName = keyof Events;
function emit<K extends EventName>(name: K, payload: Events[K]) {}

Key Points

  • Types do not enforce runtime registration
  • Define listener cleanup
  • Keep type complexity proportional to need
Q99JavaScript async

How should a client handle request timeouts?

Interview question about how should a client handle request timeouts?.

Answer

Use a bounded deadline and abort the request when supported. Distinguish timeout from user cancellation; a client timeout does not prove the server did not complete a write.

Syntax

const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 5000);
try { return await fetch(url, { signal: controller.signal }); }
finally { clearTimeout(timer); }

Key Points

  • Client timeout does not roll back server work
  • Use idempotency for retryable writes
  • Prefer explicit timeout APIs
Q100JavaScript async

How do you handle a promise that never settles?

Interview question about how do you handle a promise that never settles?.

Answer

Apply a deadline, cancellation where supported, and monitoring for stuck operations. Promise.race can stop waiting at the caller, but it does not cancel the underlying operation by itself.

Syntax

const timeout = new Promise((_, reject) => setTimeout(() => reject(new Error('Timed out')), 5000));
await Promise.race([performOperation(), timeout]);

Key Points

  • A timeout race does not cancel the original task
  • Prefer AbortSignal-aware APIs
  • Clear timers and track abandoned operations

Share this question bank

Send this page to someone preparing for an interview.