Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 61 ยท Practice and Review

Practice Exercises with Solutions

Twelve graded Shopify theme exercises with runnable solutions: Liquid loops and filters, schema checks, cart math, variant logic and accessibility fixes.

Reading about Liquid, sections and the cart is one thing; getting a number or a list exactly right is another. This lesson gives you twelve small exercises, ordered from easy to harder, that cover what theme developers do every day: loops and filters, section schemas, cart math, variant logic and accessibility repairs. Each one has a task, a hint and a solution you can run and change.

Shopify's own Liquid engine and cart live only on Shopify, so the exercises run on stand-ins: plain JavaScript functions that follow the same rules as the Liquid filters, schema validation and cart behavior. What you learn transfers directly, because the logic (what counts as available, how cents are rounded, which variant matches) is the same. All prices are integers in cents, the format Shopify's JavaScript data uses. Every solution ends with console.assert-style checks that print ok or FAILED, so a wrong answer fails loudly.

How to work: read the task, clear the editor or copy the starter somewhere, write your own version, run it, and only then compare with the solution. If yours passes the checks but looks different, ask which version you would rather maintain.

flowchart LR
  A["1-3 Liquid<br/>lists and text"] --> B["4-5 Schema<br/>and templates"]
  B --> C["6-8 Cart<br/>math"]
  C --> D["9-10 Variants<br/>and badges"]
  D --> E["11-12 Accessibility<br/>and pagination"]

The exercises move from reading data, to designing sections, to money, to choices, to quality.

The tests use a tiny helper check(name, actual, expected) that compares values with JSON.stringify. It is repeated in every block so each exercise runs on its own.

Exercise 1: The first available titles (easy)

Task. In Liquid you would write {% for product in collection.products limit: 3 %} and skip sold-out items with {% if product.available %}. Write firstAvailableTitles(products, n) that returns the titles of the first n available products, in the original order. Remember that limit counts loop iterations, so filtering inside the loop can show fewer than n items; here we want exactly n when enough exist.

Hint. Filter first, then slice.

JS Exercise 1 solution

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In Liquid the same result needs the filter first: {% assign in_stock = collection.products | where: 'available' %} and then limit: 3 on the new array.

Exercise 2: Format a price label (easy)

Task. Write priceLabel(product) that returns "$14.00" for a normal product, "From $22.00" when the variants have different prices (priceVaries is true), and "Sold out" when it is not available. Prices are cents. This mirrors a card's use of product.price_varies and the money filter.

Hint. Check availability first; sold-out wins over everything else.

JS Exercise 2 solution

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 3: Make a handle (medium)

Task. Liquid's handle filter turns a title into a URL-safe string. Write handleize(text) that lowercases, replaces every run of characters that are not letters or digits with a single hyphen, and trims hyphens from both ends. (Shopify's real filter also transliterates accents; ours keeps to ASCII.)

Hint. One regular expression for the runs, one for the ends.

JS Exercise 3 solution

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 4: Validate a section schema (medium)

Task. A schema's settings must have unique id values, every range needs min, max and step, and its default must lie inside the range. Write schemaProblems(schema) that returns a list of problem strings (empty when the schema is fine). This is a small version of what Theme Check reports.

Hint. Keep a Set of seen ids.

JS Exercise 4 solution

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 5: Resolve a JSON template (medium)

Task. A JSON template lists sections (each with a type) and an order array. Write renderTemplate(template, sectionFiles) that returns the section types in order, skipping ids that are missing from sections and throwing an error that names any section whose type has no file. This is how Shopify assembles a page.

Hint. Loop over order, not over Object.keys(sections), because only order decides sequence.

JS Exercise 5 solution

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 6: Cart total and free shipping bar (medium)

Task. Each cart line has a price (cents) and quantity. Write cartSummary(lines, threshold) that returns the total and how much more the shopper must spend to reach the free-shipping threshold (never negative), plus a progress percentage capped at 100 and rounded to a whole number.

Hint. Multiply price by quantity per line; sum integers, never floats.

JS Exercise 6 solution

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 7: Share a discount across lines (hard)

