Read a Change in Order

Monday’s queue can wait for now. Before you weigh five pull requests against each other, you need a way to read any one of them, and the diff is the wrong place to start. Code shown cold invites you to judge it on its own terms, so you end up agreeing with whatever it does.

In this lesson, you’ll read a merged change in a fixed order: the intent, the description, the list of files, then each hunk with enough of the file around it. You’ll check your summary with a run, and you’ll tell code that was only reformatted or moved from code that changed. Start with the shop on the right commit.

Read the Description and the List of Files

A pull request comes with a story, told by its title and description and backed by its author’s confidence. When you read in a fixed order, that story can’t do your thinking for you, because each step gives you something to check the next against.

This course builds on Intermediate JavaScript and the first three courses on The Second Draft, where you started your map.md. From Intermediate JavaScript, it assumes modules, nested data, higher-order functions, classes, and custom errors.

The coding exercises run in your browser. The first exercise comes after the next video, and its Contents tab explains how to use it. Put the shop on this course’s commit:

If you took the last course, open a terminal in your second-draft-books folder and run only the last three commands.

If you’re arriving directly, install Git and a current version of Node.js. The examples use Node 26. Then run all the commands, and create an empty map.md in your home folder, outside the repository:

Language: Windows PowerShell
PS> git clone https://github.com/realjs/second-draft-books.git
PS> cd second-draft-books
PS> mkdir $HOME\checks
PS> git switch main
PS> git log --oneline -1
3d15f97 Record Grace’s gift-card purchase criteria alongside redemption
PS> npm run seed
Language: Shell
$ git clone https://github.com/realjs/second-draft-books.git
$ cd second-draft-books
$ mkdir ~/checks
$ git switch main
$ git log --oneline -1
3d15f97 Record Grace’s gift-card purchase criteria alongside redemption
$ npm run seed

The line after git log --oneline -1 must start with 3d15f97, the commit this course’s line numbers come from. If it doesn’t, then run git fetch origin and git switch --detach 3d15f97, followed by npm run seed. Switching with --detach leaves your branches as they are.

If you arrive directly, use the shop once before reading its code, as docs/FIRST-HOUR.md suggests: run npm start, open http://127.0.0.1:3000/admin/, and place one order. Then stop the server with Ctrl+C and run npm run seed again.

You’ll read pull request #25, which Margaret wrote and Edsger reviewed. It landed on main after v1.5, so it’s real and safe to read without touching Monday’s queue.

As the last course taught, write the intent before you open the description or the diff. Pull request #25’s title, “Return the last rounding penny,” is its request. You know the problem from Nadia’s refund. In src/refunds/allocation.js, refundValue() rounds each return’s share on its own, so the shares can fall short of the payment.

Add a ## Reviews heading to map.md and, under ### #25, write the intent in one sentence. Here’s an example: once every paid book is back, the refunds add up to what the customer paid, and never more, without changing how earlier returns are worked out (Nadia’s 450p is its own bug).

Now open docs/pulls/25.md, the exported discussion. Margaret’s description makes three promises: the last paid item gets “any unreturned penny,” the payment limit still applies, and earlier partial returns are allocated as before. In the last course, you judged this pull request’s test diff and found that its one new test is evidence for the first promise only.

Treat the description as the author’s claim, and use the rest of the reading to check it. Next, see how big the job is. git show prints a commit’s message and changes, --stat swaps the changes for a list of files, and --oneline shortens the header:

