Questions 181–200 of 200 · 0 of 20 on this page marked learned
181.javascript-0181Mediummid
How would you write safe date utilities: add days or months, count the days between two dates, and skip weekends?
Do calendar math in UTC, or on date-only values, so daylight saving changes cannot shift results. Add days with setUTCDate, clamp the day of month when adding months, count days by dividing the difference of UTC midnights by 86,400,000 and rounding, and skip weekends by checking getUTCDay. Never divide a local time difference by 24 hours.
Full answer
Date bugs come from three sources: time zones, daylight saving time (DST), and month lengths.
Rules that keep utilities correct:
Decide whether the value is an instant (a moment in time) or a calendar date (a day with no time, like a birthday). For calendar dates, store YYYY-MM-DD, parse it as UTC parts with Date.UTC(y, m - 1, d), and use the getUTC* and setUTC* methods. A date-only string such as '2026-03-08' is parsed as UTC by Date.parse, but new Date(2026, 2, 8) uses local time, which is a common mix-up.
Add days with setUTCDate(getUTCDate() + n). The engine handles month and year overflow. Do not add n * 86400000 to a local date, because a local day can be 23 or 25 hours long.
Add months by setting the month, then clamping the day. Adding one month to January 31 should give the last day of February, not March 3, which is what the overflow of setMonth does.
Count days between two calendar dates: take both as UTC midnights, divide the difference by 86,400,000 and Math.round. Using Math.floor or ceil on instants across a DST change gives off-by-one results.
Business days: loop day by day and skip when getUTCDay() is 0 or 6, or compute it with weeks times five plus the remainder. Holidays need a calendar list passed as input.
Format with toISOString().slice(0, 10) for UTC, or Intl.DateTimeFormat with an explicit timeZone when showing instants to users.
Always make functions pure: return a new Date and do not mutate the argument. Inject now for tests.
Validate input: Number.isNaN(date.getTime()) detects an invalid date, and new Date(2026, 1, 31) silently becomes March 3.
For anything beyond this (recurrence rules, other calendars, zones), use Intl, the Temporal API where available, or a tested library.
javascript
const DAY = 86400000;
const parse = (iso) => {
const [y, m, d] = iso.split('-').map(Number);
return new Date(Date.UTC(y, m - 1, d));
};
const format = (date) => date.toISOString().slice(0, 10);
function addDays(date, n) {
const copy = new Date(date);
copy.setUTCDate(copy.getUTCDate() + n);
return copy;
}
function addMonths(date, n) {
const day = date.getUTCDate();
const result = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + n, 1));
const lastDay = new Date(Date.UTC(result.getUTCFullYear(), result.getUTCMonth() + 1, 0)).getUTCDate();
result.setUTCDate(Math.min(day, lastDay));
return result;
}
const daysBetween = (a, b) => Math.round((b - a) / DAY);
const isWeekend = (date) => [0, 6].includes(date.getUTCDay());
function addBusinessDays(date, n, holidays = new Set()) {
let current = new Date(date);
let left = Math.abs(n);
const step = n < 0 ? -1 : 1;
while (left > 0) {
current = addDays(current, step);
if (!isWeekend(current) && !holidays.has(format(current))) left--;
}
return current;
}
const isLeapYear = (year) => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
const startOfWeekMonday = (date) => addDays(date, -((date.getUTCDay() + 6) % 7));
console.log(format(addDays(parse('2026-12-30'), 5)), format(addDays(parse('2026-03-01'), -1)));
console.log(format(addMonths(parse('2026-01-31'), 1)), format(addMonths(parse('2024-01-31'), 1)), format(addMonths(parse('2026-11-15'), 3)), format(addMonths(parse('2026-03-31'), -1)));
console.log(daysBetween(parse('2026-01-01'), parse('2026-12-31')), daysBetween(parse('2026-03-09'), parse('2026-03-08')));
console.log(format(addBusinessDays(parse('2026-12-04'), 1)), format(addBusinessDays(parse('2026-12-04'), 5)), format(addBusinessDays(parse('2026-12-07'), -1)));
console.log(format(addBusinessDays(parse('2026-12-23'), 3, new Set(['2026-12-25']))));
console.log(isLeapYear(2024), isLeapYear(2100), isLeapYear(2000), format(startOfWeekMonday(parse('2026-12-06'))));
const naiveMonth = new Date(Date.UTC(2026, 0, 31));
naiveMonth.setUTCMonth(naiveMonth.getUTCMonth() + 1);
console.log('naive setMonth overflow:', format(naiveMonth));
console.log('invalid date check:', Number.isNaN(new Date('2026-13-45').getTime()), '| silent overflow:', format(new Date(Date.UTC(2026, 1, 31))));
const midnightBefore = Date.parse('2026-03-08T05:00:00Z');
const midnightAfter = Date.parse('2026-03-09T04:00:00Z');
const hours = (midnightAfter - midnightBefore) / 3600000;
console.log('New York, 8 March to 9 March 2026 is', hours, 'hours:', 'floor gives', Math.floor(hours / 24), 'days, round gives', Math.round(hours / 24));
const fmt = new Intl.DateTimeFormat('en-US', { timeZone: 'America/New_York', dateStyle: 'medium', timeStyle: 'short' });
console.log(fmt.format(midnightBefore), '->', fmt.format(midnightAfter));
Run with Node.js v24.22.1 as js-181.js; two runs gave identical output.
Output:
2027-01-04 2026-02-28
2026-02-28 2024-02-29 2027-02-15 2026-02-28
364 -1
2026-12-07 2026-12-11 2026-12-04
2026-12-29
true false true 2026-11-30
naive setMonth overflow: 2026-03-03
invalid date check: true | silent overflow: 2026-03-03
New York, 8 March to 9 March 2026 is 23 hours: floor gives 0 days, round gives 1
Mar 8, 2026, 12:00 AM -> Mar 9, 2026, 12:00 AM
Key points
Separate instants from calendar dates; do calendar math in UTC.
Add days with setUTCDate; clamp the day when adding months.
Count days between UTC midnights and round, never divide local times by 24 hours.
Skip weekends with getUTCDay; holidays need an input list.
Return new dates, validate input, and inject now for tests.
Common mistakes
Dividing a local time difference by 24 hours and flooring the result.
Using setMonth on the 31st and landing in the next month.
Mixing local constructors and date-only string parsing.
Mutating the date that was passed in.
Follow-ups
How would the business day function change for a custom weekend?
How would Temporal's PlainDate make this simpler?
How do you show an instant in the user's time zone?
Tips
Ask whether the value is an instant or a calendar date.
Name the DST case that breaks the 24-hour division.
Keep utilities pure and testable with an injected clock.
182.javascript-0182Mediummid
How do you implement a shallow equality check, and why do UI libraries use it for change detection instead of deep comparison?
A shallow equal compares two objects by their own keys and the Object.is result of each value, without looking inside nested objects. It is fast, linear in the number of keys, and works when state is updated immutably, because a changed nested value gets a new reference. Deep equality costs more and can be wrong for cycles, functions, and special objects.
Full answer
Shallow equality answers: are these two objects made of the same values at the first level? Implementation steps:
If Object.is(a, b), return true. It handles the same reference, NaN, and distinguishes +0 from -0.
If either is not an object or is null, return false.
Compare the number of own enumerable keys.
For each key of a, check that b has it as its own property (Object.hasOwn) and that Object.is(a[key], b[key]). The own property check matters when a value is undefined.
Why libraries use it: React's memo, PureComponent, and selector libraries compare props or state by reference at the first level. With immutable updates, a change at any depth creates new objects along the path, so a different reference at the top means something changed, and the same reference means nothing did. Cost is O(keys) and does not depend on data size. Deep equality is O(size of data), can run on every render, and has hard cases: circular references, Date, Map, Set, class instances, functions, and getters.
Traps:
Inline objects, arrays, and functions in props are new references each render, so shallow comparison always fails. Memoize them with useMemo or useCallback, or move them out of the component.
Mutating state keeps the same reference, so shallow equality reports no change and the UI does not update.
Arrays need the same rule: same length and same items by Object.is.
Key order does not matter for objects.
Prototype and non-enumerable properties are ignored.
A related tool is memoizing the last call: remember the previous arguments and result, and return the result if all arguments are shallow equal. It is cheap and avoids unbounded caches.
Run with Node.js v24.22.1 as js-182.js; two runs gave identical output.
Output:
same values: true
nested copy is different: false
NaN: true | +0 and -0: false
undefined vs missing: false false
arrays: true false
primitives and null: true false true
mutation looks unchanged: true
immutable update detected: true | untouched branch kept: true
calls with equal props reuse the result, total real calls: 2
inline functions defeat it: false | stable function: true
Key points
Compare own keys and Object.is of each value; do not recurse.
Use Object.hasOwn so undefined values are not confused with missing keys.
Works with immutable updates: a changed nested value changes the references above it.
Inline objects and functions defeat shallow comparison; mutation hides changes from it.
Deep equality is costlier and has edge cases such as cycles and special objects.
Common mistakes
Mutating state and expecting a change to be detected.
Creating new object or function props on every render and wondering why memo does nothing.
Treating a missing key and a key set to undefined as the same.
Reaching for deep equality when immutable updates and shallow checks would be cheaper.
Follow-ups
When is deep equality the right choice?
How does useMemo relate to shallow comparison of dependencies?
How would you compare two Maps or Sets?
Tips
Say what the check includes and what it skips.
Link it to immutable updates; it only works with them.
Name inline props as the usual reason that memo fails.
183.javascript-0183Mediummid
How do you read a form with FormData and validate it, and what are the common traps with checkboxes, multiple values, and disabled fields?
new FormData(form) collects the successful controls, so unchecked checkboxes, disabled fields, and fields without a name are missing. Use getAll for repeated names because Object.fromEntries keeps only the last value, convert types yourself, and trim text. For validation, combine the built-in constraint API (checkValidity, validity, setCustomValidity) with custom checks and show messages next to the fields.
Full answer
new FormData(form) builds the same data the browser would submit. It includes controls that have a name and are not disabled. Unchecked checkboxes and radios are left out, and a select multiple gives one entry per selected option. File inputs give File objects. Submit buttons are included only if you pass the submitter as the second argument.
Reading the data:
formData.get('name') returns the first value as a string or file, or null if missing. getAll('tags') returns an array.
Object.fromEntries(formData) is a quick way to get an object, but repeated names collapse to the last value. Build the object in a loop and use getAll for fields that can repeat.
Values are strings, so convert numbers (Number(value)), dates, and booleans yourself. An unchecked checkbox is missing, so use formData.has('agree') to get a boolean.
Trim text before validating, and do not trust client values on the server.
Validation layers:
Built-in constraints in HTML: required, type="email", pattern, min, max, minlength. form.checkValidity() and input.validity (valueMissing, typeMismatch, patternMismatch, rangeUnderflow) read them in JavaScript. input.setCustomValidity('message') adds a custom error, and an empty string clears it.
Custom rules for cross-field logic, such as password confirmation.
Show errors near the field, link them with aria-describedby, set aria-invalid, move focus to the first invalid field, and use novalidate on the form if you want your own messages for all rules.
Listen to the submit event on the form (not the click of the button), call preventDefault() when you handle it yourself, and use event.submitter to know which button was used.
Do not forget to rerun the same validation on the server, since the client can be bypassed.
javascript
document.body.innerHTML = `
<form id="signup" novalidate>
<input name="email" type="email" required value="asha@example.com">
<input name="age" type="number" min="18" max="99" value="17">
<input name="password" type="password" required value="secret123">
<input name="confirm" type="password" value="secret124">
<input type="checkbox" name="interests" value="js" checked>
<input type="checkbox" name="interests" value="css" checked>
<input type="checkbox" name="interests" value="sql">
<input type="checkbox" name="agree">
<input name="nickname" value="hidden one" disabled>
<input value="no name given">
<select name="plan"><option value="free">Free</option><option value="pro" selected>Pro</option></select>
<button name="action" value="save">Save</button>
</form>`;
const form = document.getElementById('signup');
const data = new FormData(form);
console.log('entries:', JSON.stringify([...data.entries()]));
console.log('fromEntries loses repeats:', JSON.stringify(Object.fromEntries(data).interests));
console.log('getAll:', data.getAll('interests'), '| has agree:', data.has('agree'), '| get missing:', data.get('agree'));
function readForm(formElement) {
const formData = new FormData(formElement);
return {
email: String(formData.get('email') ?? '').trim().toLowerCase(),
age: Number(formData.get('age')),
interests: formData.getAll('interests'),
agree: formData.has('agree'),
plan: formData.get('plan'),
password: formData.get('password'),
confirm: formData.get('confirm'),
};
}
function validate(formElement) {
const values = readForm(formElement);
const errors = {};
for (const field of formElement.elements) {
if (!field.name || field.disabled) continue;
field.setCustomValidity('');
}
if (values.password !== values.confirm) formElement.elements.confirm.setCustomValidity('Passwords do not match');
for (const field of formElement.elements) {
if (!field.name || field.disabled || field.willValidate === false) continue;
if (!field.checkValidity()) {
const flags = Object.keys(Object.getPrototypeOf(field.validity)).filter((key) => key !== 'valid' && field.validity[key]);
errors[field.name] = flags.join(',') + (field.validationMessage && flags.includes('customError') ? ': ' + field.validationMessage : '');
}
}
if (!values.agree) errors.agree = 'terms must be accepted (custom rule)';
return { values, errors };
}
const result = validate(form);
console.log('values:', JSON.stringify(result.values));
console.log('errors:', JSON.stringify(result.errors));
form.elements.age.value = '30';
form.elements.confirm.value = 'secret123';
form.elements.agree.checked = true;
form.elements.email.value = 'not-an-email';
console.log('after fixes:', JSON.stringify(validate(form).errors));
form.elements.email.value = 'ben@example.com';
console.log('all good:', JSON.stringify(validate(form).errors), '| form.checkValidity():', form.checkValidity());
const submitterData = new FormData(form, form.querySelector('button'));
console.log('with the submitter:', submitterData.get('action'), '| without:', new FormData(form).get('action'));
Written for a browser console or script tag; checked here with Node.js v24.22.1 and jsdom, two runs with identical output.
Output:
entries: [["email","asha@example.com"],["age","17"],["password","secret123"],["confirm","secret124"],["interests","js"],["interests","css"],["plan","pro"]]
fromEntries loses repeats: "css"
getAll: [ 'js', 'css' ] | has agree: false | get missing: null
values: {"email":"asha@example.com","age":17,"interests":["js","css"],"agree":false,"plan":"pro","password":"secret123","confirm":"secret124"}
errors: {"age":"rangeUnderflow","confirm":"customError: Passwords do not match","agree":"terms must be accepted (custom rule)"}
after fixes: {"email":"typeMismatch"}
all good: {} | form.checkValidity(): true
with the submitter: save | without: null
Key points
FormData has only named, enabled, successful controls; unchecked checkboxes are absent.
Use getAll for repeated names; Object.fromEntries keeps the last one.
All values are strings; convert and trim them yourself.
Use the constraint validation API plus custom rules; connect errors with aria attributes.
Handle the submit event, and validate again on the server.
Common mistakes
Expecting unchecked checkboxes or disabled fields in FormData.
Using Object.fromEntries on forms with repeated names.
Forgetting that all values are strings.
Trusting client validation without checking on the server.
Follow-ups
How do you validate a field on blur and again on input?
How do you make error messages accessible to screen readers?
How would you send the same data as JSON and as multipart?
Tips
List what FormData leaves out; interviewers ask about it.
Show getAll for multi-value fields.
Mention server-side validation and accessible error messages.
184.javascript-0184Hardsenior
How would you design the client side of an autocomplete (typeahead) component so it is fast, correct, and accessible?
Debounce input, skip short queries, cancel the previous request with AbortController, ignore stale responses, cache results by normalized query, and keep a small state machine for idle, loading, ready, and error. Add keyboard navigation with the combobox ARIA pattern, handle IME composition, and track metrics. The key correctness issue is out-of-order responses, which cancellation and a request token solve.
Full answer
Clarify first: data size (local filter or server search), latency target, who is the user (keyboard, screen reader), and what a selection triggers.
Core design:
Input handling: listen to input, normalize the query (trim, lowercase for the cache key), and wait for a minimum length (often 2 or 3 characters). Debounce by about 150 to 300 ms, shorter for local data. Do not search while an IME composition is in progress (compositionstart and compositionend).
Request control: create an AbortController for each request and abort the previous one when a new request starts or the input is cleared. Also keep a request id (or compare the query) and ignore any response that is not for the latest query, because aborting is cooperative and a response may still arrive.
State machine: idle, loading, ready, empty, error, with the items and an active index. Keep old results visible while loading the next ones to avoid flicker, and show a clear empty and error message.
Cache: an LRU map keyed by normalized query, with a TTL. Prefix reuse is possible: results for "jav" can filter results for "java" locally when the server returns the complete set.
Keyboard and accessibility: use the ARIA combobox pattern: role="combobox", aria-expanded, aria-controls the listbox, aria-activedescendant for the highlighted option, role="option" on items, arrow keys to move, Enter to select, Escape to close, and a live region that announces the number of results.
Rendering: highlight the matched part with safe text nodes (never innerHTML with server text), limit the number of rows, and keep the list in a portal or positioned container so it is not clipped.
Selection: close the list, put the label in the input, and do not start a new search for that programmatic change. Clear the selected value if the user edits the text afterwards.
Resilience: timeouts, retry on network errors only, and a fallback to recent searches when offline.
Server cooperation: ranking, typo tolerance, and rate limits belong to the server. The client should send a client request id and the query only, and handle HTTP 429.
Measure: time to first suggestion, cancel rate, cache hit rate, and selection position.
Trade-offs: a lower debounce feels faster but sends more requests, aggressive caching shows stale suggestions, and prefetching popular queries costs bandwidth.
Run with Node.js v24.22.1 as js-184.js; two runs gave identical output.
Output:
--- naive: no abort, no latest check ---
naive final list for "java": ["java","javascript"]
--- with cancellation and a latest check ---
loading query="jav" items=[]
loading query="java" items=[]
ready query="java" items=["java","java lang","javascript"]
requests sent: 2 | final: ["java","java lang","javascript"]
ready query="java " items=["java","java lang","javascript"]
cache hit, requests sent: 2
keyboard: 0 1 0 2 1 | select: java lang
cleared: idle
Key points
Debounce, minimum length, and IME handling reduce useless requests.
AbortController plus a latest-request check prevents out-of-order results.
A small state machine with kept previous results avoids flicker.
LRU cache with TTL, keyed by normalized query.
Use the ARIA combobox pattern, keyboard support, safe rendering, and metrics.
Common mistakes
Sending a request on every keystroke with no debounce or minimum length.
Letting an older, slower response overwrite newer results.
Building the list with innerHTML from server text.
Ignoring keyboard users and screen readers.
Follow-ups
How would you reuse the results of a shorter prefix?
What changes if the data set is small enough to filter locally?
How do you test race conditions in this component?
Tips
Name out-of-order responses as the main bug and show two defenses.
Cover accessibility: it separates strong answers.
Mention metrics and server cooperation.
185.javascript-0185Hardsenior
How would you design a client-side data cache with freshness, request deduplication, and invalidation?
Key entries by a stable request key, store data with a fetched time, serve fresh entries without a request, serve stale ones immediately while revalidating in the background, share one in-flight promise per key, bound the size, and invalidate by key or prefix after writes. Handle errors by keeping the last good data. This is the model behind libraries such as TanStack Query and SWR.
Full answer
Start with requirements: what data, how stale is acceptable, how often it changes, whether users share a device, and memory limits.
Design pieces:
Keys: a stable, serializable key such as ['user', id] turned into a string. Include every input that changes the response (filters, language, auth user), so one user never sees another's data.
Entry shape: { data, error, fetchedAt, promise }. Two time settings: staleTime (how long data counts as fresh, no request) and gcTime (how long an unused entry stays in memory).
Read path: fresh entry returns at once. Stale entry returns the old data right away and starts a background refetch (stale-while-revalidate). Missing entry fetches and waits.
Deduplication: store the in-flight promise per key, so ten components asking at once cause one request. Remove it in finally.
Errors: keep the last good data when a refetch fails, expose the error, retry with backoff for network errors, and do not cache errors for long.
Invalidation: after a mutation, mark related keys stale (by exact key or prefix) and refetch the active ones. Optimistic updates write the expected data first and roll back on failure.
Memory: a size limit with LRU eviction, and garbage collection of entries with no subscribers.
Subscriptions: components subscribe to a key and are notified on change, so the UI updates when a refetch finishes. Notify only when data actually changed.
Triggers for refetching: window focus, network reconnect, and an optional interval.
Persistence: optionally save to localStorage or IndexedDB with a version and a maximum age. Clear it on logout, and never persist sensitive data on shared devices.
HTTP cooperation: respect ETag and Cache-Control, use conditional requests, and remember that the browser also has an HTTP cache.
Testing: inject the clock and the fetcher.
Trade-offs: longer staleTime means fewer requests and more stale screens, and shared caches are fast but need careful keys and invalidation. Invalidation is the hard part, so keep rules simple: writes invalidate by prefix.
javascript
function createCache({ now, staleTime = 1000, maxEntries = 3 }) {
const entries = new Map();
const listeners = new Map();
const stats = { fetches: 0, hits: 0, staleServed: 0, deduped: 0 };
const notify = (key) => (listeners.get(key) ?? []).forEach((fn) => fn(entries.get(key)?.data));
const touch = (key, entry) => {
entries.delete(key);
entries.set(key, entry);
while (entries.size > maxEntries) entries.delete(entries.keys().next().value);
};
function refetch(key, fetcher) {
const entry = entries.get(key) ?? {};
if (entry.promise) {
stats.deduped++;
return entry.promise;
}
stats.fetches++;
const promise = fetcher()
.then((data) => {
touch(key, { data, fetchedAt: now(), promise: null });
notify(key);
return data;
})
.catch((error) => {
touch(key, { ...entries.get(key), error, promise: null });
if (entries.get(key)?.data === undefined) throw error;
return entries.get(key).data;
});
touch(key, { ...entry, promise });
return promise;
}
return {
stats,
get(key, fetcher) {
const entry = entries.get(key);
if (entry && entry.data !== undefined) {
if (now() - entry.fetchedAt < staleTime) {
stats.hits++;
return Promise.resolve(entry.data);
}
stats.staleServed++;
refetch(key, fetcher);
return Promise.resolve(entry.data);
}
return refetch(key, fetcher);
},
invalidate(prefix) {
for (const [key, entry] of entries) if (key.startsWith(prefix)) entries.set(key, { ...entry, fetchedAt: -Infinity });
},
subscribe(key, fn) {
listeners.set(key, [...(listeners.get(key) ?? []), fn]);
},
keys: () => [...entries.keys()],
};
}
let clock = 0;
let version = 1;
let failNext = false;
const server = () => new Promise((resolve, reject) => setImmediate(() => (failNext ? reject(new Error('network')) : resolve({ name: 'Asha', version }))));
const settle = () => new Promise((resolve) => setImmediate(() => setImmediate(resolve)));
(async () => {
const cache = createCache({ now: () => clock });
cache.subscribe('user:1', (data) => console.log(' subscriber saw', JSON.stringify(data)));
const [a, b, c] = await Promise.all([cache.get('user:1', server), cache.get('user:1', server), cache.get('user:1', server)]);
console.log('three readers, one fetch:', cache.stats, a === b && b === c);
clock = 500;
await cache.get('user:1', server);
console.log('fresh read:', cache.stats.hits, 'hit, fetches', cache.stats.fetches);
clock = 2000;
version = 2;
console.log('stale read returns old data first:', JSON.stringify(await cache.get('user:1', server)));
await settle();
console.log('next read has new data:', JSON.stringify(await cache.get('user:1', server)));
version = 3;
cache.invalidate('user:');
console.log('after invalidate, old data returned:', (await cache.get('user:1', server)).version);
await settle();
failNext = true;
clock = 9000;
console.log('refetch fails, last good data kept:', (await cache.get('user:1', server)).version);
await settle();
failNext = false;
for (const id of [2, 3, 4]) await cache.get('user:' + id, server);
console.log('size limit keeps the newest:', cache.keys());
})();
Run with Node.js v24.22.1 as js-185.js; two runs gave identical output.
Output:
subscriber saw {"name":"Asha","version":1}
three readers, one fetch: { fetches: 1, hits: 0, staleServed: 0, deduped: 2 } true
fresh read: 1 hit, fetches 1
stale read returns old data first: {"name":"Asha","version":1}
subscriber saw {"name":"Asha","version":2}
next read has new data: {"name":"Asha","version":2}
after invalidate, old data returned: 2
subscriber saw {"name":"Asha","version":3}
refetch fails, last good data kept: 3
size limit keeps the newest: [ 'user:2', 'user:3', 'user:4' ]
Key points
Stable keys that include every input; store data with fetchedAt.
Fresh returns directly; stale returns and revalidates; missing waits.
One in-flight promise per key prevents duplicate requests.
Keep the last good data on errors; invalidate by key or prefix after writes.
Bound memory, notify subscribers, persist carefully, and test with injected clock and fetcher.
Common mistakes
Using a cache key that misses an input such as the user or a filter.
Starting a new request for every reader instead of sharing the promise.
Dropping good data when a refetch fails.
Invalidating too broadly or not at all after writes.
Follow-ups
How would you add optimistic updates with rollback?
What would you persist, and what never?
How does this relate to HTTP caching headers?
Tips
Describe fresh, stale, and missing as three read paths.
Mention deduplication and invalidation as the real difficulty.
Mention security: keys must include the user, and clear on logout.
186.javascript-0186Hardsenior
How would you design a small client-side analytics library that batches events and does not lose them on page close?
Put events in an in-memory queue with timestamps and ids, flush on a size limit, a timer, and page hide using navigator.sendBeacon or fetch with keepalive, retry failures with backoff, cap the queue, and make delivery idempotent with event ids. Keep it off the critical path, respect consent and privacy, and never let tracking errors break the app.
Full answer
Clarify the goals: acceptable loss rate, event volume, payload size, offline behavior, and privacy rules (consent, personal data).
Design:
API: track(name, props) returns immediately and never throws. It adds metadata: an event id (crypto.randomUUID()), a client timestamp, session id, page, and library version.
Queue: an in-memory array with a maximum length. When it is full, drop the oldest events (or sample) and count the drops. Optionally persist to localStorage or IndexedDB so events survive reloads, with a size cap.
Flush triggers: batch size reached (for example 20), a timer (for example 5 seconds after the first event, not a ticking interval), and page lifecycle. On visibilitychange to hidden and on pagehide, flush with navigator.sendBeacon(url, blob) or fetch(url, { keepalive: true }). Do not use unload or beforeunload, which are unreliable and block the back/forward cache. Beacon payloads have a size limit (about 64 KB), so split big batches.
Sending: one request per batch, compressed JSON if needed, a first-party or token-based endpoint, and the send time in the payload so the server can correct client clock errors.
Failure handling: on network errors or 5xx, put events back in the queue and retry with exponential backoff and jitter, limited attempts. On 4xx (except 429), drop the batch because retry cannot help. Respect Retry-After.
Idempotency: event ids let the server remove duplicates caused by retries or by beacon and fetch both succeeding.
Performance: do the work in idle time or after the interaction, keep payloads small, do not block rendering, and avoid synchronous storage on hot paths.
Privacy and consent: do not send before consent when required, support opt-out and a "Do Not Track" or Global Privacy Control signal, avoid personal data in properties, and allow a data deletion path.
Resilience of the host app: wrap all calls in try/catch, and keep the library's error reporting separate from the application's.
Observability: count queued, sent, dropped, and retried events, and expose a debug mode.
Ad blockers: use a first-party endpoint path to reduce loss, and accept that some loss remains.
Trade-offs: larger batches save requests but increase loss on a crash, and persistence improves delivery but adds storage code and privacy duties.
Run with Node.js v24.22.1 as js-186.js; two runs gave identical output.
Output:
two events, no request yet: 0 [ 1, 2 ]
size limit reached: fetch [1,2,3] -> 200 []
timer flush: fetch [4] -> 200
server error keeps the event: [ 5 ] { sent: 4, dropped: 0, retried: 1, requests: 3 }
retry succeeded: fetch [5] -> 200 []
page hide uses a beacon: beacon [6] -> 200
client error drops the batch: [] { sent: 6, dropped: 1, retried: 1, requests: 6 }
queue cap drops the oldest: [ 3, 4 ] 2
fetch [1,2,3] -> 200
fetch [4] -> 200
fetch [5] -> 503
fetch [5] -> 200
beacon [6] -> 200
fetch [7] -> 400
Key points
Non-throwing track(), event ids, timestamps, and a bounded queue.
Flush on size, timer, and page hide using sendBeacon or fetch keepalive; avoid unload.
Retry network and 5xx failures with backoff; drop non-retryable 4xx; use ids for idempotency.
Keep it off the critical path; respect consent and avoid personal data.
Measure drops and retries.
Common mistakes
Relying on unload or beforeunload to send the last events.
Retrying 4xx errors forever.
Letting the queue grow without a limit.
Allowing analytics errors to break the application.
Follow-ups
How would you make delivery idempotent on the server?
How would you respect consent changes after events are queued?
What are the limits of sendBeacon?
Tips
Name the flush triggers and the page hide trick.
Explain retry rules: which statuses, backoff, and limits.
Raise privacy and consent early.
187.javascript-0187Hardsenior
How would you design a client-side feature flag library with percentage rollouts, fast startup, and safe defaults?
Evaluate flags locally from a cached rules payload so reads are synchronous and fast. Give each flag a default, bucket users with a stable hash of flag key and user id for percentage rollouts, bootstrap from storage or server-rendered data, refresh in the background, and log exposure once. Keep a kill switch path, and never block rendering on the network.
Full answer
Requirements to ask about: how fast flags must be available, how often they change, who targets them (users, groups, percentages), whether results must be consistent across devices, and whether experiments need exposure data.
Design:
Flag definition: { key, enabled, rules: [{ attribute, op, values, serve }], rollout: { percent }, variants, version }, delivered as one JSON payload per environment, ideally with an ETag so refreshes are cheap.
Evaluation on the client: isEnabled(key, context) is synchronous and pure. It checks the kill switch (enabled: false), explicit targeting rules, then the percentage rollout, and falls back to the default given in code. Unknown flags return the default and report a warning.
Stable bucketing: hash flagKey + ':' + userId with a fast, well-spread hash (FNV-1a or murmur), map to 0 to 9999, and compare to percent * 100. Salting with the flag key means a user is not always in the first 10% of every flag. The same user always gets the same answer, and raising from 10% to 20% keeps the first 10% enabled.
Anonymous users: use a stable random id stored in a first-party cookie or storage. State clearly that a cleared storage means a new bucket.
Startup: render with bootstrap values from the server response (inline JSON) or the last payload in localStorage, then fetch fresh rules in the background. Do not block first paint, and avoid flicker by applying flag changes at the next navigation or only when the value affects non-visible logic, unless the product accepts live updates.
Updates: poll with ETag, or use server-sent events or WebSocket for fast kill switches. Notify subscribers only when an evaluated value changes.
Exposure logging: record "user saw variant X" once per flag, user, and session, when the flag is actually evaluated for a decision, and send it through the analytics batcher.
Safety: defaults in code for each flag, a timeout for the fetch, try/catch around evaluation, and a global override for testing (query parameter or local storage, allowed only in non-production or for signed-in staff).
Security and privacy: client flags are visible to users, so never put secrets, private targeting lists, or paid-feature enforcement only in client flags. Enforce important rules on the server.
Hygiene: owners, expiry dates, and removal of old flags, because long-lived flags multiply the testing matrix.
Trade-offs: local evaluation is fast but exposes rules, while server evaluation hides rules and adds latency. Many products use server evaluation for sensitive flags and local evaluation for UI flags.
Run with Node.js v24.22.1 as js-187.js; two runs gave identical output.
Output:
20% rollout enabled for 20.0% of 20000 users
sticky: true
staff rule beats the percentage: true
country rule turns it off: false
plain flag, disabled flag, unknown flag: true false false
exposure events logged once per user and flag: 20004
raising to 40% keeps every user from 20%: true
overlap with another 20% flag is about 4%, got 3.8%
changed flags: [ 'dark-mode' ]
Key points
Synchronous local evaluation from a cached rules payload, with in-code defaults.
Stable hash of flag key and user id gives sticky, monotonic percentage rollouts.
Bootstrap from the server or storage; refresh in the background; avoid blocking render.
Log exposure once per decision; use polling or streaming for kill switches.
Client flags are not secret; enforce important rules on the server and remove old flags.
Common mistakes
Using Math.random for rollouts, which gives users a different answer each visit.
Using the same hash input for every flag, so the same users are always first.
Blocking first paint on a flag request.
Treating client-side flags as a place for secrets or access control.
Follow-ups
How would you run an A/B experiment with this client?
How do you retire a flag safely?
Why not evaluate every flag on the server?
Tips
Explain stable bucketing and why the flag key is part of the hash.
Mention defaults and a kill switch as the safety story.
Say plainly that client flags are visible to users.
188.javascript-0188Hardsenior
How would you design an offline-first client that queues changes and syncs them safely when the connection returns?
Apply changes to local state at once, record each change as an operation with a unique id in a durable queue, replay the queue in order when online, make the server idempotent using the operation id, retry network failures with backoff, drop or flag permanent failures, and resolve conflicts with versions or timestamps. Show sync status to the user.
Full answer
Start with the product rules: which data must work offline, how long, how many devices edit the same data, and what conflicts are acceptable.
Design:
Local source of truth: the UI reads from local state backed by IndexedDB (not localStorage, which is small and synchronous). Writes update local state immediately (optimistic), so the app feels instant.
Operations, not state: each change becomes { opId, type, entityId, payload, baseVersion, createdAt }. Operations are appended to a persistent queue. Collapse redundant operations when safe (several edits of one field into the last one).
Sync loop: when the app starts, comes back online (online event, though it is only a hint), or the user retries, send operations in order. Keep ordering per entity, and allow parallel requests for different entities if the server supports it. Only one sync loop runs at a time.
Idempotency: the client sends opId (an idempotency key), and the server stores processed ids, so a retry after a timeout does not apply a change twice. This is the most important server contract.
Failure handling: network errors and 5xx responses are retried with exponential backoff and jitter. A 4xx validation error is permanent: remove the operation, revert the optimistic change, and tell the user. Authentication errors pause the queue until sign-in.
Conflicts: the server compares baseVersion with the current version. Options are last-write-wins (simple, can lose edits), field-level merge, reject and ask the user, or CRDTs for collaborative text. Choose by business value.
Pull side: after pushing, fetch changes since a cursor and merge them into local state. Server changes win for fields without pending local operations. Rebase pending operations on top of new data.
Storage limits and schema: version the local database, handle migrations, cap the queue and tell the user when it is full, and clear data on logout.
Visibility: show states such as "saved on this device", "syncing", "offline", and "needs attention", and let users retry or discard.
Multi-tab: use BroadcastChannel or a lock (Web Locks API) so only one tab syncs.
Service worker and Background Sync can send queued data after the page closes where supported, but must not be the only path.
Testing: simulate offline, partial failure, duplicate delivery, and reordering.
Trade-offs: simple last-write-wins is easy but loses data, and richer merges cost design time, so choose per entity.
javascript
function createServer() {
const processed = new Map();
const docs = new Map([['note-1', { text: 'start', version: 1 }]]);
let online = false;
let dropReply = false;
return {
docs,
setOnline: (value) => (online = value),
dropNextReply: () => (dropReply = true),
async handle(op) {
if (!online) throw new Error('network');
if (processed.has(op.opId)) return processed.get(op.opId);
let response;
const doc = docs.get(op.entityId);
if (!op.payload.text) response = { status: 422 };
else if (doc.version !== op.baseVersion) response = { status: 409, version: doc.version };
else {
docs.set(op.entityId, { text: op.payload.text, version: doc.version + 1 });
response = { status: 200, version: doc.version + 1 };
}
processed.set(op.opId, response);
if (dropReply) {
dropReply = false;
throw new Error('timeout after the server applied the change');
}
return response;
},
};
}
function createClient(server) {
const local = new Map([['note-1', { text: 'start', version: 1 }]]);
const queue = [];
const log = [];
let n = 0;
let syncing = false;
return {
local,
log,
queue,
edit(entityId, text) {
const doc = local.get(entityId);
queue.push({ opId: `op-${++n}`, entityId, payload: { text }, baseVersion: doc.version, backup: { ...doc } });
local.set(entityId, { text, version: doc.version });
},
async sync() {
if (syncing) return;
syncing = true;
try {
while (queue.length) {
const op = queue[0];
let result;
try {
result = await server.handle(op);
} catch (error) {
log.push(`${op.opId}: ${error.message}, kept for retry`);
return;
}
queue.shift();
if (result.status === 200) {
local.set(op.entityId, { text: op.payload.text, version: result.version });
queue.filter((next) => next.entityId === op.entityId).forEach((next) => (next.baseVersion = result.version));
log.push(`${op.opId}: applied, version ${result.version}`);
} else {
local.set(op.entityId, op.backup);
log.push(`${op.opId}: rejected with ${result.status}, local change reverted`);
}
}
} finally {
syncing = false;
}
},
};
}
(async () => {
const server = createServer();
const client = createClient(server);
client.edit('note-1', 'offline edit one');
client.edit('note-1', 'offline edit two');
console.log('offline, UI shows:', client.local.get('note-1').text, '| queued:', client.queue.length);
await client.sync();
console.log('still offline:', client.log.at(-1), '| queued:', client.queue.length);
server.setOnline(true);
server.dropNextReply();
await client.sync();
console.log('reply lost:', client.log.at(-1));
await client.sync();
console.log('retry is idempotent:', client.log.slice(-2), '| server doc:', JSON.stringify(server.docs.get('note-1')));
client.edit('note-1', '');
await client.sync();
console.log('validation error:', client.log.at(-1), '| UI shows:', client.local.get('note-1').text);
server.docs.set('note-1', { text: 'edited elsewhere', version: 9 });
client.edit('note-1', 'my late edit');
await client.sync();
console.log('conflict:', client.log.at(-1), '| UI shows:', client.local.get('note-1').text);
console.log('server doc:', JSON.stringify(server.docs.get('note-1')), '| queue empty:', client.queue.length === 0);
})();
Run with Node.js v24.22.1 as js-188.js; two runs gave identical output.
Output:
offline, UI shows: offline edit two | queued: 2
still offline: op-1: network, kept for retry | queued: 2
reply lost: op-1: timeout after the server applied the change, kept for retry
retry is idempotent: [ 'op-1: applied, version 2', 'op-2: applied, version 3' ] | server doc: {"text":"offline edit two","version":3}
validation error: op-3: rejected with 422, local change reverted | UI shows: offline edit two
conflict: op-4: rejected with 409, local change reverted | UI shows: offline edit two
server doc: {"text":"edited elsewhere","version":9} | queue empty: true
Key points
Optimistic local writes backed by IndexedDB; the queue stores operations with ids.
Replay in order, one loop at a time; the server dedupes by operation id.
Retry network and 5xx errors with backoff; remove and revert permanent failures.
Detect conflicts with versions and choose a clear resolution policy.
Show sync status; handle multiple tabs, migrations, and logout.
Common mistakes
Using localStorage as the main offline database.
Retrying operations without an idempotency key, which applies them twice.
Replaying operations out of order for the same entity.
Hiding sync state from the user.
Follow-ups
How would you merge text edits from two devices?
What does the pull side of sync look like?
How would you handle several tabs?
Tips
Describe operations plus idempotency keys as the core.
Choose a conflict policy and justify it.
Say how the user sees pending, failed, and synced states.
189.javascript-0189Hardsenior
How would you design a plugin system for a JavaScript library so others can extend it safely?
Keep a small stable core that exposes named hooks or an event pipeline, let plugins register through a single install function that receives a restricted API, define the order and error rules, version the contract, and isolate failures so one plugin cannot break the rest. Document lifecycle, naming, and teardown, and avoid giving plugins the whole internal state.
Full answer
Good plugin design starts from what users need to change, and from what you must keep stable.
Design choices:
Shape of a plugin: a plain object { name, version, apply(api) } or a function (api, options) => void. A single entry point makes loading, testing, and typing simple. A name is needed for ordering, errors, and duplicates.
Extension points: pick one model and stay with it. Hooks with named stages (beforeRequest, afterResponse), middleware (next() chain like Express and Koa), events (on('save')), or transforms (waterfall hooks where each plugin gets the previous result). Tapable and Rollup use hook types such as sequential, waterfall, and parallel. Choose by need: waterfall for data changes, parallel for side effects.
Ordering: define it. Use registration order by default, plus explicit before and after or numeric priority when needed. Document that order matters for waterfall hooks.
The API given to plugins: a narrow object with hook(name, fn), getOption, logger, and helper methods. Do not pass the internal state or private classes, because anything exposed becomes a public contract.
Error handling: wrap each plugin call with the plugin's name in the error (Error.cause keeps the original). Choose the policy: fail fast in development, isolate and continue in production for non-critical hooks, with a timeout for async hooks.
Lifecycle: setup, dispose or teardown functions returned from install, so hot reload, tests, and unmounting do not leak listeners. Prevent double install.
Versioning: a apiVersion or requires range checked at install, a changelog for hook names and payloads, deprecation warnings before removal, and TypeScript types for the plugin API.
Security and trust: plugins run in the same realm with full power. For untrusted code use iframes, workers, or a ShadowRealm-like sandbox, with a message-based API. For first-party plugins, trust is fine but review the permissions.
Performance: lazy-load plugins, keep hook dispatch cheap (arrays of functions, no per-call allocation), and skip empty hooks.
Testing: provide a test harness and a way to create an isolated instance, so plugin authors can test without a global state.
Discoverability: naming conventions (mylib-plugin-*), a registry or documentation, and examples.
Trade-offs: more hooks give more freedom and more breaking changes. Start with few hooks, add them when real plugins need them, and keep core features out of plugins.
Run with Node.js v24.22.1 as js-189.js; two runs gave identical output.
Output:
plugins: [ 'trim', 'shout', 'early', 'logger' ]
logger saw: "HI WORLD!"
result: HI WORLD!
duplicate: plugin "trim" is already installed
version: plugin "future" needs API version 3
error: plugin "broken" failed in hook "transform" | cause: TypeError bad input
unknown hook returns the input: same
logger cleaned up
Key points
One install entry point and a narrow, documented API object.
Pick a model: hooks, middleware, events, or waterfall transforms; define order and error policy.
Wrap plugin errors with the plugin name and cause; add timeouts for async hooks.
Provide teardown, version checks, and deprecation paths.
Do not expose internals; sandbox untrusted plugins.
Common mistakes
Exposing internal objects to plugins and then being unable to change them.
Leaving plugin order undefined while using waterfall hooks.
Letting a plugin error fail with no plugin name in the message.
No teardown, which leaks listeners in tests and hot reload.
Follow-ups
When would you choose middleware over hooks?
How would you sandbox untrusted plugins?
How do you deprecate a hook?
Tips
Ask what must stay stable before choosing a model.
Cover errors, ordering, and teardown; they separate designs.
Keep the plugin API small.
190.javascript-0190Hardsenior
How would you design a client-side error monitoring library that captures errors, groups them, and does not hurt the page?
Capture window error events, unhandledrejection, resource errors, and handled errors from a captureException API, normalize them into a payload with stack, release, and context, scrub personal data, de-duplicate and sample, send in batches with sendBeacon or fetch keepalive, and resolve stacks with source maps on the server. The library must never throw, loop, or slow the app.
Full answer
Goals: find real user-facing errors quickly, group them into issues, give enough context to fix them, and add almost no cost or risk to the page.
Capture:
window.addEventListener('error', ...) for uncaught errors and, with the capture flag, for failed resource loads (images, scripts). Cross-origin scripts give only "Script error." unless they use CORS (crossorigin attribute and the right headers).
window.addEventListener('unhandledrejection', ...), whose event.reason may not be an Error (it can be a string or object), so normalize it.
A manual API captureException(error, context) for handled errors, plus integration with frameworks (error boundaries) and wrapping of fetch and XHR to record failed requests.
Breadcrumbs: a small ring buffer of recent events (clicks, navigations, network calls, console messages) to show what led to the error.
Payload: message, error type, stack frames (parsed from error.stack, which differs between engines), release and environment, URL (scrub tokens), user agent, a session id, an anonymous or hashed user id, and error.cause chain. Add custom tags.
Processing in the client:
Dedupe: fingerprint by type, message with numbers removed, and top frame. Send the first, then count repeats and rate-limit per fingerprint to survive error loops.
Sample: sampling rate for noisy apps, and always keep new fingerprints.
Ignore known noise: browser extension errors, ResizeObserver loop warnings, and aborted requests (AbortError).
Guard against recursion: if the reporter itself fails, do not report that failure.
Scrub personal data: remove query strings with tokens, form values, and request bodies by default, and offer a user-controlled filter before sending.
Delivery: same approach as analytics: batch, sendBeacon or fetch with keepalive on page hide, retry with backoff, bounded queue, and an endpoint that is not blocked by the page's CSP.
Server and workflow: upload source maps for each release (not public in production), resolve minified stacks, group issues, link to releases and commits, alert on regressions, and track the crash-free sessions rate.
Trade-offs: more context helps debugging but increases privacy risk and payload size. Choose conservative defaults with opt-in for more.
Run with Node.js v24.22.1 as js-190.js; two runs gave identical output.
Output:
same error with different numbers: [ 'sent', 'sent', 'rate limited' ] { 'TypeError|Cannot read user N': 3 }
string rejection: sent
object rejection: sent | NonErrorRejection
abort ignored: ignored
chain with scrubbed cause: [
'Error: Could not save settings',
'RangeError: payload too large?key=[removed]'
]
release and breadcrumbs: web@1.4.2 [
'POST /api/save?token=[removed]',
'navigate /settings',
'click #logout'
]
events sent: 5
Key points
Capture error, unhandledrejection, resource errors, and a manual captureException; normalize non-Error reasons.
Add release, breadcrumbs, and cause chains; scrub personal data.
Dedupe with a fingerprint, sample, rate-limit, and ignore known noise.
Never throw or recurse; deliver in batches with beacon or keepalive.
Resolve stacks with source maps on the server, grouped by release.
Common mistakes
Reporting errors from inside the error reporter, which can loop.
Sending every repeat of an error that fires in a loop.
Sending tokens, form values, or personal data in URLs and breadcrumbs.
Ignoring unhandled rejections with non-Error reasons.
Follow-ups
How do source maps resolve a minified stack?
Why does a cross-origin script give only "Script error."?
How would you measure the cost of the monitor?
Tips
Cover capture, enrich, filter, deliver, and analyze as five steps.
Mention privacy and rate limiting early.
Say the library must never throw.
191.javascript-0191Mediummid
How does dynamic import() work, and how do you use it for code splitting and preloading?
import(specifier) loads a module on demand and returns a promise for its namespace object. The module is fetched and evaluated once and cached, so later calls reuse it. Bundlers turn each dynamic import into a separate chunk, which lets you load code for routes or heavy features only when needed. Handle failures, avoid waterfalls, and preload when the user is likely to need the code.
Full answer
Static import statements are resolved before the code runs. import('./chart.js') is an expression that can run at any time, anywhere, in modules and classic scripts, and returns a promise.
Behavior:
The promise resolves to the module namespace object: const { render } = await import('./chart.js'), and the default export is in .default.
The module is loaded and evaluated once per URL (per module map). Later import() calls return the same namespace without running the module again. Top-level await in the module delays the resolution.
The specifier can be computed (import(./locales/${lang}.js)), but bundlers need a pattern they can analyze, and they may bundle every matching file.
If loading fails (network, 404, syntax error), the promise rejects. A failed fetch is not retried automatically by the browser for the same specifier in some engines, so deployment mismatches (an old page asking for a deleted hashed chunk) need a handler: show a message or reload the page.
Using it for code splitting:
Split by route: load a page's code when the user navigates. Frameworks wrap this as lazy(() => import('./Page')).
Split by feature: heavy editors, charts, PDF tools, and rarely used dialogs.
Split by condition: polyfills or locale data only when needed.
Bundlers (Webpack, Rollup, Vite, esbuild) create a chunk per dynamic import and shared chunks for common dependencies, and give hashed file names for long-term caching.
Avoiding the costs:
Waterfalls: a chunk that imports another chunk after it loads delays the feature. Preload or use <link rel="modulepreload"> for chunks you know you will need.
Prefetch on intent: start import() on hover, focus, or when the browser is idle, and keep the promise so the click reuses it.
Do not split too small. Many tiny chunks add requests, so measure with the network panel and a bundle analyzer.
Show a loading state and handle errors with a retry.
Dynamic import also works in Node.js, including from CommonJS, which is how a CommonJS file can load an ES module.
Run with Node.js v24.22.1 as js-191.js; two runs gave identical output.
Output:
before any import, evaluations: 0
namespace keys: [ 'default', 'render' ] | render: chart of 1+2 | default: default export
same namespace object: true | evaluations: 1
top-level await: top-level await finished
syntax error rejects the promise: SyntaxError
missing file rejects: ERR_MODULE_NOT_FOUND
prefetch keeps one promise: true
parallel loads: Hello Namaste
computed specifier: Namaste
lazy wrapper shares the load: true
Key points
import() returns a promise for the namespace object; the default export is in .default.
A module is fetched and evaluated once, then cached.
Bundlers make a chunk per dynamic import; split by route, feature, and condition.
Avoid waterfalls with modulepreload and prefetch on intent; keep the promise.
Handle load failures, especially after deployments change hashed file names.
Common mistakes
Importing everything statically and shipping one huge bundle.
Splitting into many tiny chunks and creating request waterfalls.
Not handling a failed chunk load after a new deployment.
Using import() with a fully dynamic specifier that a bundler cannot analyze.
Follow-ups
How does modulepreload differ from prefetch?
How would you retry a failed chunk load?
How do you load an ES module from CommonJS?
Tips
Say it returns a promise for the namespace and that modules are cached.
Give three split points: route, feature, condition.
Mention loading states, errors, and prefetch on intent.
192.javascript-0192Mediummid
What is IndexedDB, how do object stores, indexes, and transactions work, and when do you choose it over localStorage?
IndexedDB is an asynchronous, transactional object database in the browser that stores structured-clonable values, blobs, and files, with indexes for queries and much larger quotas than localStorage. Work happens inside transactions on object stores, schema changes only happen in the upgrade handler, and every request is event or promise based. Choose it for large, structured, or offline data, and localStorage for tiny strings.
Full answer
localStorage is synchronous, stores strings only, and is limited to about 5 MB, so large values block the main thread. IndexedDB solves these limits.
Key concepts:
Database and version: indexedDB.open(name, version). When the version is higher than the stored one, onupgradeneeded runs. That is the only place to create or change object stores and indexes. Plan migrations by checking event.oldVersion.
Object store: like a table. It has a key path (keyPath: 'id') or generated keys (autoIncrement). Values can be objects, arrays, dates, blobs, and typed arrays, copied with the structured clone algorithm (no functions or DOM nodes).
Index: a secondary lookup on a property, such as email or createdAt. It lets you query by that property with ranges (IDBKeyRange.bound) and cursors, and can be unique.
Transaction: all reads and writes happen in a transaction with a mode (readonly or readwrite) and a list of stores. Transactions are atomic: if one request fails or you call abort(), none of the changes apply. A transaction closes automatically when no request is pending, so you cannot await unrelated work (like fetch) in the middle of it. By the time the work is done the transaction has finished, and using it throws an error (TransactionInactiveError for a new request on an inactive transaction, InvalidStateError once it is finished).
API style: the native API uses IDBRequest objects with onsuccess and onerror, so most projects wrap it in promises or use a small library such as idb or Dexie.
Cursors and getAll(query, count) read ranges. Use a key range and a limit instead of reading everything.
Durability and limits: data is per origin, can be evicted under storage pressure unless navigator.storage.persist() is granted, and may be unavailable in private modes in some browsers. Handle QuotaExceededError.
Multiple tabs: a version upgrade is blocked while another tab holds the old version open, so handle onversionchange by closing the connection.
It is available in workers and service workers, which localStorage is not.
Use it for offline queues, caches of API data, drafts, and files. Do not store secrets in it, since any script on the origin can read it.
Run with Node.js v24.22.1 as js-192.js; two runs gave identical output.
Output:
upgrade from version 0 to 2
stores: [ 'notes' ] | indexes: [ 'byAuthor', 'byDate' ]
get by key: { author: 'ben', text: 'second', created: 1, id: 2 }
by author index: [ 'first', 'third' ]
date range 1..2: [ 'second', 'third' ]
count: 3 | structured clone keeps Date: true
count after abort: 3
write in readonly: ReadOnlyError
await between requests: InvalidStateError
duplicate key: ConstraintError
Key points
Asynchronous, transactional, structured-clone storage with indexes and large quotas.
Schema changes only in onupgradeneeded; plan versions and migrations.
Transactions are atomic and auto-close, so do not await unrelated async work inside them.
Use indexes, key ranges, and limits; wrap the API in promises or use idb or Dexie.
Handle quota, eviction, multi-tab version changes; do not store secrets.
Common mistakes
Awaiting fetch or other unrelated promises inside an open transaction.
Trying to create stores outside onupgradeneeded.
Reading a whole store to filter in JavaScript when an index and key range would do.
Storing secrets or assuming the data can never be evicted.
Follow-ups
How do you handle a version upgrade blocked by another tab?
When would you choose Dexie or idb?
How does the Cache API differ from IndexedDB?
Tips
Contrast with localStorage in size, sync versus async, and types.
Mention that transactions auto-close, since it is the usual bug.
Name a wrapper library and migrations by version.
193.javascript-0193Mediummid
How do polling, long polling, Server-Sent Events, and WebSockets differ, and how do you choose between them?
Polling asks repeatedly on a timer, long polling holds each request open until data exists, Server-Sent Events keep one HTTP response open for one-way server messages with automatic reconnect, and WebSockets open a two-way channel after an HTTP upgrade. Choose the simplest one that meets the direction, latency, and scale needs: SSE for server pushes, WebSockets for two-way low latency.
Full answer
All four move updates from a server to a page. They differ in direction, cost, and complexity.
Polling: setInterval plus fetch. Easy, works everywhere, and cacheable. Cost: wasted requests when nothing changed, and latency up to the interval. Use it when updates are rare or data is slow to change, with backoff and a pause when the tab is hidden.
Long polling: the server holds the request until data is ready or a timeout, then the client immediately asks again. Latency is low and it works through old proxies, but each message costs a full request, and servers need to hold many open connections.
Server-Sent Events (SSE): one long HTTP response with Content-Type: text/event-stream. The browser EventSource parses data: lines, reconnects automatically, and sends Last-Event-ID so the server can resume. It is one-way (server to client), text only, works over HTTP/2 multiplexing, and has a limit of six connections per host over HTTP/1.1. It cannot set custom headers with EventSource, so authentication usually uses cookies or fetch streaming instead.
WebSockets: an HTTP request upgrades to a persistent two-way connection with small frames, text and binary. It gives the lowest latency for chat, games, and collaborative editing. You must handle reconnects, heartbeats (ping and pong), backpressure, authentication at connect time, and scaling (sticky routing or a pub/sub layer between servers). Some proxies and corporate networks interfere.
Choosing:
Server pushes only (notifications, live scores, progress): SSE is usually the simplest.
Two-way and frequent (chat, multiplayer, cursors): WebSockets.
Rare updates or simple infrastructure: polling.
Restricted network and low volume: long polling.
Questions to decide: who sends, how often, message size, how many connections, delivery guarantees (all four need ids and replay if messages must not be lost), and mobile battery cost. Always add a reconnect strategy with exponential backoff and jitter, and send a state snapshot after reconnecting.
javascript
const http = require('node:http');
const subscribers = new Set();
const history = [];
const waiting = [];
let connections = 0;
let longPollRequests = 0;
const server = http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
if (url.pathname === '/poll') {
const since = Number(url.searchParams.get('since') ?? 0);
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(history.filter((e) => e.id > since)));
} else if (url.pathname === '/long-poll') {
longPollRequests++;
const since = Number(url.searchParams.get('since') ?? 0);
const ready = history.filter((e) => e.id > since);
if (ready.length) return res.end(JSON.stringify(ready));
waiting.push({ since, res });
} else if (url.pathname === '/events') {
connections++;
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' });
const lastId = Number(req.headers['last-event-id'] ?? 0);
history.filter((e) => e.id > lastId).forEach((e) => res.write(`id: ${e.id}\ndata: ${e.text}\n\n`));
subscribers.add(res);
req.on('close', () => subscribers.delete(res));
} else {
res.statusCode = 404;
res.end();
}
});
function publish(text) {
const event = { id: history.length + 1, text };
history.push(event);
subscribers.forEach((res) => res.write(`id: ${event.id}\ndata: ${event.text}\n\n`));
waiting.splice(0).forEach(({ res }) => res.end(JSON.stringify([event])));
}
async function readSse(base, headers, wanted) {
const controller = new AbortController();
const response = await fetch(base + '/events', { headers, signal: controller.signal });
const decoder = new TextDecoder();
const messages = [];
let buffer = '';
for await (const chunk of response.body) {
buffer += decoder.decode(chunk, { stream: true });
let end;
while ((end = buffer.indexOf('\n\n')) !== -1) {
const block = buffer.slice(0, end);
buffer = buffer.slice(end + 2);
messages.push(Object.fromEntries(block.split('\n').map((line) => line.split(/: (.*)/s).slice(0, 2))));
}
if (messages.length >= wanted) break;
}
controller.abort();
return messages;
}
server.listen(0, '127.0.0.1', async () => {
const base = `http://127.0.0.1:${server.address().port}`;
const getJson = async (path) => (await fetch(base + path)).json();
console.log('poll, nothing yet:', await getJson('/poll?since=0'));
publish('one');
console.log('poll after an event:', await getJson('/poll?since=0'));
const pending = getJson('/long-poll?since=1');
await new Promise((resolve) => setTimeout(resolve, 20));
publish('two');
console.log('long poll answers when data exists:', await pending, '| requests used:', longPollRequests);
const live = readSse(base, {}, 3);
await new Promise((resolve) => setTimeout(resolve, 30));
publish('three');
console.log('sse, one connection, replay plus live:', await live, '| connections:', connections);
console.log('sse resume with Last-Event-ID 2:', await readSse(base, { 'Last-Event-ID': '2' }, 1), '| connections:', connections);
console.log('raw wire format:', JSON.stringify('id: 3\ndata: three\n\n'));
server.closeAllConnections();
server.close();
});
Run with Node.js v24.22.1 as js-193.js; two runs gave identical output.
Output:
poll, nothing yet: []
poll after an event: [ { id: 1, text: 'one' } ]
long poll answers when data exists: [ { id: 2, text: 'two' } ] | requests used: 1
sse, one connection, replay plus live: [
{ id: '1', data: 'one' },
{ id: '2', data: 'two' },
{ id: '3', data: 'three' }
] | connections: 1
sse resume with Last-Event-ID 2: [ { id: '3', data: 'three' } ] | connections: 2
raw wire format: "id: 3\ndata: three\n\n"
Key points
Polling is simple but wasteful; long polling cuts latency but costs a request per message.
SSE is a one-way text stream with automatic reconnect and Last-Event-ID resume.
WebSockets are two-way and low latency but need heartbeats, reconnect logic, and scaling work.
Choose by direction, frequency, scale, and network limits.
Use ids, replay, backoff with jitter, and snapshots for reliability.
Common mistakes
Polling at a short fixed interval from many clients.
Using WebSockets for one-way notifications that SSE would handle.
No reconnect with backoff, heartbeats, or replay of missed messages.
Forgetting that open connections count against server and browser limits.
Follow-ups
How do you scale WebSocket servers across machines?
How do you authenticate an EventSource connection?
What happens to messages sent while a client is offline?
Tips
Start with direction and frequency of messages.
Name SSE as the often forgotten simple option.
Mention reconnect, ids, and replay for all four.
194.javascript-0194Hardsenior
How would you build a WebSocket client that reconnects with backoff, detects dead connections with heartbeats, and does not lose messages while offline?
Wrap the socket in a small state machine. Reconnect with exponential backoff and jitter, reset the delay after a successful open, send a ping on a timer and close the socket if no pong arrives, queue outgoing messages while disconnected and flush them on open, and send the last received id so the server can replay what was missed. Add a maximum number of attempts and a manual close that stops reconnecting.
Full answer
A raw WebSocket does not reconnect and does not tell you when the network silently disappears. A reliable client adds these parts:
States: connecting, open, closed, waiting (before a retry), and stopped (closed by the user). Keep the state explicit so you can test it.
Backoff: delay = min(max, base * 2^attempt), then apply jitter (a random factor, often "full jitter": a random value between 0 and the delay). Jitter prevents thousands of clients from reconnecting at the same second after a server restart. Reset the attempt count when a connection has been open for a stable time, not only at the first open event.
Heartbeat: a half-open connection (a dropped Wi-Fi, a proxy that timed out) can look open for minutes. Send an application-level ping every N seconds and expect a pong within a timeout, or close and reconnect. Browsers do not expose protocol-level ping frames to JavaScript.
Outgoing queue: while not open, keep messages in a bounded queue and send them in order after reconnecting. Decide what to do when the queue is full (drop the oldest, or reject). Messages should carry ids so the server can ignore duplicates.
Resume: remember the id of the last message received and send it on reconnect, so the server replays the gap. Without that, the client should ask for a fresh snapshot of the state.
Close codes: treat authentication failures and policy errors (for example code 1008 or 4401) as fatal, and do not retry them in a loop. Retry on network failures and normal server restarts.
Visibility and network hints: pause or slow down when the tab is hidden, and try early when the browser fires the online event.
Cleanup: remove timers and listeners on close so a stopped client does not retry, and guard against late events from an old socket instance.
Tests: inject the socket class and the timers, as the example does.
Libraries such as Socket.IO and reconnecting-websocket already do most of this, but interviewers ask for the design.
javascript
const { mock } = require('node:test');
mock.timers.enable({ apis: ['setTimeout', 'setInterval'] });
class FakeSocket {
static instances = [];
constructor(url) {
this.url = url;
this.sent = [];
this.readyState = 0;
FakeSocket.instances.push(this);
}
send(data) { this.sent.push(data); }
close(code = 1000) { this.readyState = 3; this.onclose?.({ code }); }
open() { this.readyState = 1; this.onopen?.(); }
receive(data) { this.onmessage?.({ data }); }
}
function createClient({ url, SocketClass, random, baseMs = 100, maxMs = 1000, pingMs = 500, pongMs = 200, maxAttempts = 5, log }) {
let socket = null;
let attempt = 0;
let state = 'closed';
let lastId = 0;
let retryTimer = null;
let pingTimer = null;
let pongTimer = null;
const queue = [];
const setState = (next) => { state = next; log(`state: ${next}`); };
const clearBeat = () => { clearInterval(pingTimer); clearTimeout(pongTimer); };
function connect() {
setState('connecting');
const current = new SocketClass(`${url}?lastId=${lastId}`);
socket = current;
current.onopen = () => {
if (socket !== current) return;
attempt = 0;
setState('open');
while (queue.length) current.send(queue.shift());
pingTimer = setInterval(() => {
current.send('ping');
pongTimer = setTimeout(() => { log('no pong, closing'); current.close(4000); }, pongMs);
}, pingMs);
};
current.onmessage = ({ data }) => {
if (socket !== current) return;
if (data === 'pong') return clearTimeout(pongTimer);
lastId = JSON.parse(data).id;
log(`received id ${lastId}`);
};
current.onclose = ({ code }) => {
if (socket !== current || state === 'stopped') return;
clearBeat();
if (code === 4401 || attempt >= maxAttempts) return setState('stopped');
const ceiling = Math.min(maxMs, baseMs * 2 ** attempt);
const delay = Math.round(ceiling / 2 + (random() * ceiling) / 2);
attempt++;
setState('waiting');
log(`retry ${attempt} in ${delay} ms (ceiling ${ceiling})`);
retryTimer = setTimeout(connect, delay);
};
}
return {
connect,
send(message) {
if (state === 'open') socket.send(message);
else queue.push(message);
},
stop() {
clearTimeout(retryTimer);
clearBeat();
setState('stopped');
socket?.close(1000);
},
state: () => state,
};
}
const lines = [];
const client = createClient({ url: 'wss://example.test/feed', SocketClass: FakeSocket, random: () => 0.5, log: (line) => lines.push(line) });
const last = () => FakeSocket.instances.at(-1);
client.connect();
client.send('hello while connecting');
last().open();
last().receive(JSON.stringify({ id: 7 }));
console.log('sent after open:', last().sent);
mock.timers.tick(500);
last().receive('pong');
mock.timers.tick(500);
mock.timers.tick(200);
console.log('after a missed pong:', client.state());
mock.timers.tick(10000);
console.log('reconnected with resume id:', last().url);
last().open();
client.send('queued message');
console.log('state:', client.state(), '| sent:', last().sent);
for (let i = 0; i < 6; i++) {
last().close(1006);
mock.timers.tick(5000);
}
console.log('gave up after the attempts:', client.state(), '| sockets created:', FakeSocket.instances.length);
console.log(lines.join('\n'));
mock.timers.reset();
Run with Node.js v24.22.1 as js-194.js; two runs gave identical output.
Output:
sent after open: [ 'hello while connecting' ]
after a missed pong: waiting
reconnected with resume id: wss://example.test/feed?lastId=7
state: open | sent: [ 'queued message' ]
gave up after the attempts: stopped | sockets created: 7
state: connecting
state: open
received id 7
no pong, closing
state: waiting
retry 1 in 75 ms (ceiling 100)
state: connecting
state: open
state: waiting
retry 1 in 75 ms (ceiling 100)
state: connecting
state: waiting
retry 2 in 150 ms (ceiling 200)
state: connecting
state: waiting
retry 3 in 300 ms (ceiling 400)
state: connecting
state: waiting
retry 4 in 600 ms (ceiling 800)
state: connecting
state: waiting
retry 5 in 750 ms (ceiling 1000)
state: connecting
state: stopped
Key points
Explicit states and exponential backoff with jitter; reset after a stable connection.
Application-level ping and pong timeout detects half-open connections.
Bounded outgoing queue flushed on open; message ids allow deduplication.
Resume with a last received id or ask for a snapshot.
Do not retry fatal close codes; clean up timers and ignore events from old sockets.
Common mistakes
Reconnecting in a tight loop with no backoff or jitter.
Trusting the open state without a heartbeat.
Retrying authentication failures forever.
Handling events from an old socket after a new one was created.
Follow-ups
Why does jitter matter after a server restart?
How would you resume without duplicate messages?
How do you test this without a real server?
Tips
Draw the states and say what triggers each change.
Explain half-open connections as the reason for pings.
Mention close codes, ids, and cleanup.
195.javascript-0195Mediummid
How would you implement undo and redo, and how do you handle limits, grouping fast edits, and branching?
Keep three parts: a past stack, the present state, and a future stack. A new change pushes the present to the past and clears the future, undo moves the present to the future and pops the past, and redo does the reverse. Use immutable snapshots or reversible commands, cap the history size, and group rapid edits, such as typing, into one step with a key and a time window.
Full answer
Two common designs:
Snapshots (state history): store past: [], present, future: [] of immutable states. Easy to build and verify, and works well when state is small or updates share structure (spread copies or an immutable library). Memory grows with each step, so cap the size.
Commands (the command pattern): each action is an object with do() and undo() (or a patch and its inverse). Memory is small and large documents work, but every action needs a correct inverse, which is hard to get right.
Rules for either design:
A new change after undo clears the future stack. This is what users expect in a linear history. Tree histories keep branches but need a more complex UI.
Undo and redo themselves must not be recorded as changes.
Cap the history (for example 100 steps) and drop the oldest entries.
Group related changes: typing characters should not produce one undo step per key. Use a coalesceKey and a time window, so consecutive changes with the same key within a short delay merge into one step. A pause, a different key, or an explicit commit() starts a new step.
Not everything belongs in history: UI state such as scroll position or hover usually does not. Keep the history for document data.
Skip no-op changes (the new state is the same reference as the old).
Expose canUndo and canRedo for the buttons, plus keyboard shortcuts (Ctrl or Cmd with Z, and Shift to redo) that do not hijack text inputs which have their own undo.
Server sync: undo after saving usually creates a new change, not a rewind of the server history.
Time and randomness should be injected so tests are stable.
Pitfall: mutating the state in place makes all stored snapshots point to the same object, so undo seems to do nothing. Always create new objects for new states.
javascript
function createHistory(initial, { limit = 100, windowMs = 500, now = Date.now } = {}) {
let past = [];
let present = initial;
let future = [];
let lastKey = null;
let lastTime = -Infinity;
return {
get state() { return present; },
get canUndo() { return past.length > 0; },
get canRedo() { return future.length > 0; },
get size() { return past.length; },
change(next, coalesceKey = null) {
if (Object.is(next, present)) return false;
const time = now();
const merge = coalesceKey !== null && coalesceKey === lastKey && time - lastTime <= windowMs && past.length > 0;
if (!merge) {
past.push(present);
if (past.length > limit) past.shift();
}
present = next;
future = [];
lastKey = coalesceKey;
lastTime = time;
return true;
},
undo() {
if (!past.length) return false;
future.push(present);
present = past.pop();
lastKey = null;
return true;
},
redo() {
if (!future.length) return false;
past.push(present);
present = future.pop();
lastKey = null;
return true;
},
commit() { lastKey = null; },
};
}
let clock = 0;
const history = createHistory({ text: '', bold: false }, { limit: 4, windowMs: 300, now: () => clock });
const type = (char, at) => {
clock = at;
history.change({ ...history.state, text: history.state.text + char }, 'typing');
};
type('H', 0); type('e', 100); type('y', 200);
console.log('fast typing is one step:', JSON.stringify(history.state), '| steps:', history.size);
type('!', 1000);
console.log('after a pause, a new step:', history.state.text, '| steps:', history.size);
history.change({ ...history.state, bold: true });
console.log('different change:', JSON.stringify(history.state), '| steps:', history.size);
history.undo();
console.log('undo:', JSON.stringify(history.state), '| canRedo:', history.canRedo);
history.undo();
console.log('undo again:', JSON.stringify(history.state));
history.redo();
console.log('redo:', JSON.stringify(history.state));
history.change({ text: 'new branch', bold: false });
console.log('new change clears redo:', history.canRedo, '| state:', history.state.text);
console.log('same reference is ignored:', history.change(history.state), '| steps:', history.size);
for (let i = 1; i <= 6; i++) history.change({ text: 'step ' + i, bold: false });
let undone = 0;
while (history.undo()) undone++;
console.log('limit of 4 keeps only 4 undo steps:', undone, '| oldest state reachable:', history.state.text);
const badHistory = createHistory({ items: [] });
badHistory.state.items.push('mutated in place');
badHistory.change(badHistory.state);
console.log('mutation breaks history (same reference, no step):', badHistory.canUndo);
Run with Node.js v24.22.1 as js-195.js; two runs gave identical output.
Output:
fast typing is one step: {"text":"Hey","bold":false} | steps: 1
after a pause, a new step: Hey! | steps: 2
different change: {"text":"Hey!","bold":true} | steps: 3
undo: {"text":"Hey!","bold":false} | canRedo: true
undo again: {"text":"Hey","bold":false}
redo: {"text":"Hey!","bold":false}
new change clears redo: false | state: new branch
same reference is ignored: false | steps: 3
limit of 4 keeps only 4 undo steps: 4 | oldest state reachable: step 2
mutation breaks history (same reference, no step): false
Key points
Snapshots use past, present, and future; commands store do and undo pairs.
A new change clears the future; undo and redo are not recorded.
Cap the history and merge rapid edits with a key and a time window.
Keep only document data in history; skip no-op changes.
Never mutate stored states; expose canUndo and canRedo.
Common mistakes
Mutating the current state, so all snapshots share the same object.
Recording undo and redo as changes.
Creating one undo step per keystroke.
Letting the history grow with no limit.
Follow-ups
How would you implement undo with commands instead of snapshots?
How would you undo changes in a collaborative document?
What would a branching history look like?
Tips
Describe past, present, and future before writing code.
Mention grouping and limits; they show experience.
Say why immutability is needed.
196.javascript-0196Hardsenior
How do you model UI or async flows with a finite state machine, and what problems does it solve compared with boolean flags?
A finite state machine lists the allowed states and the events that move between them, so impossible combinations such as loading and error at the same time cannot exist. Define a transition table with optional guards and actions, reject unknown events, and make state changes go through one function. This makes flows easy to test, draw, and extend.
Full answer
Many UI bugs come from independent boolean flags: isLoading, hasError, isSuccess. Four booleans can have 16 combinations, but only a few are valid. A state machine replaces them with one status value from a small set, and lets only the defined transitions happen.
Parts of a machine:
States: idle, loading, success, error. The set is finite and named.
Events: FETCH, RESOLVE, REJECT, RETRY, RESET.
Transitions: a table { state: { event: nextState } }. An event that is not listed for the current state is ignored or reported as an error. For example, FETCH while loading does nothing, so double submit bugs disappear.
Guards: conditions that must be true for a transition, such as retries < 3.
Actions (effects): code that runs on entering, leaving, or on a transition, such as starting a request or setting a timer. Keep the transition function pure and run effects outside it, or return a description of the effects.
Context (extended state): data that goes along with the state, such as the retry count and the last error.
Hierarchical and parallel states (statecharts) handle larger flows, for example a form that is editing while another region manages saving.
Benefits: a single place for the rules, invalid states cannot be represented, easy testing (given state and event, expect next state), and diagrams for communication. Libraries include XState, Robot, and reducers with a status field.
Costs: more code for small flows, and a learning curve. A simple toggle does not need a machine. A good test is whether more than two flags depend on each other.
Also useful for: multi-step wizards, checkout, media players, drag and drop, authentication, and connection handling (like reconnecting sockets).
Run with Node.js v24.22.1 as js-196.js; two runs gave identical output.
Output:
idle --FETCH--> loading
ignored FETCH in loading
loading --RESOLVE--> success
data: {"id":1} | state: success
success --FETCH--> loading
loading --REJECT--> error
error --RETRY--> loading
loading --REJECT--> error
error --RETRY--> loading
loading --REJECT--> error
blocked RETRY in error (guard failed)
blocked RETRY in error (guard failed)
after retries: error | retries: 3 | RETRY is in the table: true (the guard still blocks it)
error --RESET--> idle
reset: idle {"retries":0,"data":null,"error":null}
three booleans allow 8 combinations; the machine has 4 states, one active at a time
Key points
One status from a finite set replaces many booleans and removes impossible combinations.
Transitions are a table of state, event, and next state; unknown events are ignored or flagged.
Guards control when a transition may happen; context carries the data.
Keep the transition pure and run effects separately; make it testable.
Use a machine when several flags depend on each other, not for simple toggles.
Common mistakes
Using several booleans that can contradict each other.
Allowing events in states where they make no sense, such as a second submit while loading.
Mixing side effects into the transition logic, which makes tests hard.
Using a machine for a simple toggle.
Follow-ups
How would you add a delayed transition for an automatic retry?
What is the difference between a state machine and a reducer?
What are parallel and hierarchical states?
Tips
Start with the invalid combinations of booleans.
Draw states and events before coding.
Mention guards, context, and where effects run.
197.javascript-0197Hardsenior
How would you implement a small dependency injection container with singleton and transient lifetimes, scopes, and circular dependency detection?
A container maps tokens to factories. Resolving a token calls its factory with a resolver, caches the instance for singleton lifetime, creates a new one for transient, and keeps a separate cache per scope. Track the resolution path to report circular dependencies and missing registrations clearly. The benefit is that code depends on interfaces and tests can replace a registration.
Full answer
Dependency injection (DI) means a component receives what it needs instead of creating it. An inversion of control (IoC) container automates the wiring.
Core pieces:
Registration: register(token, factory, { lifetime }). A token can be a string, a symbol, or a class. A factory receives the container (or a resolve function) and returns an instance, so dependencies are declared by calling resolve inside the factory. JavaScript has no runtime types, so decorators or reflection metadata are needed for automatic constructor injection, while factories are simple and explicit.
Lifetimes: singleton (one instance for the container), transient (a new instance for each resolve), and scoped (one instance per scope, such as one per request on a server). A singleton must not depend on a scoped service, or the scoped instance will be captured and outlive its scope.
Resolution path: keep a stack of tokens being resolved. If a token appears again, throw an error that shows the cycle (A -> B -> A). Also throw a clear error for a missing registration with the path that led to it.
Child containers and scopes: createScope() returns a container that shares registrations, owns its scoped cache, and delegates singletons to the parent. Overriding a registration in a child is how tests and special cases replace services.
Async factories and disposal: real systems need async creation and a dispose() that closes resources in reverse order of creation.
Testing benefit: swap the real HTTP client for a fake with one registration, with no global mocks.
Trade-offs: containers add indirection, and hidden dependencies can make flows hard to follow. For small apps, passing parameters or using module-level singletons is simpler. Use a container when many components share services and need different lifetimes or test replacements.
Run with Node.js v24.22.1 as js-197.js; two runs gave identical output.
Output:
singleton shared: true | created: 1
transient is new each time: true
GET https://api.example.test/users/1 for request 1
true | same request id in a scope: 1
GET https://api.example.test/users/2 for request 2
singleton shared across scopes: true
override in a child: FAKE /users/9 | parent still real: GET https://api.example.test/x
Circular dependency: a -> b -> c -> a
No registration for "missing"
No registration for "database" (needed by needsMissing)
Key points
Register tokens with factories; resolve inside factories to declare dependencies.
Lifetimes: singleton, transient, and scoped; do not capture scoped services in singletons.
Track the resolution stack to detect cycles and report missing tokens with a path.
Child scopes share registrations but own scoped instances; overrides help tests.
Consider async creation and disposal; avoid containers when plain parameters are enough.
Common mistakes
Letting a singleton hold a scoped service.
Missing cycle detection, which causes a stack overflow.
Using a container as a global service locator everywhere.
Hiding dependencies so that no one can see what a function needs.
Follow-ups
How would you add async factories and disposal?
How do decorators or metadata enable constructor injection?
When would you skip a container entirely?
Tips
Define dependency injection in one sentence before the code.
Mention lifetimes and the captive dependency problem.
Show how testing becomes simpler.
198.javascript-0198Hardsenior
How would you build a worker pool that runs CPU-heavy tasks in parallel with a limit, a queue, and error handling?
Start a fixed number of workers, keep an idle list and a task queue, give each task an id, send it to an idle worker with postMessage, resolve the matching promise when the worker replies, and give the worker the next queued task. Handle task errors, worker crashes, timeouts, and a close method that waits for running tasks. The pool size should be close to the number of CPU cores.
Full answer
JavaScript runs one thread of code, so CPU-heavy work such as hashing, image processing, or parsing blocks the event loop. Workers (Worker in browsers, worker_threads in Node.js) run code in parallel threads and communicate by messages. Creating a worker is expensive, so a pool reuses a fixed set of them.
Pool design:
Size: about the number of cores (navigator.hardwareConcurrency or os.availableParallelism()), leaving one core for the main thread when the main thread is busy. More workers than cores do not speed up CPU work.
Queue: tasks wait in a FIFO queue when all workers are busy. Optionally add priorities and a maximum queue length that rejects new tasks for backpressure.
Protocol: send { id, payload } and receive { id, result } or { id, error }. A map from id to { resolve, reject } links replies to promises. A worker handles one task at a time, so it is easy to track which task it is running.
Errors: a task that throws returns an error message and the worker stays alive. An uncaught exception or exit kills the worker: reject its current task, replace the worker, and continue.
Timeouts and cancellation: for runaway tasks, terminate the worker and start a new one, because a synchronous loop cannot be interrupted any other way. Support an AbortSignal for queued tasks.
Data transfer: messages are copied with structured clone, which costs time for big data. Use transferables (ArrayBuffer) to move data without copying, or SharedArrayBuffer with care.
Shutdown: close() stops accepting tasks, waits for running tasks, and terminates workers so the process or page can exit.
When not to use it: I/O-bound work is already concurrent through the event loop, and small tasks may cost more in message passing than they save.
Measure: compare total time with and without the pool on a real workload, since startup and copying overhead can erase the gains.
Run with Node.js v24.22.1 as js-198.js; two runs gave identical output.
Output:
results in submission order: [ 6765, 75025, 55, 832040, 610, 17711 ]
sleep tasks: 4 | most tasks running at once: 2 (pool size 2)
error does not stop the pool: [ 'RangeError: unknown task nope', 5 ]
after close: pool is closed
Key points
Workers run CPU-heavy code in parallel; a pool reuses a fixed number of them.
Queue tasks; send each to an idle worker and match replies by id.
Task errors reject the promise; crashed workers are replaced; timeouts terminate the worker.
Use transferables for large data; close the pool to let the process exit.
Do not use workers for I/O-bound or tiny tasks.
Common mistakes
Creating a new worker for every task.
Starting more workers than CPU cores for CPU-bound work.
Sending huge data by copy instead of transferring it.
Forgetting to terminate workers, which keeps the process alive.
Follow-ups
How would you handle a task that runs forever?
When would a SharedArrayBuffer help?
How does this differ from the browser Web Worker API?
Tips
State the pool size rule and why more is not better.
Describe the id based message protocol.
Mention that I/O-bound work does not need workers.
199.javascript-0199Hardsenior
How would you implement a JSON diff that produces patch operations, and a function that applies them?
Walk both values together. For objects, compare keys: removed keys become remove operations, new keys become add operations, and shared keys recurse. For arrays, compare by index and handle length changes. Describe each operation with a path in JSON Pointer form, apply patches without mutating the input, and test the property that apply(a, diff(a, b)) equals b, including a randomized round-trip test.
Full answer
A diff and patch pair is used for syncing state, audit logs, undo history, and sending small updates instead of whole documents. The standard format is JSON Patch (RFC 6902) with operations add, remove, and replace (also move, copy, and test), and paths written as JSON Pointers (RFC 6901).
Algorithm for the simple version:
If both values are the same by Object.is, no operation.
If both are plain objects: for every key only in a, emit remove. For every key only in b, emit add. For keys in both, recurse with the path extended by the key.
If both are arrays: compare index by index for the shared length and recurse. If b is longer, emit add for new indexes. If b is shorter, emit remove for the extra indexes from the end to the start, so earlier removals do not shift later indexes.
Otherwise (different types or different primitives), emit replace with the new value.
Details that matter:
JSON Pointer escaping: ~ becomes ~0 and / becomes ~1, so keys such as a/b are encoded correctly. The root path is the empty string.
Distinguish plain objects, arrays, and null (typeof null is 'object'). Dates and class instances are not JSON, so convert them first.
The index-based array diff is simple and can be wasteful. Inserting at the front produces many replaces. Smarter versions use a longest common subsequence or keys for items, and produce move operations.
Applying: copy the structure along the changed path instead of mutating the input (structural sharing keeps unchanged parts), apply operations in order, and fail clearly for a missing path. Add test operations when conflicts matter.
Values must be cloned into the patch, or later changes to the source object would change the patch.
Order matters: remove array items from the end, and apply object operations independent of order.
Large documents: avoid deep recursion limits, and consider hashing subtrees to skip equal parts.
Property test: for random pairs of documents, apply(a, diff(a, b)) must deep-equal b, and a must not change. This catches the most bugs, and is better than a few handwritten examples.
javascript
const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
const escape = (key) => String(key).replaceAll('~', '~0').replaceAll('/', '~1');
const unescape = (key) => key.replaceAll('~1', '/').replaceAll('~0', '~');
const clone = (v) => structuredClone(v);
function diff(a, b, path = '', ops = []) {
if (Object.is(a, b)) return ops;
if (isObject(a) && isObject(b)) {
for (const key of Object.keys(a)) if (!(key in b)) ops.push({ op: 'remove', path: `${path}/${escape(key)}` });
for (const key of Object.keys(b)) {
if (!(key in a)) ops.push({ op: 'add', path: `${path}/${escape(key)}`, value: clone(b[key]) });
else diff(a[key], b[key], `${path}/${escape(key)}`, ops);
}
} else if (Array.isArray(a) && Array.isArray(b)) {
const shared = Math.min(a.length, b.length);
for (let i = 0; i < shared; i++) diff(a[i], b[i], `${path}/${i}`, ops);
for (let i = shared; i < b.length; i++) ops.push({ op: 'add', path: `${path}/${i}`, value: clone(b[i]) });
for (let i = a.length - 1; i >= b.length; i--) ops.push({ op: 'remove', path: `${path}/${i}` });
} else {
ops.push({ op: 'replace', path, value: clone(b) });
}
return ops;
}
function applyPatch(doc, ops) {
let result = clone(doc);
for (const { op, path, value } of ops) {
if (path === '') {
result = clone(value);
continue;
}
const keys = path.split('/').slice(1).map(unescape);
const last = keys.pop();
let parent = result;
for (const key of keys) {
if (parent == null || !(key in Object(parent))) throw new Error(`path not found: ${path}`);
parent = parent[key];
}
if (parent == null || typeof parent !== 'object') throw new Error(`path not found: ${path}`);
if (Array.isArray(parent)) {
const index = last === '-' ? parent.length : Number(last);
if (op === 'remove') parent.splice(index, 1);
else if (op === 'add') parent.splice(index, 0, clone(value));
else parent[index] = clone(value);
} else if (op === 'remove') delete parent[last];
else parent[last] = clone(value);
}
return result;
}
const before = { name: 'Asha', tags: ['a', 'b', 'c'], address: { city: 'Pune', zip: '411001' }, 'a/b': 1, 'x~y': 2 };
const after = { name: 'Asha K', tags: ['a', 'z'], address: { city: 'Pune', country: 'IN' }, 'a/b': 2, 'x~y': 2, extra: [1] };
const patch = diff(before, after);
console.log(patch.map((o) => `${o.op} ${o.path}` + ('value' in o ? ' = ' + JSON.stringify(o.value) : '')).join('\n'));
const rebuilt = applyPatch(before, patch);
console.log('round trip equal:', JSON.stringify(rebuilt) === JSON.stringify(after), '| input unchanged:', before.tags.length === 3 && before.name === 'Asha');
console.log('no changes gives an empty patch:', diff(after, structuredClone(after)).length);
console.log('type change is a replace:', JSON.stringify(diff({ a: [1] }, { a: { x: 1 } })), '| null vs object:', JSON.stringify(diff({ a: null }, { a: {} })));
console.log('root replace:', JSON.stringify(diff(1, 2)), JSON.stringify(applyPatch(1, [{ op: 'replace', path: '', value: 2 }])));
try { applyPatch({}, [{ op: 'replace', path: '/missing/deep', value: 1 }]); } catch (error) { console.log('bad path:', error.message); }
const front = diff({ list: [1, 2, 3] }, { list: [0, 1, 2, 3] });
console.log('insert at the front with an index diff:', front.length, 'operations');
function mulberry32(seed) {
return () => {
seed |= 0; seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function randomValue(rand, depth = 0) {
const kind = Math.floor(rand() * (depth > 2 ? 4 : 6));
if (kind === 0) return Math.floor(rand() * 5);
if (kind === 1) return ['x', 'y', 'a/b', 'k~'][Math.floor(rand() * 4)];
if (kind === 2) return rand() < 0.5 ? null : rand() < 0.5;
if (kind === 3) return Math.floor(rand() * 3);
if (kind === 4) return Array.from({ length: Math.floor(rand() * 4) }, () => randomValue(rand, depth + 1));
const object = {};
for (let i = Math.floor(rand() * 4); i > 0; i--) object[['a', 'b', 'c/d', 'e~f'][Math.floor(rand() * 4)]] = randomValue(rand, depth + 1);
return object;
}
function sortKeys(v) {
if (Array.isArray(v)) return v.map(sortKeys);
if (isObject(v)) return Object.fromEntries(Object.keys(v).sort().map((k) => [k, sortKeys(v[k])]));
return v;
}
const rand = mulberry32(2026);
let failures = 0;
const total = 3000;
for (let i = 0; i < total; i++) {
const a = randomValue(rand);
const b = randomValue(rand);
const snapshot = JSON.stringify(a);
const rebuilt = applyPatch(a, diff(a, b));
const same = JSON.stringify(sortKeys(rebuilt)) === JSON.stringify(sortKeys(b));
if (!same || JSON.stringify(a) !== snapshot) failures++;
}
console.log(`random round trips: ${total}, failures: ${failures}`);
Run with Node.js v24.22.1 as js-199.js; two runs gave identical output.
Output:
replace /name = "Asha K"
replace /tags/1 = "z"
remove /tags/2
remove /address/zip
add /address/country = "IN"
replace /a~1b = 2
add /extra = [1]
round trip equal: true | input unchanged: true
no changes gives an empty patch: 0
type change is a replace: [{"op":"replace","path":"/a","value":{"x":1}}] | null vs object: [{"op":"replace","path":"/a","value":{}}]
root replace: [{"op":"replace","path":"","value":2}] 2
bad path: path not found: /missing/deep
insert at the front with an index diff: 4 operations
random round trips: 3000, failures: 0
Key points
Operations add, remove, and replace with JSON Pointer paths; escape ~ and / in keys.
Objects: compare keys and recurse; arrays: compare by index, remove from the end.
Distinguish arrays, plain objects, and null; clone values into the patch.
Apply patches without mutating the input; fail clearly on bad paths.
Test the round trip with random data; consider LCS or keys for better array diffs.
Common mistakes
Treating null as an object, or arrays like objects.
Not escaping slashes and tildes in keys.
Removing array items from the start, which shifts the indexes of later removals.
Mutating the input or putting references to the source into the patch.
Follow-ups
How would you generate move operations for reordered lists?
How would you handle patches that conflict with concurrent changes?
What does the test operation protect against?
Tips
Write the four cases of the algorithm in order.
Mention JSON Pointer escaping and removal from the end.
Offer the random round-trip test.
200.javascript-0200Mediummid
How do you debug JavaScript effectively with browser DevTools, and how do source maps connect minified code to the original source?
Use breakpoints (line, conditional, logpoint, DOM, event, and exception breakpoints), the call stack and scope panels, watch expressions, and the console beyond console.log. A source map is a JSON file that maps positions in generated code back to the original files, so DevTools and error monitors can show the real file, line, and name. Reproduce first, narrow down the cause, and check the network and performance panels when the bug is not in the logic.
Full answer
A good debugging routine matters more than any one tool: reproduce the bug, make the failure small, form a hypothesis, test it, and fix the cause instead of the symptom.
Tools in browser DevTools (Chrome, Firefox, and Safari have similar ones):
Sources panel and the debugger statement pause execution. Breakpoint types: line, conditional (pauses only when an expression is true), logpoint (prints without editing code), DOM change breakpoints (on subtree, attribute, or removal), XHR or fetch breakpoints, event listener breakpoints (click, keydown), and pause on caught or uncaught exceptions.
When paused: the call stack shows how you got here (async stack traces show awaits and promise chains), the scope panel shows local, closure, and global variables, and watch expressions track values. Step over, into, out, and "blackbox" library code you do not want to step into.
Console: console.table for arrays of objects, console.group to organize output, console.error and console.warn with stack traces, console.assert, console.count, console.time, and console.dir. $0 is the selected element, $_ is the last result, and copy(value) copies to the clipboard. Live expressions track values.
Network panel for failed requests, status codes, payloads, timing, CORS errors, and throttling. Performance panel for long tasks and layout work, and Memory panel for heap snapshots to find leaks. Application panel for storage, cookies, and service workers.
Local overrides and "preserve log" help with hard-to-reproduce issues. In Node.js, run node --inspect or --inspect-brk and attach the same DevTools.
Source maps: bundlers and compilers (esbuild, Webpack, Babel, TypeScript) produce minified or transformed code that is hard to read. A .map file (version 3 format) contains sources, names, and mappings, which are encoded segments (VLQ) that map each position in the generated file to a position in an original file. The generated file ends with a //# sourceMappingURL= comment, and DevTools loads the map and shows the original files. Node.js uses --enable-source-maps to rewrite stack traces. Error monitoring tools upload maps and resolve stacks on the server.
Practices: do not publish source maps with source content to the public if the code is private (upload them privately to your error monitor), use sourcesContent when you need the source in DevTools, and keep the map version matched to the deployed file.
Common mistakes: debugging only with console.log in production-like loops, forgetting that a value in the console is a live reference (it shows the current state of an object, not what it was when logged), and fixing symptoms.
javascript
const esbuild = require('esbuild');
const { SourceMap } = require('node:module');
const vm = require('node:vm');
const original = `// price.ts
export function applyDiscount(price, percent) {
if (percent > 100) {
throw new RangeError('percent must be 100 or less');
}
const discountAmount = (price * percent) / 100;
return price - discountAmount;
}
export function checkout(items, percent) {
const total = items.reduce((sum, item) => sum + item.price, 0);
return applyDiscount(total, percent);
}
globalThis.run = () => checkout([{ price: 40 }, { price: 60 }], 150);
`;
const result = esbuild.transformSync(original, {
minify: true,
sourcemap: 'external',
sourcefile: 'price.ts',
format: 'iife',
loader: 'js',
});
const map = JSON.parse(result.map);
console.log('minified code:', result.code.trim().slice(0, 150) + '...');
console.log('map version:', map.version, '| sources:', map.sources, '| names listed:', map.names.length, '| mappings length:', map.mappings.length > 20);
const sandbox = {};
vm.runInNewContext(result.code, sandbox, { filename: 'bundle.min.js' });
let stackLine;
try {
sandbox.run();
} catch (error) {
stackLine = error.stack.split('\n').find((line) => line.includes('bundle.min.js'));
console.log('error:', error.name, error.message);
console.log('minified frame:', stackLine.trim().replace(/\(.*[\\/]/, '('));
}
const [, line, column] = stackLine.match(/bundle\.min\.js:(\d+):(\d+)/);
const sourceMap = new SourceMap(map);
const entry = sourceMap.findEntry(Number(line) - 1, Number(column) - 1);
const originalLines = original.split('\n');
console.log(`mapped back to: ${entry.originalSource}:${entry.originalLine + 1}:${entry.originalColumn + 1}`);
console.log('original code at that position:', originalLines[entry.originalLine].trim());
const withContent = esbuild.transformSync('const answer = 40 + 2;\nconsole.log(answer);', { sourcemap: 'external', sourcefile: 'a.js', sourcesContent: true });
console.log('sourcesContent included:', Array.isArray(JSON.parse(withContent.map).sourcesContent));
const user = { name: 'Asha', tags: ['js'] };
const snapshot = JSON.stringify(user);
user.tags.push('css');
console.log('logged value is live in DevTools; the snapshot taken at log time was:', snapshot);
Run with Node.js v24.22.1 as js-200.js; two runs gave identical output.
Output:
minified code: (()=>{function c(t,o){if(o>100)throw new RangeError("percent must be 100 or less");const r=t*o/100;return t-r}function u(t,o){const r=t.reduce((n,e)=>...
map version: 3 | sources: [ 'price.ts' ] | names listed: 9 | mappings length: true
error: RangeError percent must be 100 or less
minified frame: at c (bundle.min.js:1:38)
mapped back to: price.ts:4:11
original code at that position: throw new RangeError('percent must be 100 or less');
sourcesContent included: true
logged value is live in DevTools; the snapshot taken at log time was: {"name":"Asha","tags":["js"]}
Key points
Use breakpoints of many kinds, the call stack, scope, watch, and async stacks, not only console.log.
Know console.table, group, assert, time, and copy; use the network, performance, and memory panels when relevant.
A source map is JSON that maps generated positions to original files, lines, columns, and names.
Node.js can rewrite stacks with --enable-source-maps; error tools resolve stacks on the server.
Keep maps matched to releases and private when the source is private.
Common mistakes
Debugging only with console.log when a breakpoint would show the whole state.
Shipping source maps with full source to a public site by accident.
Using a map that does not match the deployed file, which shows wrong lines.
Forgetting that console shows live object references.
Follow-ups
How does Node.js apply source maps to stack traces?
What do the mappings in a source map encode?
How would you debug an issue that only happens in production?
Tips
Start with the debugging routine, then the tools.
Name conditional breakpoints and logpoints; they are underused.
Explain a source map as a lookup from generated position to original position.