Task. A cart-level discount of discount cents must be split across lines in proportion to each line's total, with no cent lost. Write allocate(lineTotals, discount) returning an array of discount amounts that sums to exactly discount. Give leftover cents to the lines with the largest fractional remainders. This is the rounding problem that makes order totals disagree by a cent.

Hint. Take the floor of each share, then hand out the remaining cents one at a time. See money as integers for the background.

JS Exercise 7 solution

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 8: Group bundle lines (medium)

Task. Cart lines may carry a properties._bundle value. Write groupBundles(lines) that returns an object mapping each bundle id to the list of variant ids, ignoring lines with no bundle property. This is what a cart snippet does to show "Part of a bundle".

Hint. The nullish assignment ??= creates the list on first use.

JS Exercise 8 solution

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 9: Find the selected variant (medium)

Task. A product has up to three options. Write findVariant(variants, selected) where selected is an array such as ['Blue', 'M']. Return the matching variant or null. Then write isOptionAvailable(variants, selected, position, value) that says whether choosing value at position (0-based) still leaves an available variant, given the other selections. Unavailable combinations should be disabled in the picker, not hidden.

Hint. Compare option arrays element by element; for availability, copy selected and replace one position.

JS Exercise 9 solution

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 10: Sale badge percentage (medium)

Task. Write saleBadge(price, compareAt) that returns "Save 25%" (rounded to a whole percent) when compareAt is greater than price, and "" otherwise. Guard against a missing or zero compareAt, because dividing by zero produces Infinity or NaN and would print nonsense.

Hint. Compute (compareAt - price) / compareAt, and test the guard first.

JS Exercise 10 solution

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 11: Find the accessibility problems (hard)

Task. Markup from a theme section is given as a list of elements. Write a11yProblems(elements) that reports: an img with no alt attribute (an empty alt is allowed, it marks a decorative image); a button with no text and no ariaLabel; and an input with neither label nor ariaLabel. Return messages in order. This is what an automated checker does; it cannot judge whether the alt text is good, only that the attribute exists.

Hint. Test alt === undefined, not "falsy", so an empty alt passes.

JS Exercise 11 solution

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 12: Paginate a collection (hard)

Task. Liquid's paginate tag slices a list into pages. Write paginate(items, pageSize, page) returning { items, page, pages, hasPrev, hasNext }. Clamp the page number into the valid range, because shoppers edit URLs: ?page=999 should show the last page, and ?page=0 or a non-number should show the first. An empty list has one (empty) page.

Hint. pages = Math.max(1, Math.ceil(length / pageSize)).

JS Exercise 12 solution

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why do the exercises keep prices as integer cents?

    Integers add and compare exactly. Convert to a display string only at the last step, as the money filter does.
  2. 2. In Exercise 11, why must the checker test alt === undefined rather than a falsy alt?

    alt="" tells assistive technology to skip a decorative image. Only a missing attribute is an error.
  3. 3. What is the reason to split a discount with remainders handed out one cent at a time?

    Flooring each share loses cents. Distributing the leftover cents by largest remainder keeps the sum exact.
  4. 4. Why does the template resolver in Exercise 5 loop over order instead of the sections object?

    The keys of sections are just ids. The order array lists which of them render, and in which sequence.
  5. 5. A shopper visits ?page=999 on a collection with 3 pages. What should a robust paginate do?

    URLs can be edited by anyone. Clamping into 1 to pages gives a sensible page instead of an error or a blank screen.

Summary

  • Practice with exact integer cents, and convert to display text only at the end.
  • Filter before you limit, so a sold-out product does not use up a slot.
  • Validate schemas and templates with small functions; Theme Check does the same at scale.
  • Distribute discounts by largest remainder so totals agree to the cent.
  • Match variants by comparing option arrays, and disable (not hide) unavailable combinations.
  • Treat shopper-editable input, such as page numbers, defensively, and treat a missing alt attribute (not an empty one) as an accessibility error.

Next, rehearse explaining these ideas aloud in Shopify Theme Developer Interview Questions.