Language: Shell
$ git show --stat --oneline 4efa63b
4efa63b Return the final rounding penny without changing partial allocations (review #25)
 docs/pulls/25.md      |  8 ++++++++
 src/refunds/create.js |  8 ++++++++
 test/refunds.test.js  | 15 +++++++++++++++
 3 files changed, 31 insertions(+)

Each line counts one file’s added (+) and removed (-) lines. If the output fills your screen, press Q to leave Git’s pager. You’ve read the discussion and judged the test, which leaves eight added lines of src/refunds/create.js.

Read Each Hunk With Enough Code Around It

A diff shows each changed block, called a hunk, with only three unchanged lines of context around it. New lines often depend on code further up or down, so a hunk read on its own can look right and mean something else. Ask Git for the one file that’s left:

Language: Shell
$ git show --oneline 4efa63b -- src/refunds/create.js
4efa63b Return the final rounding penny without changing partial allocations (review #25)
diff --git a/src/refunds/create.js b/src/refunds/create.js
index 83a2e48..490083c 100644
--- a/src/refunds/create.js
+++ b/src/refunds/create.js
@@ -17,6 +17,14 @@ export function createRefund(state, input) {
     let value = 0;
     for (let returned of returns) value += returned.value;
     let amount = refundValue(order, value);
+    let remainingPaidValue = 0;
+    for (let line of order.lines) {
+        if (!line.complimentary) {
+            remainingPaidValue += line.unitPrice * (line.quantity -
⮑ (line.returned || 0));
+        }
+    }
+    // The last paid book receives any penny left by earlier rounding.
+    if (value === remainingPaidValue) amount = order.total - order.refunded;
     // Independent rounding on each return must never send back more than was paid.
     if (amount > order.total - order.refunded) amount = order.total - order.refunded;
     let refund = { id: nextId(state.refunds, 'refund'), orderId: order.id,

The @@ -17,6 +17,14 @@ line says that six lines from line 17 of the old file became fourteen in the new one. The line wrapped with ⮑ is one line in your terminal.

Open src/refunds/create.js in your editor at createRefund(), and read lines 14 to 43 around the hunk. You need three things from the unchanged code:

  • Line 18: value holds the sum of the returned books’ values. Line 19 of src/refunds/lines.js gives a complimentary book a value of 0, so value includes only paid books’ values.
  • Line 34: A book’s returned count goes up only after the hunk has run. So when line 23 reads line.returned, the current return isn’t counted yet.
  • Line 37: order.refunded grows with each refund, so order.total - order.refunded is what’s left of the payment.

Together, those make the hunk readable. Lines 20 to 25 add up the values of the paid books still with the customer before this return. If this return brings all of them back, then line 27 refunds everything that’s left of the payment, and line 29, untouched, still caps it.

Write that summary in your own words under #25, next to Margaret’s promises. Line 29 keeps the second. Line 27 fires only on the last return, so earlier returns keep their amounts, as the third says. The first differs, because she says “any unreturned penny,” while line 27 returns whatever is left, however much that is.

Pull request #25 removes nothing, but most changes do. Read red lines as closely as green ones, and for each removed check, find what does its job now. If nothing does, then the removal changes behavior and belongs in the intent.

A summary is still a reading, so check it with a run. Nadia paid 2400p for order-1 in the seed data, and main still refunds 450p for her Small Maps, the bug from the second course. Create last-return.mjs in your checks folder, starting with this loading code. It loads src/refunds/create.js and data/seed.json, and its await expressions wait for them. Copy it as it is, since how it works is outside this lesson:

Language: JavaScript
import { readFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import { pathToFileURL } from 'node:url';

const file = resolve('src/refunds/create.js');
const refunds = await import(pathToFileURL(file));

const text = await readFile('data/seed.json', 'utf8');
const state = JSON.parse(text);

The check itself is plain synchronous code. It returns Small Maps, then The Long Way Home, the last paid book, as two refunds:

Language: JavaScript
const first = refunds.createRefund(state, { orderId: 'order-1',
    items: [{ bookId: 'book-1', quantity: 1 }] });
console.log('Small Maps:', first.amount);
const second = refunds.createRefund(state, { orderId: 'order-1',
    items: [{ bookId: 'book-2', quantity: 1 }] });
console.log('The Long Way Home:', second.amount);

It changes state in memory only, not your data files. Use your summary to predict the second refund, then run the check from your second-draft-books folder with node ~/checks/last-return.mjs, or node $HOME\checks\last-return.mjs in Windows PowerShell:

Language: Text
Small Maps: 450
The Long Way Home: 1950

The second return brings back the last paid book, so line 27 refunds everything that’s left: 2400p minus 450p is 1950p. On v1.5, before #25, the same check prints 1350p, the book’s share alone, so line 27 sends back 600p more. The refunds now add up to 2400p, but only because the last refund makes up for the earlier short refund. Your intent leaves the 450p bug out of scope, and the description never says so. That’s the difference to write down.

To see the 1350p, run git switch --detach v1.5 and the check, then go back with git switch --detach 3d15f97 and npm run seed.

Compare the run with your prediction, and write under #25 any difference between the description and the code. Whether the shop wants that behavior is a question for the intent, which a later lesson covers. To test your summary, click the button below to open Code Mentor, and paste the summary after its question:

Check each point in the reply against a line number in create.js before you change your summary.

Tell Moved Code From Changed Code

Not every red and green line changes behavior. A reformat rewrites lines without changing what they do, and a move deletes a block in one place and adds it in another. Both make a diff look bigger than its change.

You met Edsger’s formatter commit, 9dd98af, when git blame pointed at it in the second course. Read it in the same order as #25. Its intent: bring the code to the team’s indentation without changing what it does. Its description is the commit message, and --shortstat cuts the file list down to its total:

Language: Shell
$ git show --shortstat --oneline 9dd98af
9dd98af Apply the team indentation style
 40 files changed, 473 insertions(+), 473 deletions(-)

The message matches the intent, so check the 473 lines against it. The -w option tells git diff to ignore whitespace, and 9dd98af^ means the commit before 9dd98af:

Language: Shell
$ git diff -w 9dd98af^ 9dd98af

It prints nothing, so only whitespace changed. That isn’t proof of safety yet. In JavaScript, a space can decide where a token ends: a + ++b and a++ + b look the same to -w but compute different values. A space inside a string or a regular expression is part of its value too.

The -b option is stricter. It treats a longer or shorter run of spaces as equal, but shows a space added where there was none or removed altogether, which is what joins or splits tokens:

Language: Shell
$ git diff -b 9dd98af^ 9dd98af

It also prints nothing, so no token was joined or split. What -b can’t see is a run of two or more spaces that grew or shrank inside a string or regular expression. Such a run follows other text, so search the changed lines for a non-space character followed by two spaces. The -G option lists commits whose added or removed lines match a pattern, and 9dd98af^..9dd98af limits it to this commit:

Language: Shell
$ git log --oneline "-G[^ ]  " 9dd98af^..9dd98af

No commit is listed, so every changed space is indentation, and the commit does what its message says. These checks cover spaces, not tabs, which the shop doesn’t use, and not the leading spaces of a template literal that spans lines, where indentation is part of the string. 9dd98af re-indents no such literal.

A move needs one more check. It shows up as a red hunk and a green hunk with the same lines, often in two files, and git diff --color-moved paints such lines in their own colors. Matching lines don’t prove matching behavior, though, because moved code runs among its new file’s imports. The shop has two formatPrice() functions, in src/lib/money.js and src/reports/csv.js.

Try a move on the second one. The scenario is made up for this lesson. Suppose a teammate moves it in a pull request, and you make the same change so you can review its diff. You’ll undo it at the end. In your editor, cut lines 1 to 3 of src/reports/csv.js, its formatPrice(), into a new file, src/reports/price.js. Where the function was, put the line the teammate wrote:

Language: JavaScript
import { formatPrice } from '../lib/money.js';

That path is the teammate’s slip, which you reproduce so you can review it. A clean move would import from ./price.js. Then stage both files with git add, so that the diff includes the new one. Show the change with --staged, which compares what you staged with the commit. In your terminal, the function gets the colors for moved code, and only the import line is plain green. The button under the output opens Code Mentor with this diff attached:

Language: Shell
$ git add src/reports
$ git diff --staged --color-moved
diff --git a/src/reports/csv.js b/src/reports/csv.js
index eab13cb..00cec22 100644
--- a/src/reports/csv.js
+++ b/src/reports/csv.js
@@ -1,6 +1,4 @@
-export function formatPrice(pence) {
-    return (pence / 100).toFixed(2);
-}
+import { formatPrice } from '../lib/money.js';

 export function salesCsv(rows) {
     let output = 'order_id,date,paid_gbp,refunded_gbp,net_gbp\n';
diff --git a/src/reports/price.js b/src/reports/price.js
new file mode 100644
index 0000000..11828ad
--- /dev/null
+++ b/src/reports/price.js
@@ -0,0 +1,3 @@
+export function formatPrice(pence) {
+    return (pence / 100).toFixed(2);
+}

Read the moved pair line by line. They match, so the function didn’t change. What a move can change is which function a caller reaches. For each name the move touches, find what it refers to now, then run the behavior that depends on it. The last question below does that for salesCsv(), so keep the move until then.

Check Your Understanding

Answer these with map.md and src/refunds/create.js open:

  1. A teammate opens a pull request’s diff first, then reads its description and agrees with both. What did they skip, and why does the order matter?
  2. In createRefund(), why does the loop on lines 21 to 25 count the books in the current return as still with the customer?
  3. A pull request changes 12 files, with 210 insertions and 205 deletions. Its git diff -w shows one hunk, in src/discounts/policy.js. Which hunks do you read closely, and how do you clear the rest?
  4. After your practice move, which formatPrice() does salesCsv() call? Name the line that decides it, then check with npm run weekly-report.
  1. They skipped the intent. Written after the diff and the description, it can only describe what the change does, so the change meets it by definition. Written first, it’s something to check both against.
  2. Line 34 adds the current return to line.returned after the hunk has run. So remainingPaidValue holds the total value of the paid books that were out before this return, and line 27 fires when this return brings all of them back.
  3. Read the hunk in policy.js closely, because it’s the only change that isn’t whitespace. Clear the rest with git diff -b, for spaces added or removed between tokens, and the -G search, for runs of spaces that grew or shrank in strings or regular expressions. If both show nothing and no multiline template literal was re-indented, the rest is indentation.
  4. Line 1 of src/reports/csv.js imports the formatPrice() in src/lib/money.js, which adds a pound sign. Nothing imports the moved one in price.js:

    Language: Shell
    $ npm run weekly-report
    
    > [email protected] weekly-report
    > node scripts/report.js
    
    order_id,date,paid_gbp,refunded_gbp,net_gbp
    order-1,2026-11-16,£24.00,£0.00,£24.00
    

    The moved lines match, but one import changes the behavior.

Undo the practice move with git reset --hard, which discards every uncommitted change in the repository, the new file included. Your map.md now has #25’s intent, your summary, and one difference from its description. In the next lesson, Look Beyond the Diff, you’ll follow a change past its own lines, to the code that reads what it touched.

Become a Member to join the conversation.