How a diff decides what changed: the shortest list of edits
Comparing two texts sounds simple: walk down both and mark the lines that differ. That fails the moment a line is inserted near the top, because every line after it is now one place out and would be marked as changed. A diff tool answers a better question: what is the smallest set of lines to remove from the first text and add to get the second? The lines that are left over, in the same order in both, are the ones that did not change.
Take a three line snippet. The original is const a = 1;, const b = 2;, return a + b;. The new version changes only the middle line to const b = 3;. A diff finds that two lines are shared and in order, so the shortest edit is to remove const b = 2; and add const b = 3;. That is what Lines mode shows: line 1 unchanged, a − line for the old line 2, a + line for the new one, and line 3 unchanged. Because the removed and added lines sit next to each other, the tool also compares them word by word and picks out the 2 and the 3. Paste the two versions above to see it.
Finding the smallest set of edits is the work of an algorithm published by Eugene Myers in 1986, the same one git uses by default. It explores the possible edit paths in order of how many edits they need, so the first path that reaches the end of both texts is a shortest one. Before it starts, the tool skips the lines the two texts share at the start and the end, which makes the common case, a few changes in a long file, fast. The search also has a limit: past about 2,000 differences it stops and shows the whole differing middle as removed and then added. That is still a correct diff, only a longer one, and it keeps the page responsive on two very different texts.
Lines are the right unit for code and data, but the wrong one for prose. If someone edits one word in a paragraph and their editor re-wraps it, every line of the paragraph is different, and a line diff marks them all. Words mode ignores line breaks and runs the same algorithm over words and punctuation instead. "The quick brown fox jumps." against "The slow red fox jumps." shows quick brown struck out and slow red added, and nothing else.
A few limits are worth knowing. The copied unified diff has no hunk headers or file names, so tools such as git apply cannot use it, though people can read it. The comparison does not detect moved blocks: a function moved to the end of a file shows as removed in one place and added in another. Ignore spacing works within a line, so an added or removed blank line still counts as a change. And the two texts are compared as you paste them, in your browser, so nothing is uploaded, but a very large pair of files will take a moment to show.