JavaScript · Interview
JavaScript interview questions
Twenty-five original JavaScript interview questions covering state, arrays, maps, validation, browser safety, accessibility, output prediction, debugging and realistic product decisions. Try each answer before opening it; runnable snippets are checked during the build and in the browser.
Jump to a question
ConceptJuniorFor totals keyed by item name, when is Map a better choice than a plain object?
Map a better choice than a plain object?Answer
A Map is a good default when keys are dynamic or are not all strings, and when you want an explicit API such as get, set and size. A plain object is fine for simple string-keyed records, especially when serialising to JSON, but create it with Object.create(null) or check own properties if arbitrary user keys could collide with inherited names. Neither structure sorts keys for a report; sort the entries deliberately before printing.
Predict the outputMid-levelWhat does this code print? Explain why the two shifts are not both active at minute 12.
const shifts = [[9, 12], [12, 15]];
for (const minute of [11, 12]) {
console.log(minute, shifts.filter(([start, end]) => start <= minute && minute < end).length);
}
Answer
It prints one active shift at each minute. The first shift includes 9 through the instant before 12, while the second starts at 12. The comparison minute < end makes the interval half-open: [start, end). This convention avoids double-counting a handover and makes adjacent intervals compose neatly. Replacing the final comparison with <= would incorrectly report two people at the boundary.
It prints
11 1 12 1
CodingMid-levelWrite a function that counts completed tickets per owner and prints owners alphabetically for the sample data below.
Answer
Walk the ticket rows once, skipping unfinished tickets and incrementing the owner's count in a Map. Convert the entries to an array only for the final alphabetical report. Maya has two completed tickets and Leo has one; the unfinished Maya ticket is ignored. Separating aggregation from sorting makes the function reusable. In a real product, confirm whether unknown owners should be grouped or rejected before presenting totals.
const tickets = [
{ owner: 'maya', done: true }, { owner: 'leo', done: true },
{ owner: 'maya', done: false }, { owner: 'maya', done: true }
];
function completedByOwner(rows) {
const counts = new Map();
for (const row of rows) {
if (row.done) counts.set(row.owner, (counts.get(row.owner) ?? 0) + 1);
}
return [...counts].sort(([a], [b]) => a.localeCompare(b));
}
for (const [owner, count] of completedByOwner(tickets)) console.log(owner, count);
Output
leo 1 maya 2
ScenarioSeniorA task board restores saved JSON from localStorage. How would you make startup resilient and keep user-entered titles safe?
Answer
Parse storage in a try/catch, validate that the result is an array of tasks with expected field types, and fall back to a clear empty state if it is corrupt. Save only the fields the app needs rather than serialising DOM nodes or functions. Render a user-entered title with textContent, not innerHTML, so text cannot become markup. Because localStorage is private to that browser and origin, explain that clearing site data removes the board and offer export if the data matters.
ConceptMid-levelIn a peak-overlap sweep, why should all starts and ends at the same minute be processed together?
Answer
A shift ending at minute t is no longer active at t, while a shift starting at t is active. If you update the peak after each individual event, an arbitrary sort order among equal-minute events can temporarily count both and invent a peak that never exists. Sum every delta at t first, then compare the resulting active count with the best count. Visit times in increasing order and update only on a strictly larger count to preserve the earliest tied minute.
ConceptJuniorWhy should an input validator normally use === instead of ==?
=== instead of ==?Answer
Strict equality compares without coercing types, so the number 0 and the string '0' remain different inputs. Loose equality can silently turn values into one another, making boundary checks surprising. Convert input deliberately with Number or another parser, validate it, then compare strictly.
ConceptJuniorDoes const make a JavaScript array immutable?
const make a JavaScript array immutable?Answer
No. const prevents assigning a different value to the binding, but array methods can still mutate the referenced array. push works while items = [] does not. Use a copied array or a deliberate immutable update when callers must not observe changes.
ConceptMid-levelWhy can value || fallback be wrong for a legitimate zero count?
value || fallback be wrong for a legitimate zero count?Answer
The || operator uses the fallback for every falsy value, including zero, false and an empty string. ?? falls back only for null or undefined. For a count where zero is meaningful, value ?? fallback preserves the real zero instead of replacing it.
ConceptMid-levelWhat trade-off matters when using a Map rather than an object for arbitrary ticket IDs?
Answer
Map has an explicit key API, accepts keys of any type and avoids prototype-name collisions. A plain object is convenient for JSON-shaped records but coerces keys to strings and may inherit properties unless created carefully. Neither choice removes the need to validate ticket IDs.
ConceptJuniorWhy does scores.sort() not reliably sort numeric scores from smallest to largest?
scores.sort() not reliably sort numeric scores from smallest to largest?Answer
Without a comparator, sort compares string representations, so 100 can appear before 20. Use (a, b) => a - b for ascending numeric order, or b - a for descending. Sorting mutates the original array; copy it first when the caller needs the old order.
ConceptMid-levelDoes [...orders] isolate nested order objects from later edits?
[...orders] isolate nested order objects from later edits?Answer
It creates a fresh outer array but copies references to each nested object. Changing copy[0].status also changes the same object visible through the original array. Copy nested records as needed or model updates by replacing the changed object rather than mutating it.
ConceptMid-levelWhen is a Set useful for deduplicating IDs, and when is it insufficient?
Answer
A Set gives fast membership checks and one entry per distinct ID. It retains insertion order, which helps when first-seen order matters, but it does not calculate totals or select the first ID whose second event occurs without scanning the original sequence. Use a Map for counts.
ConceptMid-levelWhy can parseInt('12px', 10) be unsafe for validating a whole-number field?
parseInt('12px', 10) be unsafe for validating a whole-number field?Answer
parseInt accepts the leading digits and stops at the first invalid character, so it turns '12px' into 12. A strict field validator should check the entire token's syntax and then use Number with Number.isSafeInteger and a range check. Parsing and validation are distinct steps.
ScenarioSeniorA saved task-board JSON value is malformed. How should startup behave?
Answer
Parse inside try/catch, validate the shape and field types, and fall back to a usable empty board with a clear recovery message. Do not let a bad localStorage value crash every visit. Preserve the corrupt value for export if recovery matters before overwriting it.
ScenarioMid-levelA user enters <img onerror=...> as a task title. How should it be rendered?
<img onerror=...> as a task title. How should it be rendered?Answer
Assign user text through textContent, which displays the characters literally rather than interpreting them as HTML. Do not concatenate titles into innerHTML. Continue validating length and providing an accessible label; escaping in one view is not a substitute for a safe rendering API.
ScenarioMid-levelA checkout needs a percentage discount. What data representation prevents avoidable cent errors?
Answer
Keep source amounts in integer cents and specify the rounding rule for the percentage before subtraction. If the rule is floor, use Math.floor on the calculated cents; if the domain needs decimal precision beyond cents, use an appropriate decimal library. Document threshold and cap boundaries.
ScenarioSeniorTwo search requests return out of order, so old results overwrite new ones. How would you prevent that?
Answer
Associate each request with an increasing sequence number or abort the earlier request. Before rendering a response, check that it still belongs to the latest query. Also handle failures without clearing a newer result; network completion order is not user-intent order.
ScenarioMid-levelA button action fires twice after rerendering a task list. Where would you look?
Answer
Check whether each render adds another event listener to a persistent element. Attach one listener during setup, or use event delegation on a stable parent and derive the target from the event. A test that rerenders twice and clicks once will expose duplicate handlers.
ScenarioMid-levelAn aggregation report has correct totals but changes row order between runs. What should be fixed?
Answer
Give the report a specific order and tie-break, then sort entries immediately before display. Do not rely on object insertion order to mean alphabetical or highest-first. Add shuffled-input tests so a missing comparator cannot pass by accident.
ScenarioSeniorA filter hides most exercises without telling screen-reader users how many remain. What should the UI do?
Answer
Update a short visible count in a polite aria-live region after the filter changes, keep the form labels explicit, and preserve keyboard focus. Avoid announcing every hidden card. Test both an empty result and a populated result using keyboard and assistive technology.
Predict the outputMid-levelWhat does this code print after mutating a shared array reference?
const a = [1, 2];
const b = a;
b.push(3);
console.log(a.length, b.length);
Answer
It prints 3 3: both a and b refer to the same array, so the push changes the length seen through either name. Assignment does not copy arrays. Copy first when independent state is required.
It prints
3 3
Predict the outputMid-levelWhat are the three printed values when ?? and || receive zero and null?
?? and || receive zero and null?console.log(0 ?? 5);
console.log(0 || 5);
console.log(null ?? 5);
Answer
The lines are 0, 5 and 5. Nullish coalescing keeps a real zero, while logical OR treats zero as falsy. Both operators use the fallback for null in this example. This matters for counts and prices where zero is valid.
It prints
0 5 5
Predict the outputJuniorWhat does sorting these numbers with a numeric comparator print?
const values = [30, 2, 11];
values.sort((a, b) => a - b);
console.log(values);
Answer
It prints [ 2, 11, 30 ] in the site's console format. The comparator returns a negative value when the first number belongs earlier. Without it, default string ordering would place 11 before 2.
It prints
[ 2, 11, 30 ]
DebuggingMid-levelThe counter already contains zero for hall, but this function incorrectly treats it as absent. What is the fix?
hall, but this function incorrectly treats it as absent. What is the fix?The code with the bug
const counts = new Map([['hall', 0]]);
function read(id) { return counts.get(id) ? counts.get(id) : 'missing'; }
console.log(read('hall'));
Answer
The truthiness check rejects zero even though it is a valid stored count. Check presence with has and then read the value. That separates missing keys from keys whose value happens to be falsy, and the fixed program prints zero.
const counts = new Map([['hall', 0]]);
function read(id) { return counts.has(id) ? counts.get(id) : 'missing'; }
console.log(read('hall'));
Output
0
CodingMid-levelWrite a function that counts open tickets per owner and prints the sample owners alphabetically.
Answer
A Map accumulates only open rows, and sorting entries at the output boundary gives a reproducible report. The closed Maya ticket does not count, so Leo has one and Maya has two. Keep aggregation separate from display for easier testing.
const rows = [{owner:'maya',open:true},{owner:'leo',open:true},{owner:'maya',open:false},{owner:'maya',open:true}];
function openCounts(items) {
const counts = new Map();
for (const row of items) if (row.open) counts.set(row.owner, (counts.get(row.owner) ?? 0) + 1);
return counts;
}
for (const [name, count] of [...openCounts(rows)].sort(([a],[b]) => a.localeCompare(b))) console.log(name, count);
Output
leo 1 maya 2
Continue learning
Use checked exercises to test the ideas, review a lesson when you need the explanation, then combine the skills in a project.
How this page was checked. Runnable examples and reference solutions were run with Node.js 22 at build time; runs in your browser in an isolated Web Worker by the publishing checks, and the output shown is what it printed. The Run buttons execute the same code on your device; the site does not upload your code for execution.