Chapter 16 Quiz: Web Frontend Development with AI
Test your understanding of frontend development concepts and AI-assisted web development. Each question has one best answer unless otherwise noted.
Question 1
What are the three core technologies of the web frontend?
- A) Python, Django, PostgreSQL
- B) HTML, CSS, JavaScript
- C) React, Node.js, MongoDB
- D) HTTP, TCP, DNS
Show Answer
**B) HTML, CSS, JavaScript** HTML provides structure, CSS provides visual presentation, and JavaScript provides interactivity and behavior. These three technologies form the foundation of every web page, regardless of which frameworks or libraries are built on top of them.Question 2
Which HTML element is the most semantically appropriate for a blog post that could stand alone as an independent piece of content?
- A)
<div> - B)
<section> - C)
<article> - D)
<main>
Show Answer
**C) `Question 3
In JavaScript, what is the difference between let and const?
- A)
letis for numbers,constis for strings - B)
letallows reassignment,constdoes not - C)
letis block-scoped,constis function-scoped - D) There is no difference; they are interchangeable
Show Answer
**B) `let` allows reassignment, `const` does not** Both `let` and `const` are block-scoped. The key difference is that `const` variables cannot be reassigned after declaration (though objects and arrays declared with `const` can still have their contents modified). Use `const` by default and `let` only when you need to reassign the variable.Question 4
What is the JavaScript equivalent of Python's list comprehension [x * 2 for x in numbers]?
- A)
numbers.forEach(x => x * 2) - B)
numbers.map(x => x * 2) - C)
numbers.filter(x => x * 2) - D)
numbers.reduce(x => x * 2)
Show Answer
**B) `numbers.map(x => x * 2)`** The `.map()` method creates a new array by applying a function to every element, which is the direct equivalent of a Python list comprehension that transforms each element. `.forEach()` does not return a new array. `.filter()` selects elements based on a condition. `.reduce()` accumulates a single result.Question 5
In React, why do we use className instead of class in JSX?
- A) It is a React naming convention with no technical reason
- B) Because
classis a reserved keyword in JavaScript - C) Because
classNameis faster to render - D) Because HTML5 deprecated the
classattribute
Show Answer
**B) Because `class` is a reserved keyword in JavaScript** Since JSX is ultimately JavaScript, and `class` is a reserved keyword used to define classes in JavaScript, React uses `className` to avoid the conflict. This is mapped to the HTML `class` attribute when the JSX is rendered to the DOM.Question 6
What does the useState hook return?
- A) A single value representing the current state
- B) An array with the current state value and a function to update it
- C) An object with
getandsetmethods - D) A Promise that resolves to the state value
Show Answer
**B) An array with the current state value and a function to update it** `useState` returns a pair: `[currentValue, setterFunction]`. This is typically destructured as `const [count, setCount] = useState(0)`. The setter function triggers a re-render of the component with the new value.Question 7
What happens if you call useEffect without a dependency array?
useEffect(() => {
console.log("Effect ran");
});
- A) The effect runs only once when the component mounts
- B) The effect never runs
- C) The effect runs after every render
- D) The effect runs only when props change
Show Answer
**C) The effect runs after every render** Without a dependency array, `useEffect` runs after the initial render and after every subsequent re-render. This is rarely what you want and can cause performance issues or infinite loops (especially if the effect updates state). To run only on mount, pass an empty array `[]`. To run when specific values change, include those values in the array.Question 8
What is "prop drilling" in React?
- A) A performance optimization technique for props
- B) Passing props through intermediate components that do not use them
- C) Validating props with PropTypes
- D) Destructuring props in function parameters
Show Answer
**B) Passing props through intermediate components that do not use them** Prop drilling occurs when data needs to be passed through several layers of components that do not need the data themselves, just to reach a deeply nested component that does. This makes code harder to maintain. Solutions include React Context, state management libraries, or component composition patterns.Question 9
Which CSS layout system is best for a two-dimensional layout (rows AND columns)?
- A) Flexbox
- B) CSS Grid
- C) Float
- D) CSS Tables
Show Answer
**B) CSS Grid** CSS Grid is designed for two-dimensional layouts, controlling both rows and columns simultaneously. Flexbox is optimized for one-dimensional layouts (either a row or a column). While you can create grid-like layouts with Flexbox, CSS Grid provides more precise control over two-dimensional arrangements.Question 10
What does "mobile-first" design mean in the context of CSS media queries?
- A) Building the mobile app before the website
- B) Writing base styles for mobile and using
min-widthmedia queries for larger screens - C) Using only mobile-sized breakpoints
- D) Hiding all content on desktop browsers
Show Answer
**B) Writing base styles for mobile and using `min-width` media queries for larger screens** In a mobile-first approach, the default CSS styles target the smallest screens. Then, `@media (min-width: ...)` queries progressively add or override styles for larger screens. This approach ensures mobile users do not download unnecessary styles and encourages designers to prioritize the most essential content.Question 11
Which ARIA attribute should you use to associate an error message with a form input?
- A)
aria-label - B)
aria-describedby - C)
aria-required - D)
aria-hidden
Show Answer
**B) `aria-describedby`** `aria-describedby` links an element to another element that provides additional descriptive information, such as an error message or help text. The screen reader will announce the described-by content after the input's label. `aria-label` provides the accessible name directly. `aria-required` indicates a required field. `aria-hidden` hides elements from assistive technology.Question 12
What is the minimum touch target size recommended by WCAG 2.1 for interactive elements?
- A) 24x24 pixels
- B) 32x32 pixels
- C) 44x44 pixels
- D) 48x48 pixels
Show Answer
**C) 44x44 pixels** WCAG 2.1 Success Criterion 2.5.5 (Target Size) recommends a minimum target size of 44x44 CSS pixels for interactive elements. This ensures that users with motor impairments, those using touch screens, or those using assistive devices can reliably activate controls. Note that WCAG 2.2 added a stricter Level AA criterion at 24x24 pixels minimum with additional spacing requirements.Question 13
In a controlled React form component, what determines the value displayed in an input field?
- A) The DOM element's internal state
- B) The React component's state
- C) The browser's form auto-fill
- D) The default value attribute
Show Answer
**B) The React component's state** In a controlled component, the React state is the "single source of truth." The input's `value` prop is bound to a state variable, and changes are handled through an `onChange` handler that updates the state. This gives React full control over the form data and enables features like validation, formatting, and conditional rendering.Question 14
What does the AbortController do when used with fetch inside a useEffect cleanup function?
- A) It retries failed network requests
- B) It cancels in-flight HTTP requests when the component unmounts
- C) It caches the response for later use
- D) It logs network errors to the console
Show Answer
**B) It cancels in-flight HTTP requests when the component unmounts** When a component unmounts or re-renders before a fetch request completes, the `AbortController` cancels the pending request. This prevents "state updates on unmounted components" warnings and potential memory leaks. The cleanup function returned by `useEffect` calls `controller.abort()` to trigger the cancellation.Question 15
What is the purpose of the key prop when rendering lists in React?
- A) It sets a CSS class on the element
- B) It helps React identify which items have changed, been added, or removed
- C) It determines the rendering order of elements
- D) It provides accessibility information to screen readers
Show Answer
**B) It helps React identify which items have changed, been added, or removed** The `key` prop gives React a stable identity for each list item. When the list changes, React uses keys to determine which items to update, add, or remove, rather than re-rendering the entire list. Keys should be unique among siblings and stable across re-renders. Using array indices as keys is discouraged when the list order can change.Question 16
Which Tailwind CSS classes create a flex container with centered items and a gap between them?
- A)
display-flex center gap-4 - B)
flex items-center gap-4 - C)
flex align-center spacing-4 - D)
flexbox center-items gap-4
Show Answer
**B) `flex items-center gap-4`** Tailwind uses utility classes that map to CSS properties: `flex` sets `display: flex`, `items-center` sets `align-items: center`, and `gap-4` sets `gap: 1rem`. Tailwind's naming convention is concise and predictable, making it well-suited for AI generation.Question 17
What security risk does dangerouslySetInnerHTML introduce in React?
- A) SQL injection
- B) Cross-site scripting (XSS)
- C) Cross-site request forgery (CSRF)
- D) Server-side request forgery (SSRF)
Show Answer
**B) Cross-site scripting (XSS)** `dangerouslySetInnerHTML` renders raw HTML directly into the DOM without sanitization. If the HTML content comes from user input or an untrusted source, an attacker could inject malicious scripts. React normally escapes content to prevent XSS, but `dangerouslySetInnerHTML` bypasses this protection. If you must use it, always sanitize the HTML first with a library like DOMPurify.Question 18
What is the React Context API primarily used for?
- A) Making API calls to backend servers
- B) Sharing state across components without prop drilling
- C) Managing CSS-in-JS styling
- D) Handling form validation
Show Answer
**B) Sharing state across components without prop drilling** The Context API provides a way to pass data through the component tree without manually threading props through every intermediate component. Common use cases include theme settings, user authentication state, and language/locale preferences. It consists of a Provider (which supplies the value) and consumers (which read the value using `useContext`).Question 19
When asking AI to generate a React component, which prompt will produce the best result?
- A) "Make a card component"
- B) "Create a React card component with title, description, image, and action button"
- C) "Create a React ProductCard component. Props: product object with {id, name, price, imageUrl, description}. Display image (300x200, lazy loaded), name as h3, price formatted as USD, description truncated to 120 chars. Include 'Add to Cart' button that calls an onAddToCart(id) callback. Use Tailwind CSS. Make it accessible."
- D) "Write the best possible card component in React"
Show Answer
**C)** The detailed specification. Effective AI prompts for frontend components should specify: (1) the component name, (2) props with types, (3) visual layout details, (4) behavior and callbacks, (5) styling approach, and (6) accessibility requirements. Option A is too vague. Option B is better but lacks specifics. Option D is vague and subjective. Option C follows the component specification prompt pattern discussed in Section 16.4.Question 20
What is the correct way to conditionally render a component in JSX?
- A)
if (isLoggedIn) { return <Dashboard /> } else { return <Login /> } - B)
{isLoggedIn && <Dashboard />}or{isLoggedIn ? <Dashboard /> : <Login />} - C)
<if condition={isLoggedIn}><Dashboard /></if> - D)
<Dashboard visible={isLoggedIn} />
Show Answer
**B) `{isLoggedIn &&Question 21
Which of the following is NOT a benefit of using component libraries like shadcn/ui or Material UI?
- A) Built-in accessibility compliance
- B) Consistent design across the application
- C) Zero bundle size impact
- D) Pre-built, tested components
Show Answer
**C) Zero bundle size impact** Component libraries add to your bundle size, though the impact varies. Tree-shakeable libraries (where you import only what you use) minimize this impact. The actual benefits include built-in accessibility, design consistency, pre-built and tested components, and faster development. Some libraries like shadcn/ui copy component code into your project rather than adding a dependency, which gives more control but still adds to bundle size.Question 22
What is the purpose of the useEffect cleanup function (the function returned from the effect)?
- A) To handle errors in the effect
- B) To run code before the next effect execution or when the component unmounts
- C) To memoize the effect's return value
- D) To prevent the effect from running on the first render
Show Answer
**B) To run code before the next effect execution or when the component unmounts** The cleanup function is called before the effect re-runs (with new dependency values) and when the component unmounts. Common cleanup tasks include canceling network requests, clearing timers, removing event listeners, and closing WebSocket connections. This prevents memory leaks and stale state updates.Question 23
What is the recommended approach when AI generates frontend code that you do not fully understand?
- A) Use it as-is since AI-generated code is always correct
- B) Delete it and write everything manually
- C) Ask the AI to explain the code section by section, then verify key behaviors
- D) Search Stack Overflow for similar code
Show Answer
**C) Ask the AI to explain the code section by section, then verify key behaviors** Understanding the code you deploy is essential for debugging, maintaining, and extending it. AI is excellent at explaining its own output. Ask for line-by-line explanations, especially for unfamiliar JavaScript patterns, CSS properties, or React hooks. Verify the explanation by testing key behaviors in the browser. This approach also accelerates your learning.Question 24
Which of the following is the most important reason to include accessibility in your AI prompts for frontend code?
- A) It improves SEO rankings
- B) It is required by law in some jurisdictions and ensures your software is usable by everyone
- C) It makes the code easier to test
- D) It reduces bundle size
Show Answer
**B) It is required by law in some jurisdictions and ensures your software is usable by everyone** Accessibility ensures that people with disabilities can use your software. It is legally required in many countries (such as ADA in the US and EAA in the EU) and is a fundamental aspect of inclusive design. While accessibility can also improve SEO and testability, the primary reason is ethical and legal: building software that excludes people with disabilities is both wrong and increasingly illegal.Question 25
You are building a React application and need to decide where to store the user's preferred language setting. The setting should persist across page reloads and be accessible throughout the component tree. What is the best approach?
- A) Store it in a
useStatehook in the App component and pass it as props - B) Store it in
localStorageand read it with a Context provider that initializes fromlocalStorage - C) Store it in the URL as a query parameter
- D) Store it in a global JavaScript variable