javascript Interview Questions
Beginner Level13 questions
var = function-scoped & hoisted; let = block-scoped & reassignable; const = block-scoped & not reassignable.
== coerces types before comparing; === compares value AND type strictly.
undefined = not assigned yet; null = intentionally empty.
null === undefined → false (different types); null == undefined → true (special loose equality rule).
typeof [] is 'object'; use Array.isArray() to check for arrays.
Use Array.isArray() — it's the most reliable method.
NaN = failed math result; it's not equal to itself; use Number.isNaN() to check.
Functions without a name, used as callbacks or assigned to variables.
7 primitives (string, number, bigint, boolean, undefined, null, symbol) + object.
Backslash sequences (\n, \t, \") to represent special characters in strings.
break exits the loop entirely; continue skips current iteration.
Declarations move to top of scope; var = undefined, let/const = TDZ, functions = fully hoisted.
Primitives = copied (by value); Objects/arrays = shared reference (by reference).
Intermediate Level29 questions
Prints 0-5 because let creates a new scope per iteration; var would print 6 six times.
'b' prints first (sync), then 'a' after 2s (async via event loop).
Use async/await with a Promise-based delay to control execution order.
A function that remembers and accesses variables from its outer scope after it returns.
map transforms all elements; filter keeps only elements that pass a test.
forEach = side effects (no return); map = transform all; filter = select matching.
Reduces an array to a single value by accumulating results across elements.
Use Object.keys(obj).length — objects don't have .length directly.
Async result wrapper with 3 states: Pending → Fulfilled (.then) or Rejected (.catch).
Callbacks = passed functions; Promises = chainable objects with built-in error handling.
Promises = flat chaining + .catch(); async/await = promises that look like sync code.
Prints 'Something went wrong' — reject skips .then(), .catch() receives the error object.
Callbacks = functions passed as args; callback hell = deeply nested callbacks.
Promises flatten nesting with .then() chains, centralize errors with .catch(), and enable async/await.
Capturing = event goes DOWN to target; Bubbling = event goes UP from target. Default is bubbling.
preventDefault stops browser's default action; stopPropagation stops event from reaching parents.
Transforming f(a,b,c) into f(a)(b)(c) — each call takes one argument.
A function that executes immediately: (function(){ ... })() — creates private scope.
Functions that take functions as args or return functions (map, filter, reduce).
'this' depends on call context: object → that object, function → global/undefined, arrow → parent scope.
Arrow functions inherit 'this' from parent scope; normal functions get their own 'this'.
Caching function results by arguments to avoid repeated expensive computations.
Object.values(obj).forEach(val => console.log(val)) — simplest way.
Spread expands arrays/objects; Rest collects multiple args into one array. Same '...' syntax, opposite jobs.
Pure = same input → same output, no side effects. Impure = depends on or modifies external state.
Attach one listener to parent, use event.target to handle child events — works via bubbling.
Text data format. JSON.stringify = object→string; JSON.parse = string→object.
Create XHR → open(method, url) → onreadystatechange → send() — original async data fetching.
Shallow = top level only (nested shared); Deep = full independent clone. Use structuredClone() for deep.
Advanced Level28 questions
Node.js function that runs callback before any I/O or timers in next event loop tick.
'third' first (sync), then setTimeout/setImmediate order is non-deterministic in main module.
nextTick runs before event loop continues (highest priority); setImmediate runs in check phase after I/O.
a, b, e, d, c — await on setTimeout doesn't wait because it returns a number, not a Promise.
async marks a function as Promise-returning; await pauses it until a Promise resolves — both required together.
After 6s wait, 'second' prints immediately, then 'first' 10s later (~16s total).
Code that creates a function with name, parameters, and body — declared or expressed.
Objects inherit properties via a prototype chain — lookups walk up until null.
let/const, arrows, templates, destructuring, defaults, rest/spread, Promises, classes, modules, Symbol.
call = invoke with args; apply = invoke with array of args; bind = return new function with fixed 'this'.
localStorage (permanent), sessionStorage (tab), cookies (server-sent), IndexedDB (large data), Cache API (offline).
function* with yield — can pause/resume execution, returning values incrementally.
Object literal {}, constructor function with new, and Object.create(proto).
Methods inherited by all objects: hasOwnProperty, toString, valueOf + static methods like Object.keys.
Each method returns 'this', enabling obj.method1().method2().method3().
Recursive function that returns itself for arguments, and returns the total when called empty.
Shallow = top-level only; Deep = all levels cloned. Use structuredClone() for deep copies.
Use recursion to check if each element is an array and flatten accordingly.
Iterate and check existence in a Set; return first match.
Use .reduce() or recursion to accumulate the sum without loops.
Auto JSON, interceptors, timeout, progress tracking, works in Node+browser, rejects on HTTP errors.
Code that adds modern JS features to older browsers that lack native support.
Functions that take/return functions — master by writing polyfills for map, filter, reduce.
all = all succeed or fail fast; allSettled = wait for all; race = first to settle; any = first to succeed.
Property lookup walks up linked prototypes until found or null — this IS JavaScript inheritance.
Call Stack → Web APIs → Queues → Event Loop picks microtasks first, then macrotasks.
GEC created → memory phase (hoisting) → execution phase → function calls push FECs onto call stack.
Middleware for HTTP calls — run code before request is sent or before response is processed.
Coding Output Level9 questions
undefined — var hoists local 'a' to top of function as undefined, shadowing global 'a'.
3, 3, 3 — var shares one 'i'; callbacks run after loop ends when i=3. Fix: use let.
'object', 'undefined', 'number' — null is a bug, NaN is a numeric type.
'123' and '33' — string concatenation happens as soon as a string operand appears (left to right).
ReferenceError — { a: x } creates variable 'x' not 'a'; 'a' is just the property key.
All true — type coercion converts [], '', and false to 0. Always use === to avoid this.
Promise {1} — async functions always return a Promise; use await or .then() to unwrap.
ReferenceError — local let x shadows global x but is in Temporal Dead Zone before declaration.
start, end, promise, timeout — sync first, then microtasks (Promise), then macrotasks (setTimeout).
System Design Level21 questions
Generate short code (Base62/hash) → store in DB → redirect on access → cache popular URLs.
Debounce input → cancel old requests → cache results → trie/search backend → keyboard navigation.
IntersectionObserver on sentinel → fetch next page (cursor-based) → virtualize for performance.
WebSockets for real-time → server broadcasts to rooms → persist in DB → Redis for multi-server scale.
Token bucket or sliding window → Redis for distributed counting → 429 Too Many Requests + Retry-After.
Browser → CDN → App cache (Redis) with Cache-Aside pattern → TTL + event-based invalidation.
Paginate, select fields, debounce, cache (React Query), compress, batch requests.
Normalize data, add indexes, batch inserts, use transactions, connection pooling.
Vertical (bigger server) → Horizontal (read replicas, sharding, partitioning) + Redis cache.
Code split, lazy load, cache, compress, index DB, CDN, virtualize lists.
Event → queue → channel router (push/email/in-app) → deliver → track read status.
Chunk large files → resumable uploads → presigned URLs to S3 → progress bar → validate.
Inverted index → tokenize → rank (TF-IDF/BM25) → Elasticsearch/PostgreSQL FTS.
Bcrypt password → JWT (access + refresh tokens) → httpOnly cookies → RBAC middleware.
Distribute traffic across servers — Round Robin, Least Connections, Health Checks.
Publishers → Topics → Subscribers. Decouples services. Redis/RabbitMQ/Kafka.
B-Tree speeds up reads on WHERE/JOIN columns. Avoid on write-heavy or low-cardinality columns.
Single entry point — routing, auth, rate limiting, caching, logging for microservices.
Vertical = bigger server (limits exist); Horizontal = more servers (unlimited, complex).
1 query for list + N queries for related data = N+1. Fix with JOIN or DataLoader.
Independent services, own databases, communicate via APIs/queues, deploy separately.