Every question across every format, in one place.
Progress
0 / 658 completed
Showing 658 questions
Best Time to Buy and Sell Stock
Find the largest gain from one buy followed by one later sell in a price history.
Binary Search
Find a value's index in a sorted array in logarithmic time.
Binary Search Tree
Implement a binary search tree class with insert, lookup, delete, min/max and sorted iteration.
Binary Tree Traversals
Return the pre-order, in-order and post-order traversals of a binary tree.
Breadth-First Search
Find the fewest clicks between two pages of a site with breadth-first search.
Climbing Stairs
Count the ways to reach the top taking one or two steps at a time, the gentlest intro to DP.
Coin Change
Find the fewest coins (or credit packs) that add up exactly to an amount, using dynamic programming.
Combination Sum
List every multiset of values (reuse allowed) that adds up to a target, without duplicates.
Course Schedule
Decide whether a set of lessons with prerequisites can all be completed, by detecting cycles.
Depth-First Search
Traverse a graph depth-first from a start node and return the order nodes are visited.
Group Anagrams
Bucket words that are rearrangements of each other using a canonical hash key.
Heap Sort
Sort an array in place in guaranteed O(n log n) time using a binary max-heap.
House Robber
Pick non-adjacent items to maximise their total value, a classic 1-D dynamic programming problem.
Insert Interval
Add a new booking to a sorted list of busy blocks, merging where needed, in linear time.
Insertion Sort
Sort an array in place by growing a sorted prefix one element at a time.
Kth Largest Element
Find the k-th largest value without fully sorting, using a size-k heap or quickselect.
Binary Tree Level Order Traversal
Group a tree's values by depth, row by row, using breadth-first search.
Linked List
Implement a linked list class with insertion and removal at both ends, by index, and in-place reversal.
Longest Increasing Subsequence
Find the length of the longest strictly increasing subsequence, from O(n²) DP to O(n log n) patience sorting.
Longest Substring Without Repeating Characters
Find the length of the longest run of characters with no repeats using a sliding window.
Lowest Common Ancestor
Find the closest shared ancestor of two nodes in a DOM-like tree.
Maximum Subarray
Find the contiguous stretch with the largest sum using Kadane's algorithm.
Meeting Rooms II
Find the minimum number of rooms (or calendar columns) needed so no two overlapping meetings share one.
Merge Intervals
Collapse overlapping calendar events into the minimal set of busy blocks.
Merge Sort
Sort an array of numbers with the divide-and-conquer merge sort algorithm in O(n log n).
Min Heap
Implement a binary min-heap priority queue with a custom comparator.
Non-overlapping Intervals
Drop the fewest bookings so the remaining ones never overlap.
Number of Islands
Count connected regions of filled cells in a grid with flood fill.
Permutations
Generate every ordering of a list of distinct items with backtracking.
Product of Array Except Self
For each position, compute the product of every other element without using division.
Queue
Build a first-in, first-out queue class with O(1) enqueue and dequeue.
Quick Sort
Sort an array in place with quicksort, staying fast on sorted input and heavy duplicates.
Rotate Matrix
Rotate a square grid 90° clockwise in place, like rotating an image's pixel grid.
Selection Sort
Sort an array in place by repeatedly selecting the smallest remaining element.
Serialize and Deserialize a Binary Tree
Encode a binary tree as a string and rebuild an identical tree from it.
Sliding Window Maximum
Report the peak value in every window of k consecutive samples in O(n) with a monotonic deque.
Spiral Matrix
Read a rectangular grid in clockwise spiral order using shrinking boundaries.
Stack
Build a last-in, first-out stack class, the structure behind undo history and the call stack.
Subsets
Generate the power set of a list of distinct items, such as every combination of feature flags.
Top K Frequent Elements
Return the k most frequent values in a list, faster than sorting everything.
Topological Sort
Order modules so each one comes after everything it imports, and detect circular imports.
Trie
Build a prefix tree that powers autocomplete: insert words, look them up and list completions.
Two Sum
Find the two items in a list whose values add up to a target, in a single pass with a hash map.
Valid Parentheses
Check that every bracket in a code snippet is closed by the right kind, in the right order.
Validate Binary Search Tree
Check whether a binary tree satisfies the BST ordering rule across whole subtrees, not just parent and child.
Word Search
Check whether a word can be traced through adjacent letter tiles using backtracking.
Tell me about a failure and what you learned
Describe a real failure you were responsible for, how you handled the fallout and what changed in how you work afterwards.
Tell me about a time you changed your mind
Show that you hold strong opinions loosely: what evidence or argument changed your position, and how you handled the reversal publicly.
Tell me about a time you advocated for accessibility
Show how you made accessibility a team and organisation priority, not a one-off fix, and how you measured progress.
How do you handle burnout and keep a sustainable pace?
Explain how you spotted burnout on your team or in yourself, what you changed in planning and on-call, and how delivery held up.
Tell me about a time you delegated something important
Show how you hand off meaningful work, set up the person to succeed, and resist taking it back when it gets hard.
Tell me about delivering under a tight deadline
Show how you planned, cut risk and protected quality and people when a front-end delivery date could not move.
A disagreement with a product manager
Show how you handled a real conflict with product over scope, quality or approach, and reached a decision that served users and the business.
A disagreement with your manager
Describe pushing back on your own manager's decision, how you made your case, and how you committed once a decision was made.
Tell me about a time you drove alignment across multiple teams
Show how you got several teams with different priorities to agree on and deliver a shared front-end change.
Giving hard feedback
Describe delivering difficult feedback to a colleague, especially a strong or senior one, in a way that changed behaviour and kept trust.
Tell me about a time you had to deliver with unclear requirements
Show how you turned an ambiguous goal into a concrete plan by framing the problem, making assumptions explicit and learning quickly.
What is the hardest bug you have fixed?
Tell a debugging story that shows systematic investigation, technical depth and how you prevented the bug class from returning.
Influencing without authority
Show how you got other teams to adopt a front-end change you could not mandate, using evidence, low-friction paths and allies.
Tell me about a time you introduced a design system
Describe how you started or scaled a design system, partnered with design, drove adoption across teams and measured its value.
Tech lead, staff engineer or engineering manager: which track and why?
Explain the differences between the lead, staff and manager paths, and justify your own choice with evidence from your work.
Mentoring an underperforming engineer
Describe how you diagnosed why an engineer was struggling, set clear expectations, supported them and handled the outcome honestly.
Tell me about a time you negotiated scope cuts
Explain how you reshaped a front-end deliverable with product and design so it shipped on time without losing what users needed most.
How do you ramp up when you join or take over a new team?
Describe how you learned a new codebase, built trust and found your first high-impact contribution after joining or inheriting a team.
Tell me about a performance win with business impact
Walk through a web performance improvement you drove, how you tied Core Web Vitals to business metrics and how you kept the gains from regressing.
Prioritising tech debt against features
Explain how you made the business case for front-end tech debt work, balanced it with roadmap pressure and showed the payoff.
A production incident you owned
Walk through a front-end production incident: detection, mitigation, communication, root cause and the blameless follow-up that prevented a repeat.
Tell me about a project you led end to end
Walk through a front-end initiative you owned from problem framing to measured outcome, showing scope, trade-offs and how you led people.
Do you have any questions for me?
Use the last minutes of the interview to learn what you need to decide and to show how a lead thinks about a team.
Receiving critical feedback
Share a time you received tough feedback, how you processed it, what you changed and how you checked that the change stuck.
Walk me through an RFC or ADR you wrote
Explain a technical proposal you authored, how you framed the options, gathered feedback and drove it to a decision that held up.
Tell me about a time you said no to a stakeholder
Show how you push back on a senior stakeholder's request with data, offer alternatives and keep the relationship intact.
A technical decision you would make differently
Describe a significant front-end architecture decision that aged badly, how you recognised it and what you changed in how you decide.
Tell me about yourself (lead edition)
A two-minute career pitch that frames you as a front-end lead: scope, impact, how you lead and why this role is the next step.
Why are you leaving your current job?
Answer honestly and positively, framing the move around what you are moving towards, including tricky cases like layoffs or short tenures.
Why do you want to work here?
Give a specific, researched answer that connects the company's product and engineering challenges to your experience and goals.
How do you lead a remote or distributed team?
Explain how you keep a team spread across time zones aligned, unblocked and connected, with a concrete example of what you changed.
Array.prototype.at
Implement Array.prototype.at, including negative indices and the spec's integer coercion rules.
Array.prototype.concat
Implement Array.prototype.concat, including sparse arrays and Symbol.isConcatSpreadable.
Array.prototype.filter
Implement Array.prototype.filter with thisArg support and correct handling of sparse arrays.
Array.prototype.flat
Implement Array.prototype.flat with a depth argument, hole removal and an iterative variant.
Array.prototype.map
Implement Array.prototype.map, keeping holes in sparse arrays and supporting thisArg.
Array.prototype.reduce
Implement Array.prototype.reduce, including the no-initial-value rules and sparse arrays.
Array.prototype.square
Add a square() method to every array that returns a new array of squared values.
Async Queue with Priority
Run async tasks with a concurrency limit, starting higher-priority tasks first and keeping FIFO order within a priority.
Backbone Model
Build an observable Model class with defaults, get/set/unset, per-attribute change events, previous values and silent updates.
Cache Async (Deduplicate Requests)
Memoize an async function so concurrent calls share one in-flight promise, results expire after a TTL and failures are not cached.
Camel Case Keys
Deeply convert snake_case object keys from an API response into camelCase.
Cancellable Interval
Wrap setInterval so it returns a cancel function that stops future ticks.
Cancellable Timeout
Wrap setTimeout so it returns a cancel function instead of a timer id.
Chunk
Split an array into consecutive groups of a fixed size, with a shorter final group if needed.
Clamp
Restrict a number to an inclusive range between a lower and an upper bound.
classnames
Build a CSS class string from strings, numbers, nested arrays and conditional objects.
Compact
Return a new array with every falsy value removed.
Compose
Combine functions right to left into a single function, where each output feeds the next input.
Count By
Count how many elements of an array map to each key produced by an iteratee.
Curry
Turn a function of n arguments into one that can be called with those arguments one or several at a time.
Curry II (with placeholders)
Curry a function so that arguments can be supplied in any order using a placeholder value.
Data Merging
Merge workout session records by user: sum durations and combine equipment lists without duplicates.
Data Selection
Implement a small query function over an array of records: filtering, multi-key stable sorting, pagination and field projection.
Debounce
Delay invoking a function until a burst of calls has stopped for a given wait time.
Debounce II
Debounce with leading, trailing and maxWait options, plus cancel and flush.
Deep Clone
Make a deep copy of a JSON-like value so that no nested object or array is shared with the original.
Deep Clone II
Deep clone values with circular references, shared references, Date, RegExp, Map, Set, symbols and prototypes.
Deep Equal
Decide whether two JSON-like values are structurally equal, comparing nested objects and arrays by content.
Deep Map
Transform every leaf value in a nested object/array structure while preserving its shape.
Deep Merge
Recursively merge configuration objects without mutating the inputs, with clear rules for arrays and undefined.
Deep Omit
Remove the given keys from an object at every level of nesting, including inside arrays.
Dependency Injection Container
Build an IoC container with transient, singleton and scoped lifetimes, child scopes, overrides and circular-dependency detection.
Difference
Return the elements of an array that do not appear in any of the other given arrays.
Identical DOM Trees
Decide whether two DOM nodes are structurally identical: same tags, attributes, text and children, without using isEqualNode.
Drop Right While
Drop trailing elements of an array for as long as a predicate holds, scanning from the end.
Drop While
Drop leading elements of an array for as long as a predicate holds, then keep the rest.
Event Emitter
Implement an EventEmitter class with on, off and emit, the observer pattern behind Node's events module and DOM events.
Event Emitter II
Extend an event emitter with once, unsubscribe handles, bulk off and listener counts, with well-defined behaviour during emit.
Feature Flag Evaluator
Evaluate feature flags with a kill switch, targeting rules and a percentage rollout that uses stable hashing so users keep their bucket.
Fill
Overwrite a range of an array with a value, supporting negative start and end indices.
Find Index
Return the index of the first element that satisfies a predicate, starting from an optional index.
Find Last Index
Return the index of the last element that satisfies a predicate, searching backwards from an optional index.
Flatten
Flatten a nested array to a given depth, recursively or with an explicit stack.
From Pairs
Build an object from an array of [key, value] pairs, the inverse of Object.entries.
Function.prototype.apply
Implement Function.prototype.apply, including array-like argument lists and argument validation.
Function.prototype.bind
Implement Function.prototype.bind with partial application and correct behaviour under new.
Function.prototype.call
Implement Function.prototype.call without using call, apply or bind.
Get
Safely read a nested value from an object by a dot/bracket path, falling back to a default.
getElementsByClassName
Find every descendant element that has all of the given class names by walking the DOM tree yourself.
getElementsByStyle
Find descendant elements whose computed value for a CSS property equals a given value, normalising values like red vs #f00.
getElementsByTagName
Return every descendant element with a given tag name (or all of them for "*") by traversing the DOM tree.
Group By
Group the elements of an array into arrays keyed by the result of an iteratee.
Has
Check whether an object has an own property at a nested path, even when the value is undefined.
HTML Serializer
Turn a plain-object element tree into pretty-printed, correctly escaped HTML with indentation and void elements.
In Range
Check whether a number lies in a half-open range, with an optional start and swapped bounds.
instanceof
Re-implement the instanceof operator by walking the prototype chain.
Intersection
Return the unique values that appear in every one of the given arrays.
Is Empty
Decide whether a value is empty: no length, no size, or no own enumerable keys depending on its type.
jQuery Class Manipulation
Build a tiny $ wrapper with chainable addClass, removeClass, toggleClass and hasClass that work on every matched element.
jQuery CSS
Implement a $(selector).css() getter/setter that handles camelCase names, objects, automatic px units and removal.
JSON.parse (Lite)
Write a recursive-descent parser for JSON text that matches JSON.parse and throws SyntaxError on invalid input.
JSON.stringify
Reimplement JSON.stringify: escaping, undefined and function handling, toJSON, wrapper objects, cycles and BigInt errors.
List Format
Format a list of names into a readable sentence with options for sorting, de-duplication and an "and N others" cutoff.
LRU Cache
Implement a fixed-capacity cache that evicts the least recently used entry, with O(1) get and set.
Make Counter
Use a closure to build independent counters that remember their own state between calls.
Map Async
Map over a list with an async callback, running every call in parallel and keeping the results in input order.
Map Async with Limit
Map over a list with an async callback while never running more than a given number of calls at once.
Max By
Return the element whose iteratee value is largest, skipping elements that produce no comparable value.
Mean
Compute the arithmetic mean of an array of numbers, returning NaN for an empty array.
Memoize
Cache a function's results by argument so repeated calls with the same input skip the work.
Memoize II (multiple arguments)
Memoize a function of any number of arguments with a collision-free cache keyed on every argument.
Middlewares
Compose async middleware functions into one onion-style pipeline where each step can run code before and after next().
Min By
Return the element whose iteratee value is smallest, skipping elements that produce no comparable value.
new Operator
Re-implement the new operator: create the object, link the prototype, run the constructor.
Number of Arguments
Return how many arguments a function was called with, and explain arguments vs rest vs Function.length.
Object.create
Implement Object.create, including null prototypes and property descriptors.
Observable
Build a minimal Observable with subscribe, unsubscribe, teardown, of/from creators and pipeable map and filter operators.
Omit
Create a shallow copy of an object without the listed keys.
Once
Wrap a function so that it runs at most once and later calls return the first result.
Partial
Pre-fill some of a function's arguments, with placeholders for positions supplied later.
Pick
Create a new object containing only the listed keys of a source object.
Pipe
Chain functions left to right so data flows through them in reading order.
Promise.all
Implement Promise.all: resolve with every result in order, or reject on the first failure.
Promise.allSettled
Implement Promise.allSettled: wait for every input and report each outcome in order.
Promise.any
Implement Promise.any: fulfill with the first success, or reject with an AggregateError.
Promise Implementation
Build a Promises/A+-style MyPromise with then, catch, finally, chaining and thenable adoption.
Promise Pool
Build a concurrency-limited task queue: tasks can be added at any time and at most N run at once.
Promise.race
Implement Promise.race: settle the same way as the first input to settle.
Promise.reject
Implement Promise.reject and explain why it never unwraps promises or thenables.
Promise.resolve
Implement Promise.resolve, including promise pass-through and thenable adoption.
Promise Timeout
Wrap a promise so it rejects with a TimeoutError if it doesn't settle in time, without leaking timers.
Promise.withResolvers
Implement Promise.withResolvers to create a promise you can settle from outside its executor.
Promisify
Convert a Node-style callback function into one that returns a promise.
Promisify II
Extend promisify with a custom-implementation symbol, like Node's util.promisify.custom.
Pub/Sub Store (Mini Redux)
Implement createStore with getState, dispatch and subscribe: the core of Redux in about 50 lines.
Range
Generate an array of numbers from start up to, but not including, end with an optional step.
Range Right
Generate the same numbers as range(start, end, step) but in descending order of generation.
Retry with Backoff
Retry a failing async operation with exponential backoff and a predicate that decides which errors are worth retrying.
Run Async Tasks in Series
Run a list of async functions one after another, passing each result to the next and stopping at the first failure.
Set
Write a value at a nested path, creating missing objects and arrays along the way.
setInterval with setTimeout
Re-implement setInterval and clearInterval using only chained setTimeout calls.
Signals (Fine-Grained Reactivity)
Implement createSignal, createEffect, createMemo, batch and untrack with automatic dependency tracking and glitch-free updates.
Size
Return the size of a collection: length for arrays and strings, size for Map and Set, key count for objects.
Sleep
Write a promise-based sleep(ms) and explain why it pauses an async function but not the thread.
Spreadsheet Evaluator
Build a spreadsheet engine: parse cell formulas, evaluate references and ranges, recompute dependents on change and detect cycles.
Squash Object
Flatten a nested object into a single level whose keys are dot-separated paths.
String Repeat and Pad
Implement repeat, padStart and padEnd without the built-in string methods, matching their edge-case behaviour.
Table of Contents
Build a nested table of contents from the h1–h6 headings in a document, generating unique anchor ids and rendering it as nested lists.
Template Engine
Build a {{ }} interpolation engine with dotted paths, HTML escaping, raw {{{ }}} output, filters and a compile step.
Text Search Highlight
Wrap every case-insensitive match of the query words in <b> tags, merging overlapping and adjacent matches.
Throttle
Limit a function to at most one call per wait window, with leading and trailing calls.
Type Utilities
Write reliable checks for JavaScript's primitive types, including the null and boxed-value traps.
Type Utilities II
Write type checks for non-primitive values: arrays, functions, objects and plain objects.
Undo/Redo History
Implement an undoable value with past and future stacks, redo invalidation, no-op detection and a bounded history size.
Union By
Merge several arrays into one list of unique elements, where uniqueness is decided by an iteratee.
Unique Array
Remove duplicate values from an array while keeping the first occurrence of each, in order.
Query String Parse and Stringify
Parse a URL query string into an object (with repeated keys as arrays) and serialise it back, handling encoding, + as space and malformed input.
Virtual DOM Diff (Keyed Children)
Patch the real DOM from an old and a new virtual tree, reusing nodes by type and key and moving keyed children instead of recreating them.
Virtual DOM: createElement and render
Implement h() to build virtual DOM nodes and render() to turn them into real DOM, with attributes, styles, events and function components.
How do you abort a web request using `AbortController` in JavaScript?
Cancelling fetch with signals, timeouts, AbortSignal.any and cleaning up in effects.
How do you add, remove, and modify HTML elements using JavaScript?
createElement, append, replaceWith, remove, classList, fragments, templates and avoiding innerHTML XSS.
How do ARIA live regions work, and how do you announce dynamic updates reliably?
polite vs assertive, status and alert roles, aria-atomic, timing pitfalls and an announcer pattern.
What is the consequence of using array indices as the value for `key`s in React?
Why index keys move state and DOM to the wrong rows, and when they are safe.
What is async/await and how does it simplify asynchronous code?
Syntax over promises: sequential vs parallel awaits, error handling, top-level await and pitfalls.
How do you handle asynchronous data loading in React applications?
Server Components and loaders, query libraries, careful effects, Suspense and use().
What is the back/forward cache (bfcache), and what makes a page ineligible for it?
Instant back navigations, pageshow/pagehide, unload and other blockers, and how to test eligibility.
What are the benefits of using currying and partial application?
Reuse, configuration, composition and point-free pipelines, plus the costs.
What are the benefits of using hooks in React?
Reusable stateful logic, co-location by concern, and no classes.
Explain the concept of a callback function in asynchronous operations
Passing functions to be called later, error-first callbacks, callback hell and inversion of control.
Can you describe the main difference between a .forEach loop and a .map() loop and why you would pick one versus the other?
To understand the differences between the two, let's look at what each function does.
Can you explain the difference between coding a website to be responsive versus using a mobile-first strategy?
Note that these two approaches are not exclusive.
Can you give an example for destructuring an object or an array?
Destructuring is an expression available in ES6 which enables a succinct and convenient way to extract values of Objects or Arrays and place them into distinct
Can you give an example of a curry function and why this syntax offers an advantage?
Currying is a pattern where a function with more than one parameter is broken into multiple functions that, when called in series, will accumulate all of the re
Can you give an example of an @media property other than screen?
Yes, there are four types of @media properties (including screen):
How do you reliably determine whether an object is empty?
Own keys vs enumerable keys, symbols, prototypes, null and non-plain objects.
Explain the difference between classical inheritance and prototypal inheritance
Blueprint-copying classes vs live delegation to objects, and where JS classes fit.
What is clickjacking, and how do you defend against it?
UI redressing via invisible iframes, frame-ancestors vs X-Frame-Options, and legitimate embedding.
How can closures be used to create private variables?
The module/factory pattern for encapsulation, and how it compares to #private class fields.
Explain the concept of code coverage and how it can be used to assess test quality
Line, branch and function coverage, what they miss, and mutation testing.
What is code splitting in a React application?
Dynamic import, lazy and Suspense, route-level splitting and prefetching.
How do you decide where to code-split a large front-end app, and what can go wrong?
Route, component and vendor splitting, request waterfalls, chunk granularity and caching trade-offs.
What is the Command pattern and how is it used?
Encapsulating actions as objects for undo/redo, queues, macros and keyboard shortcuts.
What are some common security headers and their purpose?
CSP, HSTS, X-Content-Type-Options, Referrer-Policy, Permissions-Policy, COOP and friends.
What are the common pitfalls of using the `this` keyword?
Lost receivers, callbacks, nested functions, arrow methods on objects and class field trade-offs.
Explain the differences between CommonJS modules and ES modules in JavaScript
Static imports vs runtime require, live bindings, loading semantics, tree-shaking and interop in Node.
Consider HTML5 as an open web platform. What are the building blocks of HTML5?
- Semantics - Allowing you to describe more precisely what your content is.
How do you validate form elements using the Constraint Validation API?
Native form validation with ValidityState, setCustomValidity and accessible custom error UI.
How would you design and roll out a Content Security Policy for an existing production app?
Strict nonce-based CSP, strict-dynamic, report-only rollout, reporting, and the directives that matter.
What is the difference between controlled and uncontrolled React components?
Who owns the value, React state or the DOM, and the trade-offs of each.
How do you convert a Set to an array in JavaScript?
Spread, Array.from and when you might not need to convert at all.
What are the Core Web Vitals today, how are they measured, and what are the thresholds?
LCP, INP and CLS: what each one captures, the p75 thresholds, and lab vs field data.
When does the browser send a CORS preflight, and how do credentialed cross-origin requests work?
Simple vs preflighted requests, the response headers involved, credentials mode, caching preflights and debugging.
What are the most common misconceptions about CORS as a security mechanism?
Why CORS relaxes rather than adds protection, origin reflection bugs, null origins and what actually protects APIs.
Create a for loop that iterates up to 100 while outputting **"fizz"** at multiples of 3, **"buzz"** at multiples of 5 and **"fizzbuzz"** at multiples of 3 and 5.
Check out this version of FizzBuzz by Paul Irish.
Walk through the critical rendering path. What blocks rendering, and how do you shorten it?
HTML parsing, CSSOM, render-blocking vs parser-blocking resources, the preload scanner and first paint.
Compare CSR, SSR, SSG, ISR and streaming SSR. How do you choose a rendering strategy per page?
Trade-offs in TTFB, LCP, INP, freshness, cost and complexity, with a per-route decision framework.
What is CSRF, and is SameSite=Lax enough to prevent it in 2025?
How CSRF works, SameSite modes and browser defaults, same-site vs same-origin, and layered defences.
Provide some examples of how currying and partial application can be used
Practical uses: event handlers, loggers, validators, API clients and pipelines.
How do currying and partial application differ from each other?
Unary chains versus fixing some arguments once, with implementations of both.
How can you create custom error objects?
Subclassing Error with name, code and cause, and the instanceof caveats.
Explain the concept of debouncing and throttling
Run after activity stops versus at most once per interval, with implementations and use cases.
How do you debug React applications?
DevTools, the Profiler, Strict Mode, lint rules and production error reporting.
What is the Decorator pattern and how is it used?
Wrapping objects or functions to add behaviour, including higher-order functions and TC39 decorators.
Describe event bubbling.
When an event triggers on a DOM element, it will attempt to handle the event if there is a listener attached, then the event is bubbled up to its parent and the
Describe event capturing in JavaScript and browsers
The top-down phase of DOM event propagation and when listening in it is useful.
Describe what you like and dislike about the CSS preprocessors you have used.
- Mostly the advantages mentioned above.
What are design patterns and why are they useful?
Reusable solutions to recurring design problems and a shared vocabulary for teams.
How do you detect if JavaScript is disabled on a page?
noscript, the no-js class swap, the scripting media feature, and progressive enhancement.
Difference between document load event and document DOMContentLoaded event?
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes
How do you handle errors in asynchronous operations?
try/catch with await, .catch, unhandled rejections, fetch HTTP errors, aggregation and retries.
Explain the concept of error propagation in JavaScript
How errors unwind the call stack, flow through promise chains and reach global handlers.
What are event listeners and how are they used?
addEventListener options (capture, once, passive, signal), removal and memory hygiene.
Explain the event phases in a browser
Capture, target and bubble phases, eventPhase values, and how shadow DOM retargeting fits in.
Explain Ajax in as much detail as possible.
Ajax (asynchronous JavaScript and XML) is a set of web development techniques using many web technologies on the client side to create asynchronous web applicat
Explain event delegation
Event delegation is a technique involving adding event listeners to a parent element instead of adding them to the descendant elements. The listener will fire w
What is the event loop? Explain the difference between the macrotask and microtask queues.
How JavaScript schedules callbacks, promises and rendering on a single thread.
Explain Function.prototype.bind.
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any pro
Explain "hoisting".
Hoisting is a term used to explain the behavior of variable declarations in your code. Variables declared or initialized with the var keyword will have their de
Explain how JSONP works (and how it's not really Ajax).
JSONP (JSON with Padding) is a method commonly used to bypass the cross-domain policies in web browsers because Ajax requests from the current page to a cross-o
Explain how prototypal inheritance works
All JavaScript objects have a proto property with the exception of objects created with Object.create(null), that is a reference to another object, which is cal
Explain how this works in JavaScript
There's no simple explanation for this; it is one of the most confusing concepts in JavaScript. A hand-wavey explanation is that the value of this depends on ho
Explain the difference between mutable and immutable objects.
Immutability is a core principle in functional programming, and has lots to offer to object-oriented programs as well. A mutable object is an object whose state
Explain the difference between synchronous and asynchronous functions.
Synchronous functions are blocking while asynchronous functions are not. In synchronous functions, statements complete before the next statement is run. In this
Explain the same-origin policy with regards to JavaScript.
The same-origin policy restricts how a document or script from one origin can interact with resources from another origin. Two URLs have the same origin when th
Explain what a single page app is and how to make one SEO-friendly.
The below is taken from the awesome Grab Front End Guide, which coincidentally, is written by me!
What is the Factory pattern and how is it used?
Creating objects through a function that hides construction details.
What is the Flux pattern and what are its benefits?
Unidirectional actions, dispatcher and stores, and how Redux evolved from it.
How do you handle errors using try...catch blocks?
How try/catch works with sync and async code, and how to catch errors usefully.
What are some best practices for handling sensitive data in JavaScript?
What never belongs in the client, token storage, transport, logging and memory hygiene.
Have you ever used JavaScript templating? If so, what libraries have you used?
Yes. Handlebars, Underscore, Lodash, AngularJS, and JSX. I disliked templating in AngularJS because it made heavy use of strings in the directives and typos wou
Have you played around with the new CSS Flexbox or Grid specs?
Yes. Flexbox is mainly meant for 1-dimensional layouts while Grid is meant for 2-dimensional layouts.
How can you share code between files?
This depends on the JavaScript environment.
How do you organize your code? (module pattern, classical inheritance?)
In the past, I've used Backbone for my models which encourages a more OOP approach, creating Backbone models and attaching methods to them.
How does JavaScript garbage collection work?
Reachability, mark-and-sweep, generational collection and how front-end apps leak memory.
How do you create a constructor function?
Writing a constructor, putting methods on the prototype, guarding against missing new, and the class equivalent.
What causes Cumulative Layout Shift (CLS) and how do you fix it?
Session windows, the usual culprits (images, ads, fonts, injected banners) and how to debug shifts.
How do you find and fix a poor INP (Interaction to Next Paint)?
Input delay, processing time and presentation delay: finding the slow interaction and fixing each phase.
Your field LCP is 4.1 s on mobile. How do you diagnose and improve it?
Breaking LCP into TTFB, resource load delay, load duration and render delay, and fixing each part.
How does virtual DOM in React work? What are its benefits and downsides?
Render, diff with type and key heuristics, commit, and the costs of doing so.
How would you implement a web design comp that uses non-standard fonts?
Use @font-face and define font-family for different font-weights.
How does the native <dialog> element work, and what does showModal() give you over a custom modal?
Top layer, inertness, focus handling, Escape, ::backdrop, form method=dialog and remaining gaps.
Design an HTTP caching strategy for a web app: Cache-Control, ETag and stale-while-revalidate.
Immutable hashed assets, revalidated HTML, CDN vs browser caches, validators and common caching incidents.
How do you make an HTTP request using the Fetch API?
GET and POST with fetch, checking response.ok, timeouts and cancellation.
What changed from HTTP/1.1 to HTTP/2 to HTTP/3, and what does it mean for front-end delivery?
Multiplexing, HPACK/QPACK, head-of-line blocking, QUIC over UDP, and which old optimisations are now harmful.
How do iframes on a page communicate?
Cross-origin messaging with postMessage, origin checks and MessageChannel.
How do you safely embed untrusted content with iframe sandboxing?
sandbox tokens, the allow-scripts + allow-same-origin trap, separate origins, allow (Permissions Policy) and srcdoc.
How would you set up image optimisation for a large, image-heavy site?
Formats, responsive images, lazy loading, priority hints, image CDNs and governance at scale.
How do you import and export modules in JavaScript?
Named, default, namespace, re-export and dynamic imports, and live bindings.
Explain the concept of inheritance in ES2015 classes
extends, super, constructor rules, method overriding, statics and private fields in subclasses.
What is the difference between innerHTML and textContent?
How markup parsing, text nodes and innerText differ, and why textContent is the safe default.
Explain the concept of input validation and its importance in security
Server-side allowlist validation with schemas, versus output encoding, and why client checks are UX only.
Compare IntersectionObserver, ResizeObserver and MutationObserver. When would you use each?
What each observer watches, when callbacks run, performance characteristics and common pitfalls.
What is the Intl namespace object for?
Locale-aware formatting of numbers, dates, plurals, lists, collation and segmentation.
What is islands architecture, and how does it compare with full hydration and React Server Components?
Static HTML with isolated interactive islands, hydration directives, resumability, and when islands fit.
What are iterators and generators in JavaScript and what are they used for?
The iteration protocols, function*, lazy sequences, async iteration and iterator helpers.
What are the various data types in JavaScript?
The seven primitives plus objects, typeof quirks, and value vs reference semantics.
What are the different types of errors in JavaScript?
Built-in Error subclasses, DOMException, and useful ways to categorise failures.
What are modules and why are they useful?
Scope isolation, explicit dependencies, tree shaking and code splitting with ES modules.
What are some common performance bottlenecks in JavaScript applications?
Large bundles, long tasks, layout thrashing, memory leaks, network waterfalls and over-rendering.
What are some tools that can be used to measure and analyze JavaScript performance?
DevTools Performance panel, Lighthouse, RUM with web-vitals, bundle analysers and profilers.
What are some tools and techniques for identifying security vulnerabilities in JavaScript code?
Dependency audits, SAST, secret scanning, DAST, CSP reporting and code review in CI.
What are some tools that can be used for JavaScript testing?
The wider testing toolbox: runners, DOM utilities, mocking, browsers, visual, a11y and static checks.
Explain the concept of lazy loading and how it can improve performance
Deferring images, iframes, code and data until needed, and when not to.
Explain the concept of lexical scoping
Scope decided by where code is written, the scope chain, and how it enables closures.
When should you virtualise a long list, how does it work, and what does it cost you?
Windowing mechanics, variable heights, accessibility and find-in-page trade-offs, and alternatives like content-visibility.
How do you localize React applications?
Message catalogs, ICU MessageFormat, Intl, locale routing, RTL and translation workflow.
What is a long task, and what are the ways to break one up and yield to the main thread?
The 50 ms rule, setTimeout vs scheduler.yield vs postTask, isInputPending, Workers and the LoAF API.
What are some best practices for writing maintainable and effective tests in JavaScript?
Behaviour-focused, deterministic, readable tests that survive refactors.
Make this work:
Make this work:
How do you manipulate CSS styles using JavaScript?
Classes, custom properties, inline styles, computed styles and constructable stylesheets.
What are the differences between `Map`/`Set` and `WeakMap`/`WeakSet` in JavaScript?
Weakly held keys, garbage collection, non-iterability, and real use cases like caches and private data.
What is the difference between a `Map` object and a plain object in JavaScript?
Key types, ordering, size, prototype pitfalls, performance and serialisation compared.
How do memory leaks happen in long-lived SPAs, and how would you find one?
Detached DOM, forgotten listeners, timers, caches and closures, plus the heap-snapshot workflow.
What are mocks and stubs and how are they used in testing?
Test doubles: stubs, mocks, spies and fakes, plus network mocking with MSW.
What are the benefits of using a module bundler?
Graph resolution, transforms, minification, code splitting and cache-friendly output.
What are the metadata fields of a module?
import.meta.url, import.meta.resolve, host-specific fields and package.json module metadata.
What is the Module pattern and how does it help with encapsulation?
IIFE closures, revealing module, ES modules and private class fields for encapsulation.
What is the difference between `mouseenter` and `mouseover` event in JavaScript and browsers?
Why mouseenter does not bubble or fire for children, and when each is the right choice.
How do you reduce supply-chain risk from npm dependencies in a front-end codebase?
Typosquatting, compromised maintainers, install scripts, lockfiles, provenance and dependency governance.
What are JavaScript object getters and setters for?
Computed properties, validation and encapsulation with get/set, plus their performance and debugging trade-offs.
What is `Object.preventExtensions()` for?
Blocking new properties, and how it compares to Object.seal and Object.freeze.
Explain the Observer pattern and its use cases
Subjects notifying subscribers: event emitters, EventTarget, stores and their pitfalls.
How can you optimize DOM manipulation for better performance?
Batching reads and writes, fragments, delegation, virtualization and content-visibility.
How can you optimize network requests for better performance?
Fewer, smaller, earlier, cached and prioritised requests.
How would you optimize the performance of React contexts to reduce rerenders?
Stable values, split contexts, state/dispatch separation and selector-based stores.
Other Answers
- https://github.com/sudheerj/javascript-interview-questions
Explain the concept of partial application
Fixing some arguments of a function up front to create a more specific function.
What are the potential pitfalls of using closures?
Loop capture bugs, stale closures in React, retained memory and per-instance function costs.
What are some popular JavaScript testing frameworks?
Vitest, Jest, node:test, Testing Library, Playwright, Cypress and how they fit together.
Explain preload, prefetch, preconnect, dns-prefetch and modulepreload. When does each help or hurt?
Resource hints, speculation rules and 103 Early Hints, with the costs of over-hinting.
Explain the presentational vs container component pattern in React
Separating logic from view, and how hooks and headless libraries changed it.
How do you prevent the default behavior of an event?
preventDefault, cancelable events, passive listeners and when not to block defaults.
What is the difference between `event.preventDefault()` and `event.stopPropagation()`?
Cancelling the browser action vs stopping the event travelling, plus stopImmediatePropagation.
How can you prevent SQL injection vulnerabilities in JavaScript applications?
Parameterized queries, ORMs, query builders and least privilege on the Node.js side.
What are Progressive Web Applications (PWAs)?
Installable, offline-capable web apps built on a manifest, service worker and HTTPS.
How is `Promise.all()` different from `Promise.allSettled()`?
Fail-fast vs wait-for-everything, result shapes, and where any and race fit in.
Explain the different states of a Promise
Pending, fulfilled and rejected, what settled and resolved really mean, and why state is immutable.
What are JavaScript object property flags and descriptors?
writable, enumerable, configurable, accessor descriptors and how freeze/seal build on them.
Explain the concept of the Prototype pattern
Creating objects from existing ones: Object.create, prototype sharing and cloning.
What is the purpose of the finally block?
Cleanup that runs on every exit path, Promise.finally, override gotchas and using declarations.
What is the purpose of the `key` prop in React?
Keys give list items stable identity for reconciliation and state.
What is the purpose of the `new` keyword?
The four steps new performs, return-value rules, new.target and what cannot be constructed.
Explain the difference between `document.querySelector()` and `document.getElementById()`
Selector power vs a direct id lookup, scoping, live vs static collections and escaping.
What are Actions in React 19? Explain `useActionState` and `useFormStatus`
Async transitions for mutations with built-in pending, error and form-reset handling.
How has error handling changed in React 19?
Root error callbacks, de-duplicated logging, Action errors and boundaries.
How do refs work as a prop in React 19, and what are ref cleanup functions?
ref as a regular prop, the end of forwardRef, and callback ref cleanups.
What are some React anti-patterns?
Derived state, effect chains, nested component definitions, mutation and more.
What is the React Compiler and how does it change memoization?
Build-time automatic memoization, its reliance on the Rules of React, and adoption.
Explain the composition pattern in React
children, slots and compound components instead of inheritance and prop explosions.
What are some pitfalls about using context in React?
Re-render cascades, unstable values, overuse and missing providers.
What are some common pitfalls when doing data fetching in React?
Races, missing cleanup, waterfalls, missing caching and stale copies of server data.
What are error boundaries in React for?
Containing render errors with fallback UI, what they miss, and React 19 changes.
What is React Fiber and how is it an improvement over the previous approach?
Incremental, interruptible reconciliation with priorities, the basis of concurrent React.
What is `forwardRef()` in React used for?
Passing refs through components, and why React 19 makes ref a regular prop.
What are React Fragments used for?
Grouping children without extra DOM nodes, keyed fragments, and state preservation.
What are higher-order components in React?
Component-in, component-out wrappers, their conventions, and why hooks replaced most of them.
Explain what React hydration is
How React adopts server-rendered HTML and makes it interactive, and what changed in 18 and 19.
What causes hydration mismatch errors in React and how do you fix them?
Non-deterministic render, client-only APIs, locale, invalid nesting, and the fixes.
What is the difference between React Node, React Element, and a React Component?
Components produce elements; elements are one kind of renderable node.
Explain one-way data flow of React and its benefits
Props down, events up, one owner per piece of state.
What are React Portals used for?
Rendering into another DOM node while staying in the React tree for context and events.
What is reconciliation in React?
How React decides which instances to keep, update or remount, based on type, position and key.
What are render props in React and what are they for?
Function props that delegate rendering, and where they still beat hooks.
What are React Server Components and how do they differ from SSR?
Server-only components that ship no JS, the use client boundary, and how RSC complements SSR.
Explain server-side rendering of React applications and its benefits
Per-request HTML, hydration, streaming SSR and the trade-offs against CSR and SSG.
How do you decide between using React state, context, and external state managers?
Classify state as server, URL, local or shared, then pick the simplest fitting tool.
Explain static generation of React applications and its benefits
Build-time HTML on a CDN, its freshness limits, and ISR-style hybrids.
How does streaming server-side rendering with Suspense work in React?
Shell first, boundaries streamed later, and selective hydration on the client.
What is React Strict Mode and what are its benefits?
Development-only checks: double rendering, effect re-runs, ref checks and deprecation warnings.
What is React Suspense and what does it enable?
Declarative loading boundaries for lazy code, data, streaming SSR and selective hydration.
How does Suspense work for data fetching, and why doesn't it work with `useEffect`?
Suspense-enabled sources, render-as-you-fetch, and cached promises.
What does the `use` API do in React 19 and how is it different from other hooks?
Reading promises and context during render, conditional calls, and the cached-promise rule.
What is the `useCallback` hook in React and when should it be used?
Stable function identities, when they matter, and the React Compiler.
What is the `useId` hook in React and when should it be used?
SSR-safe unique ids for accessibility attributes, and why not for keys.
What is the `useMemo` hook in React and when should it be used?
Caching expensive calculations and stable identities, and when not to bother.
How does `useOptimistic` work in React 19?
Optimistic overlays on real state during Actions, with automatic revert.
What is the `useReducer` hook in React and when should it be used?
Centralized, testable state transitions with a pure reducer and stable dispatch.
What is the `useRef` hook in React and when should it be used?
A persistent mutable box for DOM nodes and values that don't affect rendering.
Explain `useTransition` and `useDeferredValue` and when to use each
Marking updates as non-urgent so concurrent React keeps input responsive.
How do you get the query string values of the current page in JavaScript?
Reading and updating query parameters safely with URLSearchParams and URL.
How would you build real-user performance monitoring (RUM) with PerformanceObserver?
Entry types, buffered observers, beaconing on visibilitychange, sampling, percentiles and segmentation.
How do you redirect to a new page in JavaScript?
location.assign vs replace, router navigation, server redirects and open-redirect safety.
Explain reflow (layout), repaint and compositing. How do you avoid layout thrashing and janky animations?
Which CSS changes trigger which pipeline stages, forced synchronous layout, will-change and layer costs.
requestAnimationFrame vs requestIdleCallback vs setTimeout: when does each run and what is each for?
Frame-aligned visual work, idle-time background work, deadlines, throttling in background tabs and alternatives.
How do you reset a component's state in React?
State follows type plus position; change the key or reset explicitly.
What are the rules of React hooks?
Top-level only, React functions only, why call order matters, and lint enforcement.
Explain the concept of scope in JavaScript
Global, module, function and block scope, the scope chain, shadowing and the temporal dead zone.
How can you implement secure authentication and authorization in JavaScript applications?
Session cookies vs tokens, OAuth/OIDC with PKCE, passkeys, and server-enforced authorization.
Explain the service worker lifecycle and caching strategies. How do you ship updates without breaking users?
install/waiting/activate, skipWaiting and clients.claim, cache-first vs network-first vs SWR, and update pitfalls.
How do Sets and Maps handle equality checks for objects?
SameValueZero and reference identity for object keys, and how to dedupe by value.
What are Sets and Maps and how are they used?
Unique-value collections and keyed collections with any key type, plus new Set methods.
What is the purpose of callback function argument format of `setState()` in React and when should it be used?
Updater functions compute next state from the latest queued state.
What is the difference between `setTimeout()`, `setImmediate()`, and `process.nextTick()`?
Where each callback lands in the Node.js event loop, and the browser equivalents.
Explain the concept of the Singleton pattern
One shared instance, why ES modules already give you one, and the testing downsides.
How do source maps work, and should you ship them to production?
Mappings, sourcesContent, hidden source maps, uploading to error trackers, and the security trade-offs.
What is the difference between state and props in React?
Props are inputs owned by the parent; state is memory owned by the component.
Explain the concept of the Strategy pattern
Swapping interchangeable algorithms behind one interface, often as a map of functions.
Why do my effects run twice in development, and how should I fix it?
Strict Mode's mount-unmount-mount check and how to write symmetric cleanups.
What is Subresource Integrity (SRI), and how do you manage the risk of third-party scripts?
Integrity hashes, crossorigin, why SRI doesn't fit evergreen tags, and isolation strategies for third parties.
Explain the concept of test-driven development (TDD)
Red-green-refactor, its benefits, costs and where it fits in front-end work.
How can you test asynchronous code in JavaScript?
Awaiting promises, asserting rejections, fake timers and waiting for UI updates.
How do you test React applications?
A layered strategy built on Testing Library, user-event, MSW and E2E tests.
Explain the concept of `this` binding in event handlers
this as currentTarget in listeners, arrows and bind, removing bound listeners and handleEvent objects.
Explain the concept of tree shaking in module bundling
Dead-code elimination of unused exports, side effects, and what defeats it.
What are Trusted Types, and how do they help eliminate DOM-based XSS?
Locking down injection sinks with CSP require-trusted-types-for, policies, default policies and rollout.
What are the different types of testing in software development?
Functional and non-functional test types and how they fit a front-end strategy.
What is the difference between `any`, `unknown` and `never` in TypeScript?
The escape hatch, the safe top type, and the empty bottom type.
What does `as const` do in TypeScript?
Const assertions for literal, readonly types and deriving unions from values.
What are assertion functions in TypeScript?
Functions that narrow by throwing: asserts condition and asserts value is T.
What are branded (nominal) types in TypeScript and why use them?
Phantom brands that stop same-shape values being mixed up and mark validated data.
How do access modifiers work in TypeScript classes, and how is `private` different from `#private`?
Compile-time vs runtime privacy, parameter properties, abstract and override.
What are conditional types and the `infer` keyword in TypeScript?
Type-level branching, pattern matching with infer, and distribution over unions.
What are `const` type parameters in TypeScript 5.0?
as const-style literal inference without caller ceremony.
What are `.d.ts` declaration files and when do you write them?
Types-only files for JS code, assets and globals, and how packages ship types.
What is declaration merging in TypeScript?
How interfaces, namespaces and enums merge, and how that powers global and module augmentation.
How do decorators work in TypeScript, and how do standard decorators differ from experimental ones?
TS 5.0 standard decorators vs legacy experimentalDecorators, and their use cases.
What are discriminated unions in TypeScript and how do you enforce exhaustive handling?
Tagged unions that make impossible states unrepresentable, checked with never.
What are distributive conditional types in TypeScript?
How conditional types map over unions, how to disable it, and the never trap.
Should you use enums or union literal types in TypeScript?
Runtime enums vs erasable unions, as const objects, and modern toolchain constraints.
What are excess property checks in TypeScript and when do they apply?
Why fresh object literals reject unknown keys, and when the check doesn't fire.
What are function overloads in TypeScript and when should you use them?
Multiple call signatures with one hidden implementation, and the alternatives.
How do you write generic React components in TypeScript?
Type parameters that connect props, tsx syntax quirks, and wrappers that lose generics.
Explain generics and generic constraints in TypeScript
Type parameters that preserve relationships, constraints, defaults, const and NoInfer.
What are index signatures in TypeScript and what are their pitfalls?
Dictionaries vs exhaustive Records, noUncheckedIndexedAccess, and when to use Map.
What is the difference between an interface and a type alias in TypeScript?
Declaration merging and extends vs unions, tuples and type-level computation.
Explain `keyof`, `typeof` and indexed access types in TypeScript
Deriving key unions, value types and property types from existing code.
What are mapped types in TypeScript and how does key remapping work?
Iterating keys to build types, modifiers, and as-based renaming and filtering.
What is module augmentation in TypeScript and when would you use it?
Extending library and global types with declare module and declare global.
How do you model immutability in TypeScript with `readonly`?
readonly modifiers, Readonly, readonly arrays and as const, and their limits.
How do you write recursive types in TypeScript, and what are their limits?
Trees, JSON and deep utilities, tail recursion, and compiler performance.
What does the `satisfies` operator do in TypeScript and how is it different from a type annotation or `as`?
Validate against a type while keeping precise inference.
What does `strict` mode enable in TypeScript, and which extra flags are worth turning on?
The strict family, noUncheckedIndexedAccess, exactOptionalPropertyTypes and migration strategy.
What is structural typing in TypeScript and what are its implications?
Compatibility by shape, excess property checks, and when you need nominal types.
What are template literal types in TypeScript and what are they useful for?
Building and parsing string literal types for handlers, routes and typed paths.
What are tuple types in TypeScript, including variadic and labeled tuples?
Fixed-position arrays, optional, rest and labeled elements, and variadic tuple types.
What is the difference between a type assertion and a type annotation in TypeScript?
Checking vs overriding the compiler, non-null assertions, and safer alternatives.
How does type narrowing work in TypeScript, and how do you write type guards?
Control-flow narrowing, user-defined and inferred type predicates, and assertion functions.
What are type-only imports in TypeScript and what does `verbatimModuleSyntax` do?
Why per-file transpilers need explicit type imports, and the modern tsconfig setup.
Do TypeScript types exist at runtime? How do you validate external data?
Type erasure, trust boundaries, schema validation and type stripping.
How do you type event handlers in React with TypeScript?
Synthetic event types, handler aliases, target vs currentTarget, and DOM listener types.
How do you type React component props in TypeScript?
Props types, ReactNode children, native element props, exclusive variants and React.FC.
How do you type refs in React with TypeScript, and what changed in React 19?
DOM refs, mutable refs, ref as a prop, imperative handles and callback ref cleanups.
How do you type `useReducer` state and actions in TypeScript?
Discriminated-union actions, exhaustive reducers and typed dispatch.
What are `using` declarations (explicit resource management) in TypeScript?
Scope-bound cleanup with Symbol.dispose, await using and DisposableStack.
Which built-in TypeScript utility types do you use most, and how do they work?
Partial, Pick, Omit, Record, ReturnType, Awaited and friends, plus their pitfalls.
Explain covariance, contravariance and invariance in TypeScript
How generic and function types relate under subtyping, strictFunctionTypes and in/out annotations.
Explain the difference between unit testing, integration testing, and end-to-end testing
Scope, speed, confidence and cost of each level, with front-end examples.
What does the dependency array of `useEffect` affect?
When effects re-synchronize, Object.is comparison, and stale closures.
What is the difference between `useEffect` and `useLayoutEffect` in React?
Effect timing relative to paint, and when blocking paint is worth it.
Explain the different ways the `this` keyword can be bound
Default, implicit, explicit and new binding, arrow functions, and the precedence between them.
What are the various ways to create objects in JavaScript?
Object literals, constructors, classes, Object.create, factories and structuredClone compared.
What are the different ways to make an API call in JavaScript?
fetch, XHR, sendBeacon, WebSocket, SSE and data-fetching libraries, and when to use each.
How do you load web fonts without hurting LCP and CLS?
font-display, preloading, subsetting, self-hosting, variable fonts and metric-matched fallbacks.
Explain the concept of the WebSocket API
Persistent full-duplex connections: handshake, client API, reconnection and auth concerns.
WebSockets vs Server-Sent Events vs long polling: how do you choose a real-time transport?
Directionality, infrastructure, reconnection, scaling and HTTP/2 implications for each real-time option.
What advantage is there for using the arrow syntax for a method in a constructor?
The main advantage of using an arrow function as a method inside a constructor is that the value of this gets set at the time of the function creation and can't
What are data- attributes good for?
Before JavaScript frameworks became popular, front end developers used data- attributes to store extra data within the DOM itself, without other hacks such as n
What are empty elements in HTML?
Empty elements in HTML are elements that do not contain any content between their opening and closing tags. Instead, they are self-closing tags, meaning they ha
What are JavaScript polyfills for?
Filling missing APIs in older environments, how polyfills differ from transpilation, and their costs.
What are Promises and how do they work?
Promise objects, chaining, error propagation, microtask scheduling and Promise.withResolvers.
What are proxies in JavaScript used for?
Intercepting object operations with traps and Reflect: validation, reactivity, logging and their limits.
What are server-sent events?
One-way streaming over HTTP with EventSource: format, reconnection, limits and alternatives.
What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?
Some examples of languages that compile to JavaScript include CoffeeScript, Elm, ClojureScript, PureScript, and TypeScript.
What are `Symbol`s used for in JavaScript?
Unique property keys, the global registry, and well-known symbols that hook into language behaviour.
What are the advantages and disadvantages of using Ajax?
- Better interactivity. New content from the server can be changed dynamically without the need to reload the entire page.
What are the advantages/disadvantages of using CSS preprocessors?
- CSS is made more maintainable.
What are the benefits of using spread syntax and how is it different from rest syntax?
ES6's spread syntax is very useful when coding in a functional paradigm as we can easily create copies of arrays or objects without resorting to Object.create,
What are the differences between ES6 class and ES5 function constructors?
Let's first look at an example of each:
What are the differences between variables created using let, var or const?
Variables declared using the var keyword are scoped to the function in which they are created, or if created outside of any function, to the global object. let
What are the different ways to visually hide content (and make it available only for screen readers)?
These techniques are related to accessibility (a11y).
What are the pros and cons of using Promises instead of callbacks?
- Avoid callback hell which can be unreadable.
What are the various clearing techniques and which is appropriate for what context?
- Empty div method - <div style="clear:both;"</div.
What are workers in JavaScript used for?
Dedicated, shared and service workers: off-main-thread work, messaging, transferables and limits.
What do you think of AMD vs CommonJS?
Both are ways to implement a module system, which was not natively present in JavaScript until ES2015 came along. CommonJS is synchronous while AMD (Asynchronou
What does a DOCTYPE do?
DOCTYPE is an abbreviation for Document Type. A DOCTYPE is always associated to a DTD - for Document Type Definition.
What does * { box-sizing: border-box; } do? What are its advantages?
- By default, elements have box-sizing: content-box applied, and only the content size is being accounted for.
Explain what happens when the `useState` setter function is called in React
Enqueue, schedule, batch, render, reconcile, commit, and the state snapshot.
What happens, end to end, when you type a URL into the browser and press Enter?
From URL parsing, HSTS and DNS through TLS, HTTP/2 or HTTP/3, caching, parsing and rendering.
What is a closure, and how/why would you use one?
A closure is the combination of a function and the lexical environment within which that function was declared. The word "lexical" refers to the fact that lexic
What is JSX and how does it work?
How JSX compiles to element-creating calls and the rules that follow.
What is progressive rendering?
Progressive rendering is the name given to techniques used to improve the performance of a webpage (in particular, improve perceived load time) to render conten
What is the use of `Promise.all()`
Running independent async work in parallel, fail-fast semantics and concurrency limits.
What does re-rendering mean in React?
Render vs commit, what triggers re-renders, and when they become a problem.
What is React? Describe the benefits of React
What React is, why teams choose it, and its honest trade-offs.
What is the CSS display property and can you give a few examples of its use?
- none, block, inline, inline-block, flex, grid, table, table-row, table-cell, list-item.
What is the definition of a higher-order function?
A higher-order function is any function that takes one or more functions as arguments, which it uses to operate on some data, and/or returns a function as a res
What is the difference between == and ===?
== is the abstract equality operator while === is the strict equality operator. The == operator will compare for equality after doing any necessary type convers
What is the DOM and how is it structured?
The live tree of nodes the browser builds from HTML, node types, and how it relates to rendering.
What is the extent of your experience with Promises and/or their polyfills?
Possess working knowledge of it. A promise is an object that may produce a single value sometime in the future: either a resolved value or a reason that it's no
What is "use strict";? What are the advantages and disadvantages to using it?
'use strict' is a statement used to enable strict mode to entire scripts or individual functions. Strict mode is a way to opt into a restricted variant of JavaS
What is virtual DOM in React?
An in-memory description of the UI that React diffs to update the real DOM.
What kind of things must you be wary of when designing or developing for multilingual sites?
- Use lang attribute in your HTML.
What language constructions do you use for iterating over object properties and array items?
- for-in loops - for (var property in obj) { console.log(property); }. However, this will also iterate through its inherited properties, and you will add an obj
What's a typical use case for anonymous functions?
They can be used in IIFEs to encapsulate some code within a local scope so that variables declared in it do not leak to the global scope.
What's the difference between an "attribute" and a "property"?
Attributes are defined on the HTML markup but properties are defined on the DOM. To illustrate the difference, imagine we have this text field in our HTML: <inp
What's the difference between .call and .apply?
Both .call and .apply are used to invoke functions and the first parameter will be used as the value of this within the function. However, .call takes in comma-
What's the difference between feature detection, feature inference, and using the UA string?
Feature detection involves working out whether a browser supports a certain block of code, and running different code depending on whether it does (or doesn't),
What's the difference between host objects and native objects?
Native objects are objects that are part of the JavaScript language defined by the ECMAScript specification, such as String, Math, RegExp, Object, Function, etc
What's the difference between inline and inline-block?
I shall throw in a comparison with block for good measure.
What tools and techniques do you use for debugging JavaScript code?
- Good old console.log debugging
When would you use document.write()?
document.write() writes a string of text to a document stream opened by document.open(). When document.write() is executed after the page has loaded, it will ca
Where should a browser app store JWTs or session tokens: localStorage, memory or cookies?
XSS vs CSRF exposure, HttpOnly cookies, in-memory access tokens with refresh rotation, and the BFF pattern.
Why is extending built-in JavaScript objects not a good idea?
Extending a built-in/native JavaScript object means adding properties/functions to its prototype. While this may seem like a good idea at first, it is dangerous
Why is it called a Ternary expression, what does the word "Ternary" indicate?
"Ternary" indicates three, and a ternary expression accepts three operands, the test condition, the "then" expression and the "else" expression. Ternary express
Why might you want to create static class members?
Static class members (properties/methods) are not tied to a specific instance of a class and have the same value regardless of which instance is referring to it
Why does React recommend against mutating state?
Reference equality, memoization, snapshots and concurrent rendering all assume immutability.
How do you use the window.history API?
pushState, replaceState, popstate and the building blocks of client-side routing.
What is the difference between the Window object and the Document object?
The global browsing-context object versus the DOM tree of the loaded page.
How do you write unit tests for JavaScript code?
Arrange-act-assert, testing behaviour not implementation, isolation and edge cases.
What are the differences between `XMLHttpRequest` and `fetch()` in JavaScript and browsers?
Promise-based fetch versus event-based XHR: errors, cancellation, streaming, progress and cookies.
Explain stored, reflected and DOM-based XSS. Does using React make you safe?
The three XSS classes, what JSX escaping does and doesn't cover, and defence in depth.
Analytics Event Pipeline and Client SDK
Design a product-analytics client SDK and event pipeline with a governed tracking plan, reliable delivery, consent and privacy, used by every team.
Autocomplete / Typeahead Component
Design a reusable, accessible autocomplete component with debounced search, caching, race handling and keyboard navigation.
Chat Application (e.g. Messenger)
Design a real-time web messenger with conversations, delivery and read receipts, typing indicators and offline support.
Collaborative Document Editor (e.g. Google Docs)
Design a real-time collaborative rich-text editor with presence, comments, offline edits and version history.
Collaborative Spreadsheet (e.g. Google Sheets)
Design a browser spreadsheet with a virtualized grid, formula engine, dependency graph and real-time co-editing.
Data Table / Data Grid Component
Design a reusable data table with sorting, filtering, pagination, selection, column resizing and virtualization.
Date Picker Component
Design an accessible, localised date and date-range picker with keyboard grid navigation, time zones and validation.
Design System at Scale
Design a company-wide design system (tokens, components, docs, tooling) consumed by dozens of teams across multiple frameworks and brands.
Collaborative Design / Drawing Tool (e.g. Figma, Canva)
Design a multiplayer vector canvas with an infinite viewport, shape editing, hit testing, cursors and undo.
Dropdown Menu Component
Design an accessible dropdown/action menu with submenus, typeahead, robust positioning and focus management.
E-commerce Marketplace (e.g. Amazon)
Design the front end of a large e-commerce site: search and listing, product detail, cart and checkout, with SEO and Core Web Vitals in mind.
Email Client (e.g. Outlook / Gmail)
Design a web email client: folders and threaded inbox, safe rendering of HTML emails, composer with drafts, offline and keyboard-driven workflows.
Embeddable Widget SDK (Third-Party Script)
Design a third-party embeddable widget and loader script that runs on thousands of customer sites, covering isolation, versioning, security and performance.
Feature Flag and Experimentation Platform
Design a feature-flag and A/B testing platform with targeting rules, client SDKs, real-time updates, exposure logging and governance.
Front-End Monorepo and CI Platform
Design the repository, build, test and CI/CD platform for 30 front-end teams sharing one monorepo, with affected builds, remote caching and governance.
Front-End Observability Platform (RUM, Errors, Tracing)
Design an org-wide front-end observability platform covering real user monitoring, error tracking with source maps, and distributed tracing.
Image Carousel Component
Design an accessible, performant image carousel with swipe, autoplay, lazy loading and responsive images.
Image Uploader Component
Design a multi-file image uploader with previews, client-side resizing, resumable direct-to-storage uploads and progress.
Localization Platform (i18n at Scale)
Design an org-wide localization platform: message format, extraction, translation workflow, delivery, runtime SDK, RTL and quality checks.
Micro-Frontend Platform
Design a platform that lets many teams build, deploy and compose independently released front-ends into one coherent product.
Modal Dialog Component
Design an accessible modal dialog: native dialog vs custom, focus trapping, scroll locking, stacking and API.
Music Streaming Web Player (e.g. Spotify)
Design a music web app with uninterrupted playback across navigation, a queue, gapless streaming, DRM and multi-device control.
News Feed (e.g. Facebook)
Design an infinitely scrolling, personalised social feed with posts, reactions, comments and live updates.
Offline-First PWA with Sync and Conflict Resolution
Design an offline-first progressive web app for field workers, covering local storage, background sync, conflict resolution and platform rollout.
Photo Sharing App (e.g. Instagram)
Design a photo-first social app: image feed, profile grid, upload with client-side processing, and likes and comments.
Pinterest (Masonry Image Feed)
Design a Pinterest-style home feed: a responsive masonry grid of variable-height pins with infinite scroll and virtualization.
Embeddable Poll Widget
Design a poll widget embeddable on many sites, with voting, live results, abuse prevention and isolation.
Real-Time Collaborative Whiteboard
Design a Miro/FigJam-style multiplayer whiteboard: canvas rendering at scale, CRDT-based sync, presence, offline, permissions and the multiplayer service.
Rich Text Editor Component
Design a reusable rich text editor: document model vs contenteditable, transactions, plugins, paste, IME and accessibility.
Travel Booking Site (e.g. Airbnb)
Design a stays marketplace: search with map and date range, listing details, availability calendar and a reliable booking flow.
Video Conferencing App (e.g. Zoom, Google Meet)
Design a browser video meeting app with WebRTC, an SFU, simulcast, adaptive layouts, screen sharing and chat.
Video Streaming Service (e.g. Netflix)
Design a Netflix-style web client: browse rows of titles, a video player with adaptive bitrate streaming, DRM, and resume playback.
Accordion
Build an accessible accordion with expandable sections and full keyboard support.
Accordion II: Single Open, Controlled
Extend an accordion so only one section is open at a time, with optional collapsing and a controlled API.
Analog Clock
Draw a ticking analog clock in SVG with correctly rotated hour, minute and second hands and an accessible name.
Auth Code Input
Build a one-time-code input split into digit boxes with auto-advance, backspace, arrow keys and paste support.
Autocomplete / Typeahead
Build an accessible combobox that searches an async API with debouncing, caching and race-condition handling.
Birth Year Histogram
Bucket a list of birth years into a bar-chart histogram with adjustable bucket size and an accessible data-table view.
Connect Four
Build Connect Four with gravity drops, last-move win detection, column-based keyboard controls and announced moves.
Contact Form
Build a contact form with accessible inline validation, a submitting state and a success message.
Data Table
Build a paginated users table with a rows-per-page selector and previous/next navigation.
Data Table II: Sorting and Filtering
Add sortable column headers and a search filter to a paginated users table.
Data Table III: Generic Columns
Turn a users-only table into a reusable DataTable driven by column definitions with renderers, sorting and typed filters.
Date Picker
Build a date input with a calendar dialog following the WAI-ARIA date picker pattern: grid keyboard navigation, focus trap and return.
Dice Roller
Roll a chosen number of six-sided dice, draw each face with CSS pips and announce the total accessibly.
Digital Clock
Build a ticking digital clock that stays aligned to real seconds, with a 12/24-hour toggle and clean timer teardown.
Drag-and-Drop Sortable List
Build a reorderable list with pointer dragging and a full keyboard alternative: pick up, move, drop or cancel, with announcements.
Dropdown Menu
Build an accessible menu button: open and close, arrow-key and typeahead navigation, outside click and focus return.
File Explorer
Render a nested folder/file tree where folders expand and collapse, sorted folders-first.
File Explorer II: Keyboard Tree
Turn a file explorer into a WAI-ARIA tree view with roving focus, arrow-key navigation and type-ahead.
Flight Booker
Build a one-way or return flight form with date constraints, disabled states and a booking confirmation.
Generate Table
Generate a numbered table from row and column inputs, filled row by row, column by column or in a snake pattern.
Grid Lights
Build a grid of toggle lights that, once all are lit, switch off one by one in reverse activation order.
Hello World Counter
Build a counter with increment, decrement and reset that never drops below zero and announces its value.
Holy Grail Layout
Build the classic header, three columns and footer layout with CSS Grid, landmarks, a sticky footer and responsive stacking.
Image Carousel
Build an accessible image carousel with previous/next controls, wrap-around and dot navigation.
Image Carousel II: Infinite Transitions
Extend the image carousel with sliding animations that loop seamlessly in both directions.
Infinite Scroll Feed
Build a cursor-paginated feed that loads more posts as you scroll, with abort handling, retries and the ARIA feed pattern.
Job Board
Build a paginated job board on a Hacker News-style API: fetch ids, then load job details in parallel pages.
Kanban Board
Build a kanban board with normalised state, adding and deleting cards, and moving cards between columns by pointer or keyboard.
Like Button
Build a toggle Like button that talks to a flaky API, with pending, error and accessible pressed states.
Memory Game
Build a card-matching memory game with timed flip-back, move counting and screen-reader friendly announcements.
Modal Dialog
Build a reusable modal dialog with a portal, labelled dialog semantics, Escape and backdrop dismissal, and focus restoration.
Mortgage Calculator
Calculate the monthly payment, total cost and total interest of a fixed-rate loan as the user types.
Multi-step Form Wizard
Build a three-step sign-up wizard with per-step validation, a progress indicator, focus management and a review step.
Nested Checkboxes
Build a checkbox tree where parents reflect their children as checked, unchecked or indeterminate.
Pixel Art Editor
Build a 16×16 pixel-art editor with a colour palette, draw/erase tools, click-and-drag painting and keyboard drawing.
Progress Bar
Build a reusable, accessible progress bar that clamps its value and shows the percentage.
Progress Bars
Each click adds a progress bar that fills from 0 to 100% over two seconds, driven by requestAnimationFrame.
Progress Bars II: Concurrency Limit
Extend the progress bars so at most three fill at once while the rest wait in a queue.
Progress Bars III: Pause and Resume
Queue-limited progress bars that can be paused and resumed without losing progress, driven by one shared clock.
Selectable Cells (Drag Select)
Build a grid where dragging selects a rectangle of cells, with modifier-key multi-select and a full keyboard equivalent.
Sign-up Form Validation
Build a sign-up form with on-blur validation, a live password checklist, cross-field checks and a show-password toggle.
Star Rating
Build a star rating input with hover preview, keyboard support and a clear button, built on native radios.
Stopwatch
Build an accurate stopwatch with start, stop, lap and reset, based on timestamps rather than counting ticks.
Tabs
Build a tabs component that shows one panel at a time, with the correct tab roles and selected state.
Tabs II: Keyboard Accessible
Add roving tabindex, arrow-key navigation and automatic or manual activation to a tabs component.
Temperature Converter
Two linked inputs, Celsius and Fahrenheit, that update each other and handle invalid input gracefully.
Tic-tac-toe
Build a two-player tic-tac-toe game with win and draw detection, a live status and a keyboard-navigable board.
Tic-tac-toe II: N × N, M in a Row
Generalise tic-tac-toe to a configurable N × N board where M marks in a row win, with an efficient last-move win check.
Toast Notifications
Build a toast system with a context API, live-region announcements, auto-dismiss that pauses on hover or focus, and a visible limit.
Todo List
Build a todo list with add, complete, delete and filters, using semantic forms and good focus management.
Tooltip and Popover
Build an accessible hover/focus tooltip and a click-triggered popover, and explain when to use each.
Traffic Light
Build a traffic light that cycles through configurable states with timers, a pause control and clean effect teardown.
Transfer List
Move checked items between two lists with per-list select-all and bulk transfer controls.
Tweet Card
Build a social post card with semantic markup, relative timestamps, compact counts and accessible action buttons.
Users Database (CRUD)
Build a small users database with search, a keyboard-accessible listbox, and create, update, delete and cancel actions.
Virtualized List
Render a 10,000-row list smoothly by windowing: only the visible rows plus overscan are in the DOM.