Unit 5: Interactive Web Development - Practice Quiz

CSE326 — Internet Programming 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 Which JavaScript loop is commonly used to repeat a block of code a known number of times?

Loops and Iterative Programming Easy
A. if statement
B. try statement
C. switch statement
D. for loop

2 Which keyword immediately ends the execution of a JavaScript loop?

Loops and Iterative Programming Easy
A. return
B. continue
C. yield
D. break

3 What is a higher order function in JavaScript?

Higher Order Functions Easy
A. A function that uses only numbers
B. A function that runs only once
C. A function that accepts or returns functions
D. A function that always returns an object

4 What is a callback function?

Callback Functions Easy
A. A function stored in browser storage
B. A function defined inside an object
C. A function passed to another function
D. A function that reloads a page

5 What does DOM stand for in web development?

DOM Fundamentals Easy
A. Document Order Map
B. Data Operation Method
C. Document Object Model
D. Digital Output Module

6 Which method selects an element by its id attribute?

DOM Selection and Manipulation Easy
A. document.getElementById()
B. document.getElementsByName()
C. document.addEventListener()
D. document.createElement()

7 Which property can be used to change only the text inside a DOM element?

DOM Selection and Manipulation Easy
A. textContent
B. nodeName
C. ownerDocument
D. classList

8 Which method attaches an event handler to a DOM element?

Event Handling Easy
A. addEventListener()
B. querySelector()
C. createElement()
D. removeAttribute()

9 Which DOM method creates a new HTML element?

Dynamic Content Generation Easy
A. document.querySelector()
B. document.createElement()
C. document.getElementById()
D. document.removeEventListener()

10 Which practice helps make a custom JavaScript control usable with a keyboard?

JavaScript Accessibility Practices Easy
A. Remove all text labels
B. Handle relevant keyboard events
C. Disable the focus outline
D. Use only mouse events

11 Which HTML attribute makes a form field mandatory before submission?

Form Validation Easy
A. readonly
B. disabled
C. required
D. multiple

12 Which JavaScript method checks whether a regular expression matches a string?

Regular Expressions Easy
A. slice()
B. push()
C. join()
D. test()

13 Which JavaScript object is used to work with dates and times?

Date and Time Handling Easy
A. Calendar
B. Time
C. Date
D. Clock

14 Which media event fires when audio or video playback begins?

Audio and Video Events Easy
A. ended
B. volumechange
C. pause
D. play

15 Which Web Storage object keeps data after the browser is closed and reopened?

Browser Storage using Web Storage API (Local Storage and Session Storage) Easy
A. sessionStorage
B. navigator
C. history
D. localStorage

16 Which method stores a value in sessionStorage?

Browser Storage using Web Storage API (Local Storage and Session Storage) Easy
A. removeItem()
B. clear()
C. setItem()
D. getItem()

17 What does the JavaScript fetch() function return?

Fetch API and JSON Processing Easy
A. An HTML element
B. A storage object
C. A JSON string
D. A Promise

18 Which method converts a JSON string into a JavaScript value?

Fetch API and JSON Processing Easy
A. JSON.convert()
B. JSON.parse()
C. JSON.format()
D. JSON.stringify()

19 Which method requests the user's current geographic position?

Geolocation API Easy
A. navigator.geolocation.getCurrentPosition()
B. navigator.location.getPosition()
C. navigator.geolocation.clearWatch()
D. navigator.position.getLocation()

20 Which HTML attribute generally enables an element to be dragged?

Drag and Drop API Easy
A. movable="true"
B. draggable="true"
C. selectable="true"
D. droppable="true"

21 What is printed by this code?

JAVASCRIPT
let total = 0;
for (let i = 1; i <= 4; i++) {
  if (i === 3) continue;
  total += i;
}
console.log(total);

Loops and Iterative Programming Medium
A. 7
B. 6
C. 4
D. 10

22 Which expression returns a new array containing the squares of all even numbers in numbers?

Higher Order Functions Medium
A. numbers.forEach(n => n % 2 === 0).map(n => n * n)
B. numbers.filter(n => n % 2 === 0).map(n => n * n)
C. numbers.reduce(n => n % 2 === 0).map(n => n * n)
D. numbers.map(n => n % 2 === 0).filter(n => n * n)

23 What is the main purpose of passing a callback to setTimeout?

Callback Functions Medium
A. To execute the function after the specified delay
B. To execute the function repeatedly at fixed intervals
C. To convert the function into a synchronous operation
D. To prevent the function from accessing outer variables

24 What does the DOM represent in a web browser?

DOM Fundamentals Medium
A. A compiled version of the JavaScript source code
B. A tree-like object representation of the HTML document
C. A browser-specific replacement for CSS stylesheets
D. A database containing all files loaded by the page

25 Which code changes the text of the first element with the class status without interpreting the assigned value as HTML?

