Unit 5: Interactive Web Development - Practice Quiz
1 Which JavaScript loop is commonly used to repeat a block of code a known number of times?
if statement
try statement
switch statement
for loop
2 Which keyword immediately ends the execution of a JavaScript loop?
return
continue
yield
break
3 What is a higher order function in JavaScript?
4 What is a callback function?
5 What does DOM stand for in web development?
6
Which method selects an element by its id attribute?
document.getElementById()
document.getElementsByName()
document.addEventListener()
document.createElement()
7 Which property can be used to change only the text inside a DOM element?
textContent
nodeName
ownerDocument
classList
8 Which method attaches an event handler to a DOM element?
addEventListener()
querySelector()
createElement()
removeAttribute()
9 Which DOM method creates a new HTML element?
document.querySelector()
document.createElement()
document.getElementById()
document.removeEventListener()
10 Which practice helps make a custom JavaScript control usable with a keyboard?
11 Which HTML attribute makes a form field mandatory before submission?
readonly
disabled
required
multiple
12 Which JavaScript method checks whether a regular expression matches a string?
slice()
push()
join()
test()
13 Which JavaScript object is used to work with dates and times?
Calendar
Time
Date
Clock
14 Which media event fires when audio or video playback begins?
ended
volumechange
pause
play
15 Which Web Storage object keeps data after the browser is closed and reopened?
sessionStorage
navigator
history
localStorage
16
Which method stores a value in sessionStorage?
removeItem()
clear()
setItem()
getItem()
17
What does the JavaScript fetch() function return?
Promise
18 Which method converts a JSON string into a JavaScript value?
JSON.convert()
JSON.parse()
JSON.format()
JSON.stringify()
19 Which method requests the user's current geographic position?
navigator.geolocation.getCurrentPosition()
navigator.location.getPosition()
navigator.geolocation.clearWatch()
navigator.position.getLocation()
20 Which HTML attribute generally enables an element to be dragged?
movable="true"
draggable="true"
selectable="true"
droppable="true"
21
What is printed by this code?
let total = 0;
for (let i = 1; i <= 4; i++) {
if (i === 3) continue;
total += i;
}
console.log(total);
22
Which expression returns a new array containing the squares of all even numbers in numbers?
23
What is the main purpose of passing a callback to setTimeout?
24 What does the DOM represent in a web browser?
25
Which code changes the text of the first element with the class status without interpreting the assigned value as HTML?
26 A button is created dynamically after the page loads. Which approach reliably handles its click event?
preventDefault() on the document during page loading
27 Which method is generally safest when adding user-provided text to a newly created paragraph element?
paragraph.textContent to the user-provided text
paragraph.innerHTML to the user-provided text
document.write() after page load
28 Which practice best improves keyboard accessibility for a custom clickable control?
<button> element whenever the control performs an action
aria-hidden="true"
div and rely only on a mouse click listener
29 Why should client-side form validation be combined with server-side validation?
30
What does the regular expression /^[A-Z][a-z]+$/ match?
31
Which statement correctly creates a Date object representing the current date and time?
32 Which event is most appropriate for updating a progress indicator as a video plays?
play, because it fires continuously during playback
loadeddata, because it fires for every elapsed second
timeupdate, because it fires when the playback position changes
ended, because it fires whenever the current time changes
33
Which statement correctly describes the difference between localStorage and sessionStorage?
localStorage stores objects directly, while sessionStorage stores only arrays
localStorage is available only to server-side code, while sessionStorage is client-side
localStorage is deleted on refresh, while sessionStorage remains permanently
localStorage lasts across browser sessions, while sessionStorage is tied to a page session
34
How should an array named tasks be stored in localStorage?
35
Which code correctly processes a successful JSON response from fetch('/api/users')?
36
Why should code check response.ok after calling fetch?
fetch rejects automatically for every HTTP error status
response.ok converts the response body into JSON
response.ok indicates whether the HTTP status represents success
37 Which code requests the user's current location and handles the returned coordinates?
38
Why is event.preventDefault() commonly called in a dragover handler?
dragend event immediately
39
What is the key difference between querySelector and querySelectorAll?
querySelector changes elements, while querySelectorAll only reads attributes
querySelector selects only IDs, while querySelectorAll selects only classes
querySelector returns the first match, while querySelectorAll returns a collection of matches
querySelector returns HTML strings, while querySelectorAll returns CSS rules
40
What does calling event.preventDefault() in a form's submit event handler do?
41
What is printed by the following code, in order?
let sum = 0; for (let i = 0; i < 3; i++) { Promise.resolve().then(() => { sum += i; }); } console.log(sum); queueMicrotask(() => console.log(sum));
3 followed by 3
0 followed by 3
0 followed by 0
3 followed by 0
42
What does this memoization code print?
function memoize(fn) { const cache = new Map(); return x => cache.get(x) || (cache.set(x, fn(x)), cache.get(x)); } let calls = 0; const f = memoize(x => { calls++; return x - 1; }); console.log(f(1), f(1), f(2), f(2), calls);
0 0 1 2 4
0 0 1 1 3
0 1 1 1 3
0 0 1 1 2
43
Assuming top-level await is allowed, what does this code print?
function classify(cb) { try { return Promise.resolve(cb()).catch(() => "async"); } catch (e) { return Promise.resolve("sync"); } } console.log(await classify(() => { throw new Error(); })); console.log(await classify(async () => { throw new Error(); }));
sync followed by async
async followed by sync
async followed by async
sync followed by sync
44
A <ul> initially contains four <li> elements with text A, B, C, and D. What is logged?
const live = ul.children; const snapshot = ul.querySelectorAll("li"); for (let i = 0; i < live.length; i++) { live[i].remove(); } console.log(snapshot.length, live.length, ul.textContent);
2 2 "BD"
4 2 "BD"
4 0 ""
2 0 ""
45
A DOM subtree is duplicated using const copy = original.cloneNode(true), where original has descendant elements with IDs and listeners registered using addEventListener. Which statement is correct?
46
Given a button inside outer, what is logged when the button is clicked?
document.addEventListener("click", () => console.log("D"), true); outer.addEventListener("click", e => { console.log("O"); e.stopPropagation(); }, true); button.addEventListener("click", () => console.log("B"));
O then D
D then O then B
D then O
B then O then D
47
An application receives untrusted JSON containing a user's display name and must insert it into a newly created <span>. Which implementation provides the appropriate default protection against HTML injection?
textContent
DOMParser and append its body
<script> tags and use insertAdjacentHTML
innerHTML
48
A design constraint requires a <div> to behave like an enabled button. Which implementation most closely reproduces the essential keyboard interaction expected by assistive-technology and keyboard users?
role="link", tabindex="0", click handling, and arrow-key handling
role="button", tabindex="0", click handling, and Enter/Space key handling
aria-label, tabindex="-1", click handling, and Escape key handling
aria-live="polite", click handling, and Enter-only key handling
49
An input validator calls input.setCustomValidity("Username is unavailable") when an asynchronous check fails. Later, the username becomes available, but form.checkValidity() still returns false. What correction is required?
required attribute before calling checkValidity()
input.setCustomValidity(null) after the value becomes valid
input.setCustomValidity("") after the value becomes valid
form.reset() before repeating the availability check
50 Which JavaScript regular expression matches an ASCII identifier that is 3 to 16 characters long, begins with a letter, contains only letters, digits, or underscores, and includes at least one digit?
/^(?=[A-Za-z0-9_]{3,16}$)(?=.*[A-Za-z])[0-9][A-Za-z0-9_]*$/
/^(?=[A-Za-z0-9_]{3,16})(?=.*[0-9])[A-Za-z_][A-Za-z0-9_]*$/
/^(?=[A-Za-z0-9_]{3,16}$)(?!.*[0-9])[A-Za-z][A-Za-z0-9_]*$/
/^(?=[A-Za-z0-9_]{3,16}$)(?=.*[0-9])[A-Za-z][A-Za-z0-9_]*$/
51
In the America/New_York time zone, d represents local noon on March 9, 2024. After executing const before = d.getTime(); d.setDate(d.getDate() + 1);, approximately how many elapsed hours does d.getTime() - before represent?
52 Which approach correctly handles starting media playback when browser autoplay policy may block it?
media.play() and use playing to detect actual playback
media.play() and use loadedmetadata to detect actual playback
media.autoplay = true and use durationchange as proof of playback
media.load() and use canplay as proof of playback
53
Tab A and Tab B are separate top-level tabs on the same origin. Tab A executes localStorage.setItem("theme", "dark"). Assuming the value changes, which behavior is expected?
storage event, while Tab B does not receive it
storage event, while Tab A does not receive it
storage events for the change
54
Two same-origin tabs concurrently run const n = Number(localStorage.getItem("count") || 0); localStorage.setItem("count", String(n + 1)); when count is initially 0. Which result is possible after both finish?
0 because concurrent writes cancel one another
1 because both tabs can overwrite based on the same read
2 because each read-modify-write is atomic
55
A server responds to fetch() with HTTP 404 and a valid JSON error body. What happens if the request is not interrupted by a network failure?
response.json() is called immediately
200-299
response.ok or status
56
A successful DELETE request returns HTTP 204 No Content. What is the likely result of unconditionally executing await response.json()?
null because the response has no body
fetch() treats 204 as an error status
{} because 204 implies an empty object
57
Which statement about using navigator.geolocation in a deployed web application is correct?
enableHighAccuracy is set to true
58
A draggable element fires dragstart, but a target element never receives drop in a typical desktop browser. Which target-side change is essential for declaring that the current drag operation may be dropped there?
event.preventDefault() from the source's dragend handler
event.dataTransfer.clearData() from the target's dragover handler
event.preventDefault() from the target's dragover handler
event.stopPropagation() from the target's dragenter handler
59
What is the value of result?
const steps = [x => x + 1, x => x * 2, x => x - 3]; const pipeline = steps.reduce((previous, step) => x => step(previous(x)), x => x); const result = pipeline(5);
3
9
5
1
60
A click listener on <ul id="list"> delegates events to its direct <li> children, but each direct child may contain a nested <ul> with additional <li> elements. Which guard prevents clicks on nested list items from being handled as direct items?
const item = e.target.closest("li"); if (!item || !list.contains(item)) return;
const item = e.target.closest("li"); if (!item || item.parentElement !== list) return;
const item = e.currentTarget.closest("li"); if (!item || item !== list) return;
const item = e.target.querySelector("li"); if (!item || item.parentElement === list) return;
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →