deep-diff, diff, diff2html, and diff3 are specialized utilities for detecting, visualizing, and resolving changes in data and text. diff is the foundational library for comparing strings and generating patches. deep-diff focuses on comparing complex JavaScript objects recursively. diff2html takes raw diff output and renders it into readable HTML for UI display. diff3 handles three-way merges, typically used in version control scenarios where you need to reconcile changes from two branches against a common ancestor.
When building tools that track changes, sync data, or visualize updates, choosing the right diffing library is critical. deep-diff, diff, diff2html, and diff3 each solve specific parts of this problem. diff handles the core text comparison logic. deep-diff specializes in JavaScript object structures. diff2html focuses on presentation. diff3 tackles the complex logic of three-way merges. Let's break down how they work and when to use them.
The fundamental difference lies in what data they compare and how they handle the result.
diff is the standard for text comparison.
// diff: Line-based comparison
import { diffLines } from 'diff';
const text1 = 'line 1\nline 2';
const text2 = 'line 1\nline 3';
const changes = diffLines(text1, text2);
changes.forEach((part) => {
console.log(part.added ? 'Added' : part.removed ? 'Removed' : 'Unchanged', part.value);
});
deep-diff is built for JavaScript objects.
// deep-diff: Object comparison
import Diff from 'deep-diff';
const obj1 = { name: 'Alice', role: 'Dev' };
const obj2 = { name: 'Alice', role: 'Engineer' };
const differences = Diff(obj1, obj2);
differences.forEach((d) => {
console.log(d.kind, d.path, d.lhs, d.rhs);
});
diff2html does not compute diffs itself.
diff or Git) and converts them to HTML.// diff2html: Rendering HTML
import { Diff2Html } from 'diff2html';
const diffInput = '--- a/file.js\n+++ b/file.js\n@@ -1 +1 @@\n-old code\n+new code';
const htmlOutput = Diff2Html.html(diffInput, { drawFileList: true });
document.body.innerHTML = htmlOutput;
diff3 handles three-way merges.
// diff3: Three-way merge
import { diff3 } from 'diff3';
const original = 'line 1\nline 2\nline 3';
const mine = 'line 1\nline 2 modified\nline 3';
const theirs = 'line 1\nline 2\nline 3 updated';
const result = diff3(mine, original, theirs);
console.log(result.ok || result.conflict);
Displaying changes to a user requires more than just computing them. You need formatting.
diff returns data structures.
// diff: Raw output
import { createTwoFilesPatch } from 'diff';
const patch = createTwoFilesPatch('file1.txt', 'file2.txt', content1, content2);
// Returns a string like standard `git diff` output
console.log(patch);
deep-diff returns change descriptions.
kind: 'E' (edited) or kind: 'D' (deleted).// deep-diff: Change metadata
import { applyChange } from 'deep-diff';
// You can apply changes to clone an object
const clone = JSON.parse(JSON.stringify(obj1));
applyChange(clone, obj1, differences);
console.log(clone);
diff2html generates ready-to-use HTML.
// diff2html: Configurable HTML output
import { Diff2Html } from 'diff2html';
const html = Diff2Html.html(diffString, {
outputFormat: 'side-by-side',
drawFileList: true,
matching: 'lines'
});
// Directly injectable into DOM
diff3 returns merge results.
// diff3: Conflict detection
import { diff3 } from 'diff3';
const mergeResult = diff3(mine, original, theirs);
if (mergeResult.conflict) {
// Handle conflict markers manually
console.log('Conflicts found:', mergeResult.conflict);
}
Real-world data is messy. Libraries handle errors and conflicts differently.
diff handles whitespace and newlines flexibly.
// diff: Ignoring whitespace
import { diffChars } from 'diff';
const diff = diffChars('Hello World', 'hello world', { ignoreCase: true });
// Treats case differences as unchanged
deep-diff handles circular references and arrays.
// deep-diff: Filtering properties
import { createDiff } from 'deep-diff';
const diff = createDiff({
prefilter: (path, key) => key === 'timestamp' // Ignore timestamp
});
const changes = diff(obj1, obj2);
diff2html relies on input quality.
// diff2html: Error handling
try {
const html = Diff2Html.html(invalidDiffString);
} catch (e) {
console.error('Invalid diff format');
}
diff3 is designed specifically for conflicts.
// diff3: Structured conflicts
import { diff3 } from 'diff3';
const result = diff3(mine, original, theirs);
// result.ok contains merged lines
// result.conflict contains conflicting sections
While they serve different purposes, these libraries share some common goals and patterns.
// Example: Non-mutating comparison
// diff
const changes = diffLines(original, modified);
// original is untouched
// deep-diff
const diffs = Diff(obj1, obj2);
// obj1 and obj2 are untouched
// diff: Custom comparator
const diff = diffLines(a, b, { comparator: (left, right) => left.trim() === right.trim() });
// diff2html: Custom templates
const html = Diff2Html.html(diff, { template: 'custom-template' });
diff and diff2html align with Git-style patch formats.deep-diff uses a standard change notation (kind, path, value).// diff: Unified Patch
const patch = createTwoFilesPatch('a', 'b', content1, content2);
// Compatible with `git apply`
// deep-diff: Standard Change Object
// { kind: 'E', path: ['name'], lhs: 'Old', rhs: 'New' }
| Feature | diff | deep-diff | diff2html | diff3 |
|---|---|---|---|---|
| Primary Input | Strings / Text | JavaScript Objects | Diff Strings | Three Text Strings |
| Output | Change Array / Patch | Change Array | HTML String | Merged Text / Conflicts |
| Visualization | None (Data only) | None (Data only) | Full HTML UI | None (Data only) |
| Merge Logic | Two-way only | Two-way only | N/A | Three-way merge |
| Best For | Code comparison, Patches | State tracking, Debugging | Code Review UIs | Version Control, Sync |
diff is the engine π. It is the reliable workhorse for comparing text. If you are building a tool that needs to know what changed in a string, start here.
deep-diff is the specialist π¬. Use it when your data is structured JSON or JavaScript objects. It saves you from writing recursive comparison logic yourself.
diff2html is the painter π¨. It takes the raw output from diff and makes it human-readable. Use it when you need to show changes to a user in a browser.
diff3 is the negotiator π€. It is essential for merging concurrent changes. If you are building a collaborative editor or version control system, this is your tool for resolving conflicts.
Final Thought: In many professional setups, you will use diff to compute changes, diff2html to show them, and deep-diff to manage application state. diff3 remains a specialized tool for advanced merge scenarios. Choose based on whether you need calculation, visualization, object tracking, or merging.
Choose deep-diff when you need to track changes in complex JavaScript objects, such as state management in React or Redux. It is ideal for debugging state transitions or implementing features like 'undo/redo' where you need to know exactly which nested properties changed. Avoid it for plain text comparison.
Choose diff when you need a robust, standard-compliant way to compare strings, lines, or characters. It is the go-to for generating patches, comparing code snippets, or building text-based diff tools. It is the most versatile for general-purpose text comparison.
Choose diff2html when you need to display differences to end-users in a web interface. It converts raw diff strings (from diff or Git) into styled HTML. Use this for code review tools, pull request views, or any UI that needs to show changes visually.
Choose diff3 when you are building version control features or collaborative editing tools that require three-way merging. It is necessary when you have two versions of a file and need to merge them based on a common ancestor. Do not use it for simple two-way comparisons.
deep-diff is a javascript/node.js module providing utility functions for determining the structural differences between objects and includes some utilities for applying differences across objects.
npm install deep-diff
Possible v1.0.0 incompatabilities:
deep-diff does a pre-order traversal of the object graph, however, when it encounters an array, the array is processed from the end towards the front, with each element recursively processed in-order during further descent.npm install deep-diff
var diff = require('deep-diff')
// or:
// const diff = require('deep-diff');
// const { diff } = require('deep-diff');
// or:
// const DeepDiff = require('deep-diff');
// const { DeepDiff } = require('deep-diff');
// es6+:
// import diff from 'deep-diff';
// import { diff } from 'deep-diff';
// es6+:
// import DeepDiff from 'deep-diff';
// import { DeepDiff } from 'deep-diff';
<script src="https://cdn.jsdelivr.net/npm/deep-diff@1/dist/deep-diff.min.js"></script>
In a browser,
deep-diffdefines a global variableDeepDiff. If there is a conflict in the global namespace you can restore the conflicting definition and assigndeep-diffto another variable like this:var deep = DeepDiff.noConflict();.
In order to describe differences, change revolves around an origin object. For consistency, the origin object is always the operand on the left-hand-side of operations. The comparand, which may contain changes, is always on the right-hand-side of operations.
var diff = require('deep-diff').diff;
var lhs = {
name: 'my object',
description: 'it\'s an object!',
details: {
it: 'has',
an: 'array',
with: ['a', 'few', 'elements']
}
};
var rhs = {
name: 'updated object',
description: 'it\'s an object!',
details: {
it: 'has',
an: 'array',
with: ['a', 'few', 'more', 'elements', { than: 'before' }]
}
};
var differences = diff(lhs, rhs);
v 0.2.0 and above The code snippet above would result in the following structure describing the differences:
[ { kind: 'E',
path: [ 'name' ],
lhs: 'my object',
rhs: 'updated object' },
{ kind: 'E',
path: [ 'details', 'with', 2 ],
lhs: 'elements',
rhs: 'more' },
{ kind: 'A',
path: [ 'details', 'with' ],
index: 3,
item: { kind: 'N', rhs: 'elements' } },
{ kind: 'A',
path: [ 'details', 'with' ],
index: 4,
item: { kind: 'N', rhs: { than: 'before' } } } ]
Differences are reported as one or more change records. Change records have the following structure:
kind - indicates the kind of change; will be one of the following:
N - indicates a newly added property/elementD - indicates a property/element was deletedE - indicates a property/element was editedA - indicates a change occurred within an arraypath - the property path (from the left-hand-side root)lhs - the value on the left-hand-side of the comparison (undefined if kind === 'N')rhs - the value on the right-hand-side of the comparison (undefined if kind === 'D')index - when kind === 'A', indicates the array index where the change occurreditem - when kind === 'A', contains a nested change record indicating the change that occurred at the array indexChange records are generated for all structural differences between origin and comparand. The methods only consider an object's own properties and array elements; those inherited from an object's prototype chain are not considered.
Changes to arrays are recorded simplistically. We care most about the shape of the structure; therefore we don't take the time to determine if an object moved from one slot in the array to another. Instead, we only record the structural
differences. If the structural differences are applied from the comparand to the origin then the two objects will compare as "deep equal" using most isEqual implementations such as found in lodash or underscore.
When two objects differ, you can observe the differences as they are calculated and selectively apply those changes to the origin object (left-hand-side).
var observableDiff = require('deep-diff').observableDiff;
var applyChange = require('deep-diff').applyChange;
var lhs = {
name: 'my object',
description: 'it\'s an object!',
details: {
it: 'has',
an: 'array',
with: ['a', 'few', 'elements']
}
};
var rhs = {
name: 'updated object',
description: 'it\'s an object!',
details: {
it: 'has',
an: 'array',
with: ['a', 'few', 'more', 'elements', { than: 'before' }]
};
observableDiff(lhs, rhs, function (d) {
// Apply all changes except to the name property...
if (d.path[d.path.length - 1] !== 'name') {
applyChange(lhs, rhs, d);
}
});
A standard import of var diff = require('deep-diff') is assumed in all of the code examples. The import results in an object having the following public properties:
diff(lhs, rhs, prefilter, acc) β calculates the differences between two objects, optionally prefiltering elements for comparison, and optionally using the specified accumulator.observableDiff(lhs, rhs, observer, prefilter) β calculates the differences between two objects and reports each to an observer function, optionally, prefiltering elements for comparison.applyDiff(target, source, filter) β applies any structural differences from a source object to a target object, optionally filtering each difference.applyChange(target, source, change) β applies a single change record to a target object. NOTE: source is unused and may be removed.revertChange(target, source, change) reverts a single change record to a target object. NOTE: source is unused and may be removed.diffThe diff function calculates the difference between two objects.
lhs - the left-hand operand; the origin object.rhs - the right-hand operand; the object being compared structurally with the origin object.prefilter - an optional function that determines whether difference analysis should continue down the object graph.acc - an optional accumulator/array (requirement is that it have a push function). Each difference is pushed to the specified accumulator.Returns either an array of changes or, if there are no changes, undefined. This was originally chosen so the result would be pass a truthy test:
var changes = diff(obja, objb);
if (changes) {
// do something with the changes.
}
The prefilter's signature should be function(path, key) and it should return a truthy value for any path-key combination that should be filtered. If filtered, the difference analysis does no further analysis of on the identified object-property path.
const diff = require('deep-diff');
const assert = require('assert');
const data = {
issue: 126,
submittedBy: 'abuzarhamza',
title: 'readme.md need some additional example prefilter',
posts: [
{
date: '2018-04-16',
text: `additional example for prefilter for deep-diff would be great.
https://stackoverflow.com/questions/38364639/pre-filter-condition-deep-diff-node-js`
}
]
};
const clone = JSON.parse(JSON.stringify(data));
clone.title = 'README.MD needs additional example illustrating how to prefilter';
clone.disposition = 'completed';
const two = diff(data, clone);
const none = diff(data, clone,
(path, key) => path.length === 0 && ~['title', 'disposition'].indexOf(key)
);
assert.equal(two.length, 2, 'should reflect two differences');
assert.ok(typeof none === 'undefined', 'should reflect no differences');
When contributing, keep in mind that it is an objective of deep-diff to have no package dependencies. This may change in the future, but for now, no-dependencies.
Please run the unit tests before submitting your PR: npm test. Hopefully your PR includes additional unit tests to illustrate your change/modification!
When you run npm test, linting will be performed and any linting errors will fail the tests... this includes code formatting.
Thanks to all those who have contributed so far!