DOM Selection and Manipulation Medium
A. document.getElementsByClassName('status').text = value
B. document.querySelectorAll('.status').value = value
C. document.querySelector('.status').innerHTML = value
D. document.querySelector('.status').textContent = value

26 A button is created dynamically after the page loads. Which approach reliably handles its click event?

Event Handling Medium
A. Use event delegation on an existing ancestor element
B. Attach the listener only to the browser's address bar
C. Assign a listener to the button before the button is created
D. Call preventDefault() on the document during page loading

27 Which method is generally safest when adding user-provided text to a newly created paragraph element?

Dynamic Content Generation Medium
A. Set paragraph.textContent to the user-provided text
B. Set paragraph.innerHTML to the user-provided text
C. Build a script element containing the user-provided text
D. Insert the text using document.write() after page load

28 Which practice best improves keyboard accessibility for a custom clickable control?

JavaScript Accessibility Practices Medium
A. Remove the visible focus indicator to reduce visual distraction
B. Use a semantic <button> element whenever the control performs an action
C. Hide the control from assistive technologies with aria-hidden="true"
D. Use a div and rely only on a mouse click listener

29 Why should client-side form validation be combined with server-side validation?

Form Validation Medium
A. Client-side validation can only validate numeric fields
B. Server-side validation is needed because client-side code can be bypassed
C. Client-side validation prevents all automated requests
D. Server-side validation makes browser validation messages unnecessary

30 What does the regular expression /^[A-Z][a-z]+$/ match?

Regular Expressions Medium
A. A string containing only uppercase letters and spaces
B. A string with at least one lowercase letter anywhere
C. A string beginning with any character and ending with a digit
D. A string containing one uppercase letter followed by lowercase letters

31 Which statement correctly creates a Date object representing the current date and time?

Date and Time Handling Medium
A. const now = Date.current();
B. const now = Date.createNow();
C. const now = new Date();
D. const now = new Date.current;

32 Which event is most appropriate for updating a progress indicator as a video plays?

Audio and Video Events Medium
A. play, because it fires continuously during playback
B. loadeddata, because it fires for every elapsed second
C. timeupdate, because it fires when the playback position changes
D. ended, because it fires whenever the current time changes

33 Which statement correctly describes the difference between localStorage and sessionStorage?

Browser Storage using Web Storage API (Local Storage and Session Storage) Medium
A. localStorage stores objects directly, while sessionStorage stores only arrays
B. localStorage is available only to server-side code, while sessionStorage is client-side
C. localStorage is deleted on refresh, while sessionStorage remains permanently
D. localStorage lasts across browser sessions, while sessionStorage is tied to a page session

34 How should an array named tasks be stored in localStorage?

Browser Storage using Web Storage API (Local Storage and Session Storage) Medium
A. localStorage.setItem('tasks', tasks)
B. localStorage.setObject('tasks', tasks)
C. localStorage.setItem('tasks', JSON.stringify(tasks))
D. localStorage.store('tasks', JSON.parse(tasks))

35 Which code correctly processes a successful JSON response from fetch('/api/users')?

Fetch API and JSON Processing Medium
A. fetch('/api/users').then(response => response.json()).then(users => console.log(users))
B. fetch('/api/users').then(users => users.parseJSON(response)).then(console.log)
C. fetch('/api/users').json().then(response => console.log(response))
D. fetch('/api/users').then(response => response.text.json()).then(users => console.log(users))

36 Why should code check response.ok after calling fetch?

Fetch API and JSON Processing Medium
A. Because checking it prevents the browser from sending the request
B. Because fetch rejects automatically for every HTTP error status
C. Because response.ok converts the response body into JSON
D. Because response.ok indicates whether the HTTP status represents success

37 Which code requests the user's current location and handles the returned coordinates?

Geolocation API Medium
A. navigator.geolocation.getCurrentPosition((position) => console.log(position.coords))
B. navigator.getPosition((position) => console.log(position.location))
C. window.geolocation.current((position) => console.log(position.coords))
D. navigator.location.get((position) => console.log(position.coords))

38 Why is event.preventDefault() commonly called in a dragover handler?

Drag and Drop API Medium
A. To allow the element to become a valid drop target
B. To automatically move the dragged element into the target
C. To trigger the dragend event immediately
D. To permanently store the dragged data in browser storage

39 What is the key difference between querySelector and querySelectorAll?

DOM Selection and Manipulation Medium
A. querySelector changes elements, while querySelectorAll only reads attributes
B. querySelector selects only IDs, while querySelectorAll selects only classes
C. querySelector returns the first match, while querySelectorAll returns a collection of matches
D. querySelector returns HTML strings, while querySelectorAll returns CSS rules

40 What does calling event.preventDefault() in a form's submit event handler do?

Event Handling Medium
A. It removes all event listeners from the form
B. It prevents JavaScript from reading the form fields
C. It stops the browser's default form submission behavior
D. It permanently disables the submit button

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));

