Notice: Due to an ongoing migration of our storage and publishing system, material requested since last month will not be uploaded for the time being, and new requests are paused. All existing notes remain available.
Question 1 of 60 · Document Object Model (DOM) structure · Easy
What does "DOM" stand for?
Not quite. Try another option.
Answer: Document Object Model
DOM stands for Document Object Model. It is a programming interface for web documents that represents the page so that programs can change the document structure, style, and content.
Question 2 of 60 · Document Object Model (DOM) structure · Easy
How does the DOM represent an HTML document?
Not quite. Try another option.
Answer: As a tree-like structure of nodes
The DOM represents an HTML document as a logical tree. Each branch of the tree ends in a node, and each node contains an object. For example, the <html> element is the root node, and it has children like <head> and <body>.
Question 3 of 60 · Document Object Model (DOM) structure · Easy
In the DOM tree, what is the topmost node that serves as the entry point to the page's content?
Not quite. Try another option.
Answer: The document object
The document object is the root of the DOM tree and represents the entire webpage. All operations on the DOM, like selecting elements, start from this object.
Question 4 of 60 · DOM traversal and manipulation · Easy
Which JavaScript method is specifically designed to select a single HTML element by its unique id?
Not quite. Try another option.
Answer: document.getElementById()
getElementById() is a direct and highly efficient method for selecting an element when you know its unique id attribute. It returns a single element object.
Question 5 of 60 · DOM traversal and manipulation · Easy
Which method should you use to select the first element that matches a specific CSS selector, like div.my-class?
Not quite. Try another option.
Answer: querySelector()
The querySelector() method returns the very first element within the document that matches the specified CSS selector. In contrast, querySelectorAll() returns a list of all matching elements.
Question 6 of 60 · DOM traversal and manipulation · Easy
To change the text inside a <p> tag while ensuring no HTML is rendered, which property is the safest to use?
Not quite. Try another option.
Answer: textContent
textContent gets the content of all elements as plain text. It's safer than innerHTML because it doesn't parse HTML, preventing potential security risks like Cross-Site Scripting (XSS).
Question 7 of 60 · Dynamic styling and content updates · Easy
How can you change the CSS color property of an element to red using JavaScript?
Not quite. Try another option.
Answer: element.style.color = 'red';
The style property of a DOM element allows you to directly access and modify its inline CSS properties. CSS properties with hyphens (e.g., font-size) are written in camelCase (e.g., fontSize).
Question 8 of 60 · Dynamic styling and content updates · Easy
What does the element.classList.add('new-class') method do?
Not quite. Try another option.
Answer: It adds the CSS class new-class to the element.
The classList property provides a simple way to manipulate an element's classes. The add() method adds one or more classes to the element without affecting existing ones.
Question 9 of 60 · Event propagation and delegation · Easy
What is an "event" in the context of the DOM?
Not quite. Try another option.
Answer: A signal from the browser that something has happened, like a mouse click or key press.
Events are actions or occurrences that happen in the system you are programming, which the system tells you about so your code can react to them. Examples include user interactions (click, mouseover) and browser actions (load, resize).
Question 10 of 60 · Event propagation and delegation · Easy
What is the default direction of event propagation in modern browsers, where an event travels from the target element up to its ancestors?
Not quite. Try another option.
Answer: Bubbling
Event bubbling is the default behavior where an event triggered on an element first runs the handlers on it, then on its parent, then all the way up on other ancestors to the document object.
Question 11 of 60 · Event propagation and delegation · Easy
Which modern JavaScript method is used to attach an event handler (like a function) to an element?
Not quite. Try another option.
Answer: addEventListener()
element.addEventListener('event_name', function) is the standard and most flexible way to register an event handler. It allows adding multiple handlers for a single event.
Question 12 of 60 · Debugging using browser developer tools · Easy
Which browser developer tool panel is primarily used for logging messages and errors from your JavaScript code?
Not quite. Try another option.
Answer: Console
The Console panel is the main tool for viewing log messages from console.log(), inspecting variables, and seeing error messages generated by your scripts.
Question 13 of 60 · Debugging using browser developer tools · Easy
In the developer tools, which panel allows you to inspect and edit the live HTML and CSS of a webpage?
Not quite. Try another option.
Answer: Elements
The Elements panel displays the webpage's HTML as a live DOM tree. You can select any element to inspect and modify its attributes and the CSS rules applied to it.
Question 14 of 60 · Debugging using browser developer tools · Easy
What is the primary purpose of the console.log() function?
Not quite. Try another option.
Answer: To output information to the web console for debugging purposes.
console.log() is a fundamental debugging tool for developers. It allows them to print the value of variables or custom messages to the browser's console to track the state of their application.
Question 15 of 60 · Module bundling concepts using modern build tools · Easy
What is the main purpose of a JavaScript module bundler like Webpack or Vite?
Not quite. Try another option.
Answer: To combine multiple JavaScript files into a single, optimized file for the browser.
Module bundlers take your modules with their dependencies and generate one or more optimized bundles that can be loaded by a browser. This reduces the number of HTTP requests and can improve loading performance.
Question 16 of 60 · Module bundling concepts using modern build tools · Easy
Which of the following is a popular JavaScript module bundler?
Not quite. Try another option.
Answer: Webpack
Webpack is one of the most widely-used module bundlers in the front-end ecosystem. Vite and Rollup are other popular examples. jQuery is a library, React is a framework, and ESLint is a linter.
Question 17 of 60 · Code linting and formatting practices · Easy
What is the main function of a code linter like ESLint?
Not quite. Try another option.
Answer: To analyze code for potential errors and enforce coding standards.
A linter is a static analysis tool used to find programming errors, bugs, stylistic errors, and suspicious constructs. It helps improve code quality and maintain consistency across a team.
Question 18 of 60 · Code linting and formatting practices · Easy
What is the primary role of a code formatter like Prettier?
Not quite. Try another option.
Answer: To automatically enforce a consistent code style by reformatting code.
A code formatter, like Prettier, is an opinionated tool that parses your code and re-prints it according to its own set of rules. This ensures a consistent style (e.g., spacing, indentation, line length) across the entire codebase, saving developers time and preventing style debates.
Question 19 of 60 · DOM traversal and manipulation · Easy
Which JavaScript method is used to create a new HTML element from scratch?
Not quite. Try another option.
Answer: document.createElement()
The document.createElement('tagName') method creates the HTML element specified by tagName (e.g., 'p', 'div'). The newly created element can then be added to the DOM using methods like appendChild().
Question 20 of 60 · Dynamic styling and content updates · Easy
To completely replace an element's content with new HTML content, which property is most suitable?
Not quite. Try another option.
Answer: innerHTML
The innerHTML property sets or gets the HTML syntax describing the element's descendants. Assigning a string of HTML to it will parse the string and replace the element's existing content with the new nodes.
Question 21 of 60 · DOM traversal and manipulation · Medium
What is the difference in output between document.getElementById('parent').childNodes.length and document.getElementById('parent').children.length?
Not quite. Try another option.
Answer: childNodes returns 5, while children returns 2.
children returns a collection of only the element nodes (e.g., <p>, <span>). childNodes returns a collection of all nodes, including element nodes, text nodes (like whitespace and newlines between elements), and comment nodes. In this case, children finds the <p> and <span> (2 elements). childNodes finds the comment, the <p>, the <span>, and the text nodes containing whitespace between them (5 nodes total).
Question 22 of 60 · Event propagation and delegation · Medium
Given the HTML below, if a user clicks on the <p> element, in what order will the alerts fire during the bubbling phase?
Event bubbling is the default behavior in modern browsers. The event starts at the most specific target (#child), and then 'bubbles up' through its ancestors in the DOM tree. Therefore, the order of execution will be child, then parent, then grandparent.
Question 23 of 60 · Module bundling concepts using modern build tools · Medium
In the context of a module bundler like Webpack or Vite, what is the primary purpose of 'tree shaking'?
Not quite. Try another option.
Answer: To remove unused code (dead-code elimination) from the final bundle.
Tree shaking is a process used by modern module bundlers to eliminate unused code. It analyzes import and export statements to detect which modules are not being used in a project and excludes them from the final production bundle, resulting in a smaller file size.
Question 24 of 60 · Code linting and formatting practices · Medium
What is the key difference between a code linter (like ESLint) and a code formatter (like Prettier)?
Not quite. Try another option.
Answer: A linter analyzes code for potential errors and bad practices, while a formatter enforces a consistent code style.
A linter (ESLint) focuses on code quality. It flags programming errors, potential bugs, stylistic issues, and suspicious constructs (e.g., unused variables). A formatter (Prettier) is only concerned with code style—things like indentation, line length, and spacing. Its goal is to make the code look consistent, not to find bugs.
Question 25 of 60 · Dynamic styling and content updates · Medium
You need to apply ten different CSS style changes to a single DOM element in response to a user action. Which of the following approaches is generally most performant?
Not quite. Try another option.
Answer: Defining a CSS class with all ten styles and adding that class to the element, e.g., element.classList.add('active-state');
Applying a single class is more performant than setting multiple inline styles individually. Each direct manipulation of the style property can trigger a browser reflow/repaint. By adding a class, you are making a single change to the DOM, and the browser can then calculate the style changes more efficiently in one go. It also separates concerns (styling in CSS, logic in JS), which is a best practice.
Question 26 of 60 · Debugging using browser developer tools · Medium
You notice a JavaScript function is being called with an incorrect value, but only after it has been executed hundreds of times in a loop. Which debugging feature would be most efficient for pausing execution only when the problematic value appears?
Not quite. Try another option.
Answer: A conditional breakpoint with an expression that checks for the incorrect value.
A conditional breakpoint allows you to specify a JavaScript expression. The debugger will only pause execution on that line if the expression evaluates to true. This is ideal for situations within loops or frequent function calls where you only want to stop when a specific condition is met, avoiding the need to manually step through hundreds of correct iterations.
Question 27 of 60 · Event propagation and delegation · Medium
Why is event delegation a recommended pattern for handling events on a large list of items, especially if items are added or removed dynamically?
Not quite. Try another option.
Answer: It attaches a single event listener to a parent element, which improves performance and automatically handles events for new child elements.
Event delegation involves attaching one event listener to a common ancestor (e.g., the <ul>) instead of one listener for every list item (<li>). This reduces memory usage. Because the listener is on the parent, it uses event bubbling to catch events from any child. This means it works for existing children and any new children added later, without needing to attach new listeners to them.
Question 28 of 60 · DOM traversal and manipulation · Medium
What is the primary advantage of using document.createDocumentFragment() when appending multiple elements to the DOM?
Not quite. Try another option.
Answer: It creates a virtual, off-screen DOM tree, allowing you to append multiple elements with a single reflow/repaint, improving performance.
A DocumentFragment is a lightweight, minimal DOM object with no parent. You can append new elements to it in memory, and then append the entire fragment to the main DOM. This is much more performant than appending each element one-by-one, as each individual append can trigger a costly browser reflow/repaint. With a fragment, all elements are added in a single operation, causing only one reflow.
Question 29 of 60 · Document Object Model (DOM) structure · Medium
Which of the following statements accurately describes the relationship between the DOM and an HTML document?
Not quite. Try another option.
Answer: The DOM is a programming interface (API) that represents the HTML document as a tree-like structure of objects, allowing it to be manipulated by scripts.
The browser parses the HTML source code and creates a Document Object Model (DOM) from it. This model is a live, in-memory representation of the document as a tree of nodes (objects). JavaScript can then interact with this API to read or modify the document's structure, content, and style.
Question 30 of 60 · Dynamic styling and content updates · Medium
What is the key difference between setting an element's textContent versus its innerHTML?
Not quite. Try another option.
Answer: textContent automatically escapes HTML tags, treating them as plain text, while innerHTML parses and renders them as DOM elements.
textContent gets or sets the text content of a node and its descendants. It ignores HTML and returns only the text. Setting it is a safe way to insert text without risking a Cross-Site Scripting (XSS) attack. innerHTML gets or sets the HTML markup contained within an element. If you set it with a string containing HTML tags, the browser will parse that string and create corresponding DOM nodes.
Question 31 of 60 · Module bundling concepts using modern build tools · Medium
In a modern front-end build process, what is the typical role of a tool like Babel?
Not quite. Try another option.
Answer: To transpile modern JavaScript (ES6+) code into a backwards-compatible version (like ES5) that older browsers can understand.
Babel is a JavaScript transpiler. Its main purpose is to convert code written in the latest versions of JavaScript (which may not be supported by all browsers) into an older, more widely-supported version, such as ES5. This allows developers to use modern language features without sacrificing browser compatibility. Bundlers like Webpack often use Babel as part of their build pipeline.
Question 32 of 60 · Debugging using browser developer tools · Medium
You have a CSS rule !important that is still being overridden by another style. Where in the Chrome Developer Tools would be the best place to investigate which style is taking precedence and why?
Not quite. Try another option.
Answer: The Elements tab, by selecting the element and viewing the 'Computed' and 'Styles' panes.
The 'Elements' tab is designed for this purpose. After selecting the element, the 'Styles' pane shows all the CSS rules applied to it, including those that have been overridden (which are shown with a strikethrough). The 'Computed' pane shows the final, calculated style that is actually being rendered, and you can trace back which rule it came from. This is the most direct way to debug CSS specificity and precedence issues.
Question 33 of 60 · Event propagation and delegation · Medium
What is the effect of calling event.stopPropagation() inside an event listener?
Not quite. Try another option.
Answer: It stops the event from continuing its propagation journey through the DOM (i.e., it stops bubbling up or capturing down).
event.stopPropagation() is a method on the event object that, when called, prevents the event from traveling further up (or down) the DOM tree. For example, in the bubbling phase, if a click event listener on a child element calls stopPropagation(), the event will not bubble up to its parent elements, and their click listeners will not be triggered.
Question 34 of 60 · DOM traversal and manipulation · Medium
Given the following JavaScript code, what will the final structure of the <ul> element look like?
The parentNode.insertBefore(newNode, referenceNode) method inserts newNode into the parentNode's list of children, just before the referenceNode. In this code, new_item ('Cherry') is inserted into the list before the item1 ('Apple') element. Therefore, 'Cherry' becomes the first item in the list.
Question 35 of 60 · Code linting and formatting practices · Medium
A development team wants to ensure that every time a developer commits code, it is automatically checked for both stylistic consistency and potential logical errors (like using a variable before it's defined). Which combination of tools is best suited for this automated workflow?
Not quite. Try another option.
Answer: A code formatter (Prettier) and a code linter (ESLint), likely integrated with a pre-commit hook.
This task requires two distinct functions: enforcing style (the job of a formatter like Prettier) and finding potential bugs/errors (the job of a linter like ESLint). To automate this process upon committing, these tools are typically run via a pre-commit hook (using a tool like Husky), which ensures the checks pass before the code is added to the repository.
Question 36 of 60 · Document Object Model (DOM) structure · Medium
In the DOM tree, what type of node represents the actual text inside an element like <p>Hello World</p>?
Not quite. Try another option.
Answer: A TEXT_NODE
The DOM represents an HTML document as a tree of nodes. The <p> tag itself is an ELEMENT_NODE. The text 'Hello World' contained within it is a separate child node of type TEXT_NODE. This distinction is important for understanding methods like childNodes, which includes text nodes, versus children, which does not.
Question 37 of 60 · Dynamic styling and content updates · Medium
What is the purpose of the dataset property on an HTML element in JavaScript?
Not quite. Try another option.
Answer: To get and set custom data attributes (data-*) on an element in a structured way.
The dataset property provides a simple, readable way to access all custom data-* attributes on an element. An attribute like data-user-id="123" on an element el can be accessed in JavaScript as el.dataset.userId. It's a convenient mechanism for storing extra information on an element without resorting to non-standard attributes or extra properties.
Question 38 of 60 · Debugging using browser developer tools · Medium
You are trying to debug a complex layout issue where an element is not sized or positioned as expected. Which feature in browser developer tools would be most helpful for visualizing the element's box model (margin, border, padding, and content)?
Not quite. Try another option.
Answer: The box model visualizer, typically found in the Elements tab under the 'Computed' pane.
Modern browser developer tools include an interactive box model diagram in the Elements tab (usually under the 'Computed' or a 'Layout' sub-tab). This visualizer shows the exact pixel values for the selected element's margin, border, padding, and content dimensions. You can even edit these values directly in the diagram to see how they affect the layout, making it an essential tool for debugging CSS layout problems.
Question 39 of 60 · Module bundling concepts using modern build tools · Medium
What problem do module bundlers primarily solve in the context of front-end development?
Not quite. Try another option.
Answer: They process and combine many separate JavaScript modules into fewer files (often just one) to optimize for browser loading.
Modern JavaScript development encourages breaking code into small, reusable modules. However, making a separate HTTP request for each module is highly inefficient for a browser. A module bundler like Webpack, Vite, or Parcel traverses the dependency graph of these modules and bundles them into a single (or a few) optimized files that the browser can download much more efficiently, improving application load times.
Question 40 of 60 · DOM traversal and manipulation · Medium
Consider an element <button id="myBtn">Click</button>. Which JavaScript selector would find the closest ancestor element that has the class container?
The element.closest(selector) method traverses up the DOM tree from the current element (inclusive) and returns the first ancestor that matches the provided CSS selector. querySelector searches down the tree for descendants. parentNode returns only the immediate parent and cannot take a selector. findAncestor is not a standard DOM API method.
Question 41 of 60 · Event propagation and delegation · Hard
Consider the following HTML structure and JavaScript code. What is the final output logged to the console when the child div is clicked?
The event propagation follows three phases: Capture, Target, and Bubble.
Capture Phase: The event travels from the root down to the target. The 'Parent Capture' listener fires first. Then, the 'Child Capture' listener fires.
Target Phase: The event has reached the target (child). Listeners on the target are executed. The useCapture flag is ignored here; they fire in the order they were registered. The first listener for child is the 'Child Bubble' listener (even though it's registered for the bubbling phase, it fires at the target). It logs 'Child Bubble' and then calls e.stopImmediatePropagation().
stopImmediatePropagation() Effect: This method prevents any other listeners on the same element from being executed for the same event. Therefore, the 'Child Bubble 2' listener is never called.
stopPropagation() vs stopImmediatePropagation(): Because stopImmediatePropagation() also includes the functionality of stopPropagation(), it prevents the event from moving to the next phase (Bubbling). Therefore, the 'Parent Bubble' listener is also never called. The final output is 'Parent Capture', 'Child Capture', 'Child Bubble'.
Question 42 of 60 · Module bundling concepts using modern build tools · Hard
In a Webpack configuration, you are trying to implement long-term caching using [contenthash]. You notice that changing a CSS file also changes the content hash of your main JavaScript entry bundle, even though the JS code itself hasn't changed. What is the most likely cause and solution for this behavior?
Not quite. Try another option.
Answer: This is caused by the Webpack runtime and manifest being embedded in the main JS bundle. The solution is to use optimization.runtimeChunk: 'single' to extract the runtime into a separate chunk.
Webpack maintains a 'manifest' which includes a map of all module IDs to the output bundle files. When you change any file (JS or CSS), the ID or chunk hash of that module changes. If the runtime and manifest logic are part of your main JS bundle (main.js), then main.js must be updated to reflect the change in the CSS file's hash. This causes the content hash of main.js to change as well. By extracting the runtime into its own chunk using optimization.runtimeChunk: 'single', the manifest is isolated. Now, when the CSS changes, only the CSS bundle and the small runtime chunk will have their hashes updated, leaving the main JS bundle's hash unchanged, which is ideal for long-term caching.
Question 43 of 60 · DOM traversal and manipulation · Hard
You are tasked with improving the performance of a script that adds 1000 <li> elements to a <ul> in the DOM. Which of the following methods is generally the most performant and why?
Method A: Loop 1000 times, creating an <li> and calling ul.appendChild() in each iteration. Method B: Loop 1000 times, creating an <li> and appending it to a DocumentFragment, then appending the fragment to the ul once.
* Method C: Build a single string of 1000 <li> elements and set ul.innerHTML with this string.
Not quite. Try another option.
Answer: Method B is most performant because it minimizes reflows/repaints by manipulating a detached DOM tree and attaching it only once.
While Method C (innerHTML) is fast because it's a single operation, it can be slower than the DocumentFragment method for large numbers of complex elements because the browser has to parse the entire HTML string, destroy existing children of ul, and then create and append the new DOM nodes. Method A is the slowest because each appendChild to a live DOM element can potentially trigger a reflow and repaint, leading to n reflows for n elements in the worst case. Method B (DocumentFragment) is typically the winner. It creates a lightweight, in-memory DOM structure. All appends happen off-screen, triggering no reflows. The final appendChild of the fragment to the live DOM is a single, highly optimized operation that moves all the fragment's children at once, causing only one reflow. It also preserves existing event listeners on the ul element, unlike innerHTML which destroys them.
Question 44 of 60 · Dynamic styling and content updates · Hard
A script needs to apply several style changes to an element and then read its final dimensions. The code is structured as follows:
Which statement best describes the performance implications of this code?
Not quite. Try another option.
Answer: The call to element.getBoundingClientRect() forces a synchronous reflow (layout) to calculate the correct dimensions, negating the browser's ability to batch the preceding style changes.
Modern browsers are very efficient and try to batch style and layout changes, applying them in a single pass just before the next repaint. However, certain properties and methods (like getBoundingClientRect(), offsetTop, clientWidth, etc.) require the browser to provide an up-to-the-minute value. To do this, the browser must immediately apply all queued style changes, calculate the layout (reflow), and then return the value. This is called a 'forced synchronous layout' or 'layout thrashing'. In this code, the read (getBoundingClientRect) right after the writes (.style...) forces the browser to perform the layout calculation synchronously, which can be a significant performance bottleneck, especially if done inside a loop.
Question 45 of 60 · Debugging using browser developer tools · Hard
While using the Chrome DevTools Performance profiler, you observe a large, solid purple block labeled 'Layout' in the flame chart, which is causing significant UI jank. What is the most effective initial step to diagnose the root cause of this 'forced synchronous layout'?
Not quite. Try another option.
Answer: In the 'Performance' tab, find the 'Layout' event, click on it, and inspect the 'Summary' and 'Call Stack' in the details pane to identify the specific JavaScript code that triggered the layout calculation.
While other options can be useful for debugging, the most direct and effective initial step for a 'Layout' bottleneck is to use the information already provided by the Performance profiler. When you select the purple 'Layout' block, the bottom 'Details' pane provides a wealth of information. The 'Summary' tab shows how many nodes were affected and the duration. Most importantly, the 'Call Stack' (or 'Initiator' in some views) will show the exact sequence of JavaScript function calls that led to the forced layout. This allows you to pinpoint the exact line of code (e.g., a getBoundingClientRect() call immediately after a style write) that is causing the performance issue.
Question 46 of 60 · Code linting and formatting practices · Hard
Your team uses ESLint and Prettier, but you encounter a conflict: Prettier formats code in a way that violates an ESLint rule (e.g., max-len). What is the standard, recommended practice for resolving such conflicts and ensuring a smooth developer experience?
Not quite. Try another option.
Answer: Use the eslint-plugin-prettier and eslint-config-prettier packages. eslint-config-prettier disables conflicting ESLint rules, and eslint-plugin-prettier runs Prettier as an ESLint rule.
This is the canonical solution. The problem has two parts: reporting and fixing. eslint-config-prettier is a configuration that turns off all ESLint's stylistic rules that are unnecessary or might conflict with Prettier. This prevents ESLint from flagging code that Prettier has formatted. eslint-plugin-prettier integrates Prettier directly into ESLint's rule system. It reports differences between your code and Prettier's expected output as individual ESLint issues. This means you get all your feedback in one place (your linter), and commands like eslint --fix can be used to fix both linting and formatting issues in one pass. This creates a single, authoritative source for code quality and style.
Question 47 of 60 · Document Object Model (DOM) structure · Hard
When an event originating from within a Shadow DOM is dispatched, and it crosses the shadow boundary into the light DOM, what happens to the event.target property as observed by listeners in the light DOM?
Not quite. Try another option.
Answer: event.target is retargeted to be the host element of the Shadow DOM to preserve its encapsulation.
A key feature of Shadow DOM is encapsulation. To prevent the internal structure of a web component from leaking out, events that bubble or are composed across the shadow boundary are retargeted. For any listener outside the Shadow DOM, the event.target will appear to be the component's host element (the element the shadow root is attached to), not the actual internal element that was the original target. This preserves the 'black box' nature of the component. Inside the Shadow DOM, listeners will still see the correct, original event.target. The original path of the event can still be inspected using event.composedPath().
Question 48 of 60 · Module bundling concepts using modern build tools · Hard
You're using an ES module-based library and have configured Webpack for tree-shaking. However, you notice that a large, unused portion of the library is still included in your final bundle. The library's package.json does NOT have a "sideEffects" field. Which of the following is the most probable cause for the tree-shaking failure?
Not quite. Try another option.
Answer: The library's code contains a top-level function call or modifies a global object (e.g., window.myLib = {}), which is considered a side effect that Webpack cannot safely remove.
Tree-shaking relies on static analysis of ES module import and export statements to determine which code is unused. A 'side effect' is code that does something other than just exporting values, such as modifying global objects, logging to the console, or applying a stylesheet at the module's top level. If a bundler cannot prove that a module has no side effects, it must include the entire module to ensure the side effect is executed, even if none of its exports are used. If a library author knows their code is free of side effects, they can add "sideEffects": false to their package.json to help the bundler. In the absence of this flag, the bundler must be conservative and assume side effects might exist. A top-level function call is a very common source of such a side effect.
Question 49 of 60 · DOM traversal and manipulation · Hard
What is a key difference between a NodeList returned by document.querySelectorAll() and an HTMLCollection returned by document.getElementsByTagName() in modern browsers?
Not quite. Try another option.
Answer: HTMLCollection is live, meaning it automatically updates if the DOM changes. NodeList from querySelectorAll is static.
This is a crucial and often misunderstood distinction. An HTMLCollection (from methods like getElementsByTagName or element.children) is a live collection. If you add or remove elements from the DOM that match the selector, the collection instance will automatically reflect these changes. In contrast, the NodeList returned by querySelectorAll is static. It is a snapshot of the DOM at the moment the query was run. Any subsequent changes to the DOM will not be reflected in that specific NodeList instance. This difference has significant performance implications; iterating over a live collection while modifying it can lead to infinite loops or unexpected behavior, whereas a static list is safe to iterate over while changing the DOM.
Question 50 of 60 · Event propagation and delegation · Hard
You are implementing event delegation on a complex list where each <li> contains multiple nested elements. You want to trigger a function only when a click originates specifically on a <span> with the class .icon inside any <li>. Which event handler implementation is the most robust and efficient?
The correct option is the most robust. Let's analyze why others are flawed:
The first option (e.target.className === 'icon') is brittle; it fails if the span has other classes.
The third option (e.target.tagName === 'SPAN' && ...) is better but still fails if the click target is a child of the span (e.g., an icon font using an <i> tag inside the <span>).
The last option is not event delegation at all. It attaches a listener to every single icon, which is inefficient for large lists and doesn't work for dynamically added items.
The correct answer using e.target.closest('.icon') is the most robust delegation pattern. It starts from the actual click target (e.target) and traverses up the DOM tree to find the nearest ancestor that matches the selector .icon. This correctly handles clicks on the icon <span> itself or any of its descendants. The additional list.contains(icon) check is a safeguard to ensure the found icon is indeed a descendant of the element we attached the listener to, preventing issues in deeply nested or complex scenarios.
Question 51 of 60 · Dynamic styling and content updates · Hard
To achieve a smooth, high-performance animation in JavaScript (e.g., moving an element across the screen), why is using requestAnimationFrame(callback) superior to using setInterval(callback, 16) or a recursive setTimeout(callback, 16)?
Not quite. Try another option.
Answer: The browser can optimize animations scheduled with requestAnimationFrame by grouping them into a single reflow/repaint cycle, and it will pause them in inactive tabs, saving CPU and battery life.
requestAnimationFrame (rAF) is specifically designed for animations. The browser invokes the rAF callback right before it is about to perform the next repaint. This timing is critical. It ensures that all DOM changes for the animation frame are batched together, minimizing layout thrashing and resulting in smoother visuals. In contrast, setInterval/setTimeout are not synchronized with the browser's paint cycle. Their callbacks can fire at inopportune times, such as right after a paint, forcing the browser to perform another layout calculation and potentially missing a frame. Furthermore, a key optimization is that browsers will automatically pause rAF loops when the page or tab is not visible, which is a massive benefit for performance and battery on mobile devices. setInterval will continue to fire relentlessly in the background.
Question 52 of 60 · Debugging using browser developer tools · Hard
You're debugging a complex JavaScript application and suspect a specific function, updateState(), is being called with an invalid argument, but only under very specific, hard-to-reproduce conditions. The function is called thousands of times. What is the most efficient way to pause execution only when updateState(arg) is called where arg.id is null?
Not quite. Try another option.
Answer: Set a conditional breakpoint at the beginning of updateState() with the condition arg.id === null.
A conditional breakpoint is the perfect tool for this scenario. It combines the pausing power of a standard breakpoint with the logic of an if statement. You can set the breakpoint on a line of code, right-click it, and provide a JavaScript expression. The debugger will only pause execution on that line if the expression evaluates to true. This allows you to ignore thousands of valid calls to updateState() and stop precisely at the moment the problematic call occurs. The other methods are far less efficient: manual logging creates noise, a standard breakpoint requires tedious manual stepping, and a logpoint is useful for logging information without pausing but doesn't help you pause and inspect the call stack at the critical moment.
Question 53 of 60 · Code linting and formatting practices · Hard
What is the primary purpose of the overrides key in an ESLint configuration file (.eslintrc.js) and in what scenario is it most critically used?
Not quite. Try another option.
Answer: To apply a different set of rules for a specific list of files or file glob patterns, such as having stricter rules for test files.
The overrides key is a powerful feature in ESLint that allows for configuration targeted at specific subsets of your codebase. It takes an array of objects, where each object specifies a files pattern (e.g., "**/*.test.js" or "src/api/**/*.js") and a corresponding configuration (rules, parserOptions, etc.) to be applied only to those files. This is critically useful in monorepos or projects with mixed code types. A common use case is to apply different rules to test files (e.g., allowing more dependencies in devDependencies, or using a testing-specific plugin like eslint-plugin-jest) than to your main application source code. It allows for a single, manageable ESLint config file instead of multiple disconnected ones.
Question 54 of 60 · Document Object Model (DOM) structure · Hard
Which of these statements accurately describes the relationship between the DOM, CSSOM, and the Render Tree?
Not quite. Try another option.
Answer: The Render Tree is created by combining the DOM and CSSOM; it includes only the nodes that are visually rendered, so elements like <head> or those with display: none; are excluded.
The browser's rendering process involves several steps. First, it parses HTML to create the Document Object Model (DOM). In parallel, it parses CSS to create the CSS Object Model (CSSOM). Crucially, it then combines these two trees to form the Render Tree. The Render Tree is the tree of visual elements to be painted. It is not a 1:1 mapping of the DOM. It omits non-visual nodes (like <script>, <head>, or <meta>) and, importantly, any nodes that are hidden via CSS (e.g., display: none;). However, nodes hidden with visibility: hidden;are included in the Render Tree (as they still occupy space in the layout), they just aren't painted.
Question 55 of 60 · Module bundling concepts using modern build tools · Hard
In the context of Webpack, what is the fundamental difference between a loader and a plugin?
Not quite. Try another option.
Answer: Loaders operate on individual files as they are being added to the dependency graph, while plugins operate on the bundle as a whole at various points in the compilation lifecycle.
This is the core distinction. Loaders work at the individual module/file level. When Webpack encounters an import or require statement, it uses loaders to preprocess the content of that file before it's added to the bundle. For example, babel-loader transforms a single .js file from ES2021 to ES5, and css-loader interprets @import and url() inside a single .css file. Plugins, on the other hand, have a much broader scope. They can tap into Webpack's compilation lifecycle hooks to perform actions on the entire bundle (or 'chunk'). Examples include MiniCssExtractPlugin which takes all the CSS from all modules and extracts it into a single .css file, or HtmlWebpackPlugin which generates an index.html file and injects the final bundle scripts into it. Loaders transform files, plugins manage the bundling process.
Question 56 of 60 · DOM traversal and manipulation · Hard
Given the following HTML snippet, what will el.querySelector(':scope > .c') select, where el is the DOM element with the ID a?
Answer: It will select only the div commented with C1.
The :scope pseudo-class represents the element on which the query selector is being called (el in this case). The > is the direct child combinator. Therefore, the selector ':scope > .c' translates to: "Find elements with the class c that are direct children of the :scope element (which is #a)." Looking at the HTML structure, only the div commented with C1 is a direct child of #a. The divs C2 and C3 are grandchildren or deeper descendants, so they are not matched by the > combinator. This demonstrates a precise way to scope a query to an element's immediate children without needing to know the parent's own ID or class.
Question 57 of 60 · Dynamic styling and content updates · Hard
What is the primary difference between setting an element's opacity to 0 and setting its display to none?
Not quite. Try another option.
Answer: opacity: 0 makes the element invisible but it still occupies its space in the layout and can receive events. display: none removes the element from the layout flow and it cannot receive events.
This is a critical distinction in dynamic styling. display: none completely removes the element from the document's render tree and layout flow. It takes up no space, and its descendants are also not rendered. It's as if the element doesn't exist on the page for rendering or event purposes. In contrast, opacity: 0 is purely a visual property. It makes the element and its children fully transparent, but the element still exists in the layout, occupies its original dimensions, and can still be a target for DOM events like clicks. (Note: some browsers might optimize away event targeting for fully transparent elements, but the spec allows them to be interactive). Additionally, opacity is an animatable property, making it ideal for fade-in/fade-out transitions, while display is not (though you can transition other properties and then set display at the end).
Question 58 of 60 · Event propagation and delegation · Hard
Under what specific circumstance would you need to use pointer-events: none; in CSS as part of a complex event delegation strategy?
Not quite. Try another option.
Answer: When an element (e.g., a decorative overlay <div>) is positioned on top of another element that needs to be clickable, allowing clicks to 'pass through' the overlay to the element below.
pointer-events: none; is a CSS property that instructs an element to ignore pointer events (like clicks, hover, etc.). The browser will treat the element as if it is not there for the purpose of event targeting. This is extremely useful in UI design where you might have a non-interactive element (like a decorative gradient overlay, a custom-styled checkbox's ::before pseudo-element, or a tooltip arrow) that visually sits on top of an element that should be interactive. Without pointer-events: none; on the overlay, it would 'capture' the click, and the element underneath would never receive it. By applying this style to the overlay, events will pass right through it to whatever is visually layered behind it, simplifying the event handling logic significantly.
Question 59 of 60 · Module bundling concepts using modern build tools · Hard
What is the primary purpose of a 'source map' (.js.map file) generated by a build tool like Webpack, and how does it relate to debugging?
Not quite. Try another option.
Answer: It is a JSON file that maps the code within a bundled/minified/transpiled file back to its original position in the source files, allowing developers to debug their original code in the browser.
Modern web development involves many transformations: TypeScript/Babel transpiles code, Webpack bundles multiple files into one, and tools like Terser minify it for production. The code that the browser actually executes can look vastly different from the code the developer wrote. This makes debugging nearly impossible. A source map is the solution. It's a file that creates a two-way mapping between the generated code and the original source code. When you open your browser's developer tools and a source map is present, the browser uses it to show you your original, readable source files. You can set breakpoints, view variables, and see stack traces all in the context of your original code, even though the browser is running the transformed version.
Question 60 of 60 · DOM traversal and manipulation · Hard
Consider the following code intended to remove all child nodes from a div with the id container. Why is the first approach problematic, while the second one works correctly?
JavaScript
// Approach 1 (Problematic)
const container1 = document.getElementById('container');
const children1 = container1.children;
for (let i = 0; i < children1.length; i++) {
container1.removeChild(children1[i]);
}
// Approach 2 (Correct)
const container2 = document.getElementById('container');
while (container2.firstChild) {
container2.removeChild(container2.firstChild);
}
Not quite. Try another option.
Answer: Approach 1 fails because container.children returns a live HTMLCollection. As children are removed, the collection shrinks and children.length changes, causing the loop to terminate prematurely and skip elements.
The core of the problem lies in the 'live' nature of the HTMLCollection returned by element.children. When i is 0, the first child (children1[0]) is removed. The collection instantly updates: what was children1[1] now becomes children1[0], and the collection's length decreases by one. In the next loop iteration, i increments to 1. The loop now tries to remove children1[1], but it's actually removing the third original child, having skipped the second one entirely. This continues, resulting in only about half the children being removed. Approach 2 works because it's simple and not dependent on a shifting index. It repeatedly removes the current first child until no first child is left. This is a classic 'gotcha' when dealing with live DOM collections.
That's unit 4
Answer a few questions and your score shows up here.
Nearly through. Did unit 4 of INT219 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did unit 4 of INT219 save you a night before the exam?
Then you can help keep it free for the next batch. 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.