Last updated
How Code Diff Works
A diff (difference) shows the changes between two versions of a file.
The standard diff algorithm (Myers diff) finds the shortest edit script —
the minimum number of insertions and deletions needed to transform one text
into another. Lines prefixed with + are additions;
lines with - are deletions; unchanged lines provide context.
Unified Diff Format
Diff
--- a/app.js 2026-03-20 10:00:00
+++ b/app.js 2026-03-22 14:30:00
@@ -1,7 +1,8 @@
const express = require('express');
const app = express();
+const cors = require('cors');
-app.listen(3000, () => {
- console.log('Server running');
+app.use(cors());
+app.listen(process.env.PORT || 3000, () => {
+ console.log(`Server running on port ${process.env.PORT || 3000}`);
});
Generating Diffs in JavaScript
JavaScript
import { diffLines, diffWords } from 'diff';
// Line-by-line diff
const changes = diffLines(oldText, newText);
changes.forEach(part => {
const prefix = part.added ? '+' : part.removed ? '-' : ' ';
const color = part.added ? '[32m' : part.removed ? '[31m' : '';
process.stdout.write(color + part.value.split('
')
.map(l => prefix + l).join('
') + '[0m');
});
// Word-level diff (inline)
const wordChanges = diffWords('Hello World', 'Hello Beautiful World');
wordChanges.forEach(part => {
if (part.added) process.stdout.write('[+' + part.value + ']');
else if (part.removed) process.stdout.write('[-' + part.value + ']');
else process.stdout.write(part.value);
});