Loops and Iterative Programming Hard
A. 3 followed by 3
B. 0 followed by 3
C. 0 followed by 0
D. 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);

Higher Order Functions Hard
A. 0 0 1 2 4
B. 0 0 1 1 3
C. 0 1 1 1 3
D. 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(); }));

Callback Functions Hard
A. sync followed by async
B. async followed by sync
C. async followed by async
D. 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);

DOM Fundamentals Hard
A. 2 2 "BD"
B. 4 2 "BD"
C. 4 0 ""
D. 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?

DOM Selection and Manipulation Hard
A. Descendants and IDs are copied, but registered listeners are not copied
B. All descendants, IDs, and registered listeners are copied
C. Only the root node and its registered listeners are copied
D. Descendants and listeners are copied, but ID attributes are removed

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"));

Event Handling Hard
A. O then D
B. D then O then B
C. D then O
D. 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?

Dynamic Content Generation Hard
A. Create the span and assign the name to its textContent
B. Parse the name with DOMParser and append its body
C. Escape only <script> tags and use insertAdjacentHTML
D. Create the span and assign the name to its 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?

JavaScript Accessibility Practices Hard
A. Use role="link", tabindex="0", click handling, and arrow-key handling
B. Use role="button", tabindex="0", click handling, and Enter/Space key handling
C. Use aria-label, tabindex="-1", click handling, and Escape key handling
D. Use 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?

Form Validation Hard
A. Remove the input's required attribute before calling checkValidity()
B. Call input.setCustomValidity(null) after the value becomes valid
C. Call input.setCustomValidity("") after the value becomes valid
D. Call 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?

Regular Expressions Hard
A. /^(?=[A-Za-z0-9_]{3,16}$)(?=.*[A-Za-z])[0-9][A-Za-z0-9_]*$/
B. /^(?=[A-Za-z0-9_]{3,16})(?=.*[0-9])[A-Za-z_][A-Za-z0-9_]*$/
C. /^(?=[A-Za-z0-9_]{3,16}$)(?!.*[0-9])[A-Za-z][A-Za-z0-9_]*$/
D. /^(?=[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?

Date and Time Handling Hard
A. 24 hours
B. 22 hours
C. 25 hours
D. 23 hours

52 Which approach correctly handles starting media playback when browser autoplay policy may block it?

Audio and Video Events Hard
A. Handle rejection from media.play() and use playing to detect actual playback
B. Call media.play() and use loadedmetadata to detect actual playback
C. Set media.autoplay = true and use durationchange as proof of playback
D. Catch errors from 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?

Browser Storage using Web Storage API (Local Storage and Session Storage) Hard
A. Neither tab receives an event because storage changes are synchronous
B. Tab A receives a storage event, while Tab B does not receive it
C. Tab B receives a storage event, while Tab A does not receive it
D. Both tabs receive identical 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?

Browser Storage using Web Storage API (Local Storage and Session Storage) Hard
A. The final value is 0 because concurrent writes cancel one another
B. The operation throws because simultaneous storage access is prohibited
C. The final value is 1 because both tabs can overwrite based on the same read
D. The final value is always 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?

Fetch API and JSON Processing Hard
A. The fetch promise fulfills only if response.json() is called immediately
B. The fetch promise rejects automatically because the status is outside 200-299
C. The fetch promise fulfills, and code must inspect response.ok or status
D. The fetch promise rejects automatically with the parsed JSON error body

56 A successful DELETE request returns HTTP 204 No Content. What is the likely result of unconditionally executing await response.json()?

Fetch API and JSON Processing Hard
A. It rejects because the empty body cannot be parsed as JSON
B. It resolves to null because the response has no body
C. It rejects because fetch() treats 204 as an error status
D. It resolves to {} because 204 implies an empty object

57 Which statement about using navigator.geolocation in a deployed web application is correct?

Geolocation API Hard
A. It is available to every iframe unless the iframe explicitly disables location access
B. It generally requires a secure context and may still be blocked by permission policy or the user
C. It works in insecure contexts when enableHighAccuracy is set to true
D. It requires only same-origin scripts and bypasses user permission after the first request

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?

Drag and Drop API Hard
A. Call event.preventDefault() from the source's dragend handler
B. Call event.dataTransfer.clearData() from the target's dragover handler
C. Call event.preventDefault() from the target's dragover handler
D. Call 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);

Higher Order Functions Hard
A. 3
B. 9
C. 5
D. 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?

Event Handling Hard
A. const item = e.target.closest("li"); if (!item || !list.contains(item)) return;
B. const item = e.target.closest("li"); if (!item || item.parentElement !== list) return;
C. const item = e.currentTarget.closest("li"); if (!item || item !== list) return;
D. const item = e.target.querySelector("li"); if (!item || item.parentElement === list) return;