Practice Questions

1. What is the purpose of the integrity and crossorigin attributes when loading a library from a CDN? What problem do they solve?

Solution

The integrity attribute contains a cryptographic hash that the browser uses to verify the fetched file has not been tampered with. If the hash does not match, the browser refuses to load the resource. This protects against compromised CDN servers delivering malicious code.

The crossorigin="anonymous" attribute tells the browser to make a CORS (Cross-Origin Resource Sharing) request without sending credentials (like cookies). This is required for the integrity check to work on resources loaded from a different origin.

Together, they implement Subresource Integrity (SRI). That is what makes it safe to load a file you do not host yourself.

2. Explain how Bootstrap’s grid system works. What are the roles of container, row, and col? How many columns does the grid have?

Solution

Bootstrap’s grid system is built with flexbox and organizes content into three levels:

  • container: Centers the content and gives it a maximum width. It acts as the outermost wrapper.
  • row: Creates a horizontal group of columns. It uses flexbox to lay out its children side by side.
  • col: Defines individual columns within a row. By default, columns share the available space equally.

The grid is divided into 12 columns. You can specify how many of those 12 columns an element should span (e.g., col-6 takes half the row). Using just col divides the space equally among all columns in that row.

3. What are Bootstrap breakpoints? Given the following column class, explain what happens at different screen sizes:

<div class="col-sm">Content</div>
Solution

Breakpoints are predefined screen widths where the layout behavior changes. Bootstrap defines breakpoints at specific pixel widths: extra small (<576px), small (>=576px), medium (>=768px), large (>=992px), extra large (>=1200px), and extra extra large (>=1400px).

With col-sm, the column behaves as a full-width stacked element on extra small screens (below 576px). Once the screen reaches 576px or wider, it shares the row space equally with other col-sm columns. This keeps you from getting a layout where some columns sit side by side and others are still stacked.

4. What is the difference between onclick and addEventListener for handling events? Why is addEventListener generally preferred?

Solution

Both attach event handlers to elements, but they differ in a few ways:

  • onclick (property-based): Assigning a function to element.onclick sets a single handler. Assigning a new function replaces the previous one.

    button.onclick = handleClick;
    button.onclick = anotherHandler;  // replaces handleClick
    
  • addEventListener (method-based): Allows multiple handlers for the same event on the same element. Each call adds a new handler without removing existing ones.

    button.addEventListener("click", handleClick);
    button.addEventListener("click", anotherHandler); // both run
    

addEventListener is preferred because it supports multiple handlers, gives more control over event behavior, and is the standard approach in modern JavaScript.

5. Write JavaScript code that selects a button element with the id "submit", and attaches a click event listener that logs "Button clicked!" to the console.

Solution
const submitBtn = document.getElementById("submit");

submitBtn.addEventListener("click", function () {
  console.log("Button clicked!");
});

Alternatively, using a named function:

const submitBtn = document.getElementById("submit");

function handleClick() {
  console.log("Button clicked!");
}

submitBtn.addEventListener("click", handleClick);

6. When a function is used as an event handler, the browser passes an event object to it. What information does this object contain, and how would you use event.target to determine which element triggered the event?

Solution

The event object contains information about what triggered the event: which element was clicked, mouse position, whether modifier keys were held, the event type, and more.

event.target refers to the actual DOM element that triggered the event. You can read its properties (like id, textContent, className) to determine which specific element was clicked.

function handleClick(event) {
  console.log("Clicked element id:", event.target.id);
  console.log("Clicked element text:", event.target.textContent);
}

document.getElementById("btn1").addEventListener("click", handleClick);
document.getElementById("btn2").addEventListener("click", handleClick);

This pattern is useful when several elements share the same handler. You use event.target to tell which one was clicked.

7. Write a JavaScript expression that generates a random integer between 0 and 4 (inclusive). Explain how Math.random() and Math.floor() work together.

Solution
const randomInt = Math.floor(Math.random() * 5);
  • Math.random() returns a floating-point number in the range [0, 1) — that is, from 0 (inclusive) up to but not including 1.
  • Multiplying by 5 gives a range of [0, 5).
  • Math.floor() rounds down to the nearest integer, producing one of: 0, 1, 2, 3, or 4.

The general pattern for a random integer from 0 to n-1 is:

Math.floor(Math.random() * n);

8. What does document.getElementById() return? What happens if no element with the given id exists? Write code that safely updates an element’s text only if it exists.

Solution

document.getElementById() returns the DOM element with the matching id, or null if no such element exists.

const heading = document.getElementById("title");

if (heading !== null) {
  heading.innerHTML = "Updated Title";
}

If you try to access a property on null (e.g., heading.innerHTML when heading is null), JavaScript throws a TypeError. That is why checking for null before using the result is a good practice.

9. What is the difference between innerHTML and textContent? Given the following code, what does the page display?

const el = document.getElementById("output");
el.innerHTML = "Hello <strong>World</strong>";
Solution
  • innerHTML parses the assigned string as HTML, rendering any tags it contains.
  • textContent treats the string as plain text, displaying tags literally without rendering them.

With the code above, the page displays: Hello World (with “World” in bold), because innerHTML interprets the <strong> tag as HTML.

If you used textContent instead:

el.textContent = "Hello <strong>World</strong>";

The page would display the literal text: Hello <strong>World</strong> with the tags visible.

10. Explain what the following Bootstrap utility classes do: my-5, p-5, w-100, gap-2, text-center. How does Bootstrap’s spacing shorthand notation work?

Solution
  • my-5: Adds margin on the y-axis (top and bottom), size 5 (the largest default).
  • p-5: Adds padding on all four sides, size 5.
  • w-100: Sets the element’s width to 100% of its parent.
  • gap-2: Adds a gap (space) between flex/grid children, size 2.
  • text-center: Centers inline content (text, inline elements) within the element.

Bootstrap’s spacing notation follows the pattern {property}{sides}-{size}:

  • Property: m for margin, p for padding.
  • Sides: t (top), b (bottom), s (start/left), e (end/right), x (left and right), y (top and bottom), or blank (all sides).
  • Size: 0 through 5, where 0 removes spacing and 5 is the largest.

For example, pt-3 means padding-top at size 3, and mx-auto centers an element horizontally using auto margins.

11. You have three <div> elements that should appear side by side on medium screens and larger, but stack vertically on smaller screens. Write the HTML using Bootstrap’s grid system to achieve this.

Solution
<div class="container">
  <div class="row">
    <div class="col-md">First</div>
    <div class="col-md">Second</div>
    <div class="col-md">Third</div>
  </div>
</div>

Using col-md means the columns stack vertically below 768px (the medium breakpoint) and appear side by side at 768px and above. Each column takes equal width when displayed horizontally.

You could also add a gap class to the row for spacing when stacked:

<div class="row gap-2"></div>

12. Compare using a CDN versus downloading a library locally. What are the advantages and disadvantages of each approach?

Solution

CDN (Content Delivery Network) approach:

Advantages:

  • No files to manage in your project; just include a URL.
  • CDN servers are globally distributed, so users download from a nearby server, which can improve load times.
  • If many sites use the same CDN URL, the browser may already have the file cached.

Disadvantages:

  • Requires an internet connection; your site breaks offline.
  • You depend on a third-party service; if the CDN goes down, your site loses its styles or functionality.
  • A compromised CDN could serve malicious code (mitigated by the integrity attribute).

Local download approach:

Advantages:

  • Works offline; all files are self-contained.
  • No dependency on external services.
  • Full control over the exact version used.

Disadvantages:

  • Increases your project’s file size.
  • You must manually update when new versions are released.
  • No benefit from shared caching across sites.