Quiz · Medium
Twenty-two questions on array methods, promises and the event loop, fetch, DOM nodes, events and delegation, storage and JSON, including diagram questions.
Which array method returns a new array containing only the elements that pass a test?
filter
reduce
find
some
filter returns every element for which the callback is truthy, as a new array. find returns just the first match (or undefined), some returns a boolean, and reduce folds everything into one value.
What does this code print?
const a = [1, 2, 3, 4];
const removed = a.splice(1, 2);
console.log(a, removed);[1, 2, 3, 4] [2, 3]
[2, 3] [1, 4]
[1, 4] [2, 3]
[1, 3] [2]
splice(1, 2) removes two elements starting at index 1 from the original array (leaving [1, 4]) and returns the removed ones ([2, 3]). slice would not have changed a.
What is the correct way to sort [10, 9, 1] into ascending numeric order?
nums.sort((a, b) => a > b)
nums.sort((a, b) => a - b)
nums.sort()
nums.sortNumbers()
The default sort() compares elements as strings and gives [1, 10, 9]. A comparator returning a number (negative, zero, positive) is required; returning a boolean (a > b) is unreliable. sortNumbers does not exist.
fetch('/api/missing') receives an HTTP 404 response. What happens to the returned promise?
It never settles
It still fulfills; you must check response.ok and handle the error yourself
It fulfills with null
It rejects with a 404 error
fetch only rejects for network-level failures (offline, DNS, CORS, abort). A response with status 404 or 500 is a successful HTTP exchange, so the promise fulfills and response.ok is false.
In the diagram of the JavaScript runtime, where does a finished setTimeout callback wait before the event loop moves it to the call stack?

Directly on the call stack
In the heap
In the callback (task) queue
In the Web APIs box
When the timer (handled by the Web APIs) expires, its callback is placed in the callback/task queue. The event loop pushes it onto the call stack only when the stack is empty. The heap stores objects, and the call stack runs code.
Image: Byteslovesbits, CC BY-SA 4.0, via Wikimedia Commons.
What does this code print?
async function f() {
console.log('A');
await null;
console.log('B');
}
f();
console.log('C');A B C
A C B
C A B
B A C
f() runs synchronously until the first await, logging A. The rest of f is queued as a microtask, so the main script continues and logs C. B prints after the script finishes.
What does an async function always return?
A generator
undefined unless it uses await
A promise
The value it returns
Returned values are wrapped in a fulfilled promise and thrown errors become rejected promises, whether or not the function uses await.
Promise.all([p1, p2, p3]) where p2 rejects immediately and the others take a long time. What does Promise.all do?
It waits for all three, then rejects
It ignores the rejection and fulfills
It fulfills with the two that succeeded
It rejects right away with p2's reason
Promise.all fails fast: the first rejection rejects the combined promise. Use Promise.allSettled if you want every outcome, even failures.
What does this code print?
const o = Object.freeze({ n: { x: 1 } });
o.n.x = 2;
console.log(o.n.x, Object.isFrozen(o), Object.isFrozen(o.n));1 true true
2 true false
2 false false
1 true false
Object.freeze is shallow: o itself is frozen, but the nested object o.n is a different object that remains mutable, so x changes to 2.
What does this code print?
console.log(['1', '2', '3'].map(parseInt));[NaN, NaN, NaN]
[1, 2, 3]
[1, NaN, NaN]
[1, 2, NaN]
map calls parseInt(value, index, array), so the index is the radix: parseInt('2', 1) and parseInt('3', 2) are NaN. Use .map(Number) or .map(s => parseInt(s, 10)).
What kind of DOM node is the string "A heading" in the tree shown?

An attribute of the <h1> element
A comment node
An element node
A text node that is a child of the <h1> element
Text inside an element is stored as a separate text node in the DOM. Attributes (like href in the diagram) are attached to elements, and elements are the tag-based nodes.
Image: Birger Eriksson, CC BY-SA 3.0, via Wikimedia Commons.
A page inserts a comment typed by a user with element.innerHTML = comment. What is the danger?
Nothing; innerHTML escapes input automatically
The page becomes slower
Cross-site scripting (XSS): the string is parsed as HTML, so injected markup such as <img onerror=...> can run script
The comment is stored in localStorage
innerHTML interprets the string as HTML. For plain text, use textContent, which inserts text without parsing markup. If HTML is required, sanitize it first.
A list has hundreds of <li> elements and you want one click handler. Which property tells you which child was clicked?
event.this
event.parent
event.target
event.currentTarget
With event delegation the listener sits on the <ul>: currentTarget is the <ul> (where the listener lives) while target is the element that was actually clicked (often an <li> or something inside it). event.this and event.parent do not exist.
A button is inside a div, and both have a click listener (default bubbling). Which runs first when the button is clicked?
Only the button's
The div's listener, then the button's
The button's listener, then the div's
Both at the same time
By default, events bubble: they fire on the target first and then travel up through ancestors. Capturing listeners ({ capture: true }) would run from the outside in, first.
Which of these returns a live collection that updates automatically when the DOM changes?
document.getElementsByClassName('item')
Array.from(document.querySelectorAll('.item'))
document.querySelectorAll('.item')
document.querySelector('.item')
getElementsByClassName returns a live HTMLCollection. querySelectorAll returns a static NodeList, Array.from makes a snapshot array, and querySelector returns a single element.
What does event.preventDefault() do on a form's submit event?
Stops the event from bubbling
Validates the form fields
Stops the browser from submitting and reloading the page, so you can handle the data with JavaScript
Removes the event listener
preventDefault cancels the default action. stopPropagation is the one that stops bubbling. Validation is done by the browser's constraint validation or your own code.
True or False: data stored in localStorage is sent to the server with every HTTP request.
True
False
localStorage lives only in the browser and is never sent automatically. Cookies are the storage that is attached to each request to the matching domain.
What is the difference between DOMContentLoaded and load?
DOMContentLoaded waits for all images
DOMContentLoaded fires when the HTML is parsed; load fires later, after images and other resources finish loading
They are identical
load fires first, then DOMContentLoaded
DOMContentLoaded does not wait for stylesheets, images or subframes (only for deferred scripts). window.onload waits for everything.
What does this code print?
console.log(JSON.stringify({ a: undefined, b: 1, c: () => 2, d: null }));{"b":1}
{"a":undefined,"b":1,"d":null}
{"b":1,"d":null}
{"a":null,"b":1,"c":null,"d":null}
JSON.stringify omits properties whose values are undefined, functions or symbols, but keeps null. (Inside arrays those values become null.)
What does this code print?
console.log([...new Set('hello')].join(''));helo
hello
hel
lo
A Set keeps unique values in insertion order, so the repeated l is dropped: h, e, l, o. Strings are iterable by character, which is why new Set('hello') works.
What does this code print?
function f(x = 10) { return x; }
console.log(f(undefined), f(null), f(0), f());undefined null 0 undefined
10 null 10 10
10 10 10 10
10 null 0 10
A default parameter is used only when the argument is undefined (or missing). null and 0 are real values and are kept.
What is the main advantage of Promise.allSettled over Promise.all for a dashboard that loads several independent widgets?
It retries failed promises
It runs the promises sequentially
It waits for every promise and reports each success or failure, so one failure does not hide the others
It runs faster than Promise.all
allSettled never rejects; each result is { status: 'fulfilled', value } or { status: 'rejected', reason }. Both run the promises concurrently; neither retries.