deep-diff vs diff vs diff2html vs diff3
Advanced Diffing and Merge Strategies in JavaScript
deep-diffdiffdiff2htmldiff3Similar Packages:

Advanced Diffing and Merge Strategies in JavaScript

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.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
deep-diff00-08 years agoMIT
diff09,121616 kB145 days agoBSD-3-Clause
diff2html03,3502.02 MB333 months agoMIT
diff301411.9 kB2-MIT

Advanced Diffing and Merge Strategies in JavaScript

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.

🧠 Core Logic: Text vs. Objects vs. Merges

The fundamental difference lies in what data they compare and how they handle the result.

diff is the standard for text comparison.

  • It compares strings character-by-character, line-by-line, or word-by-word.
  • It outputs a structured list of changes or a unified patch.
// 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.

  • It recursively walks through object trees to find property-level changes.
  • It returns an array of change objects describing edits, deletes, or adds.
// 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.

  • It takes raw diff strings (usually from diff or Git) and converts them to HTML.
  • It is purely a rendering layer.
// 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.

  • It takes three inputs: original, mine, and theirs.
  • It attempts to merge changes from both sides against the base.
// 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);

πŸ–₯️ Visualization: Raw Data vs. User Interface

Displaying changes to a user requires more than just computing them. You need formatting.

diff returns data structures.

  • You get arrays of objects or patch strings.
  • You must build your own UI to show green/red highlights.
// 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.

  • You get metadata like kind: 'E' (edited) or kind: 'D' (deleted).
  • You must map these to UI elements yourself.
// 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.

  • It includes CSS classes for additions and deletions.
  • It supports file lists and side-by-side views out of the box.
// 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.

  • It outputs the merged content or conflict markers.
  • Visualization is up to you, often showing conflict regions.
// 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);
}

πŸ”„ Handling Conflicts and Edge Cases

Real-world data is messy. Libraries handle errors and conflicts differently.

diff handles whitespace and newlines flexibly.

  • You can ignore case or whitespace during comparison.
  • It does not handle merge conflicts, only differences.
// 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.

  • It can detect changes inside arrays (moves, edits).
  • It has options to filter out specific properties from comparison.
// 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.

  • If the input diff string is malformed, output may break.
  • It does not resolve conflicts, only displays what it is given.
// diff2html: Error handling
try {
  const html = Diff2Html.html(invalidDiffString);
} catch (e) {
  console.error('Invalid diff format');
}

diff3 is designed specifically for conflicts.

  • It identifies overlapping changes that cannot be auto-merged.
  • It returns structured conflict data for manual resolution.
// diff3: Structured conflicts
import { diff3 } from 'diff3';

const result = diff3(mine, original, theirs);
// result.ok contains merged lines
// result.conflict contains conflicting sections

🌱 Similarities: Shared Ground

While they serve different purposes, these libraries share some common goals and patterns.

1. πŸ“ Text and Data Integrity

  • All aim to preserve data integrity during comparison or merge.
  • They avoid mutating original inputs unless explicitly told to apply changes.
// 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

2. πŸ› οΈ Extensibility

  • All support configuration options to tweak behavior.
  • You can customize how differences are detected or displayed.
// 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' });

3. βœ… Standard Outputs

  • 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' }

πŸ“Š Summary: Key Differences

Featurediffdeep-diffdiff2htmldiff3
Primary InputStrings / TextJavaScript ObjectsDiff StringsThree Text Strings
OutputChange Array / PatchChange ArrayHTML StringMerged Text / Conflicts
VisualizationNone (Data only)None (Data only)Full HTML UINone (Data only)
Merge LogicTwo-way onlyTwo-way onlyN/AThree-way merge
Best ForCode comparison, PatchesState tracking, DebuggingCode Review UIsVersion Control, Sync

πŸ’‘ The Big Picture

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.

How to Choose: deep-diff vs diff vs diff2html vs diff3

  • deep-diff:

    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.

  • diff:

    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.

  • diff2html:

    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.

  • diff3:

    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.

README for deep-diff

deep-diff

CircleCI

NPM

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.

Install

npm install deep-diff

Possible v1.0.0 incompatabilities:

  • elements in arrays are now processed in reverse order, which fixes a few nagging bugs but may break some users
    • If your code relied on the order in which the differences were reported then your code will break. If you consider an object graph to be a big tree, then 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.

Features

  • Get the structural differences between two objects.
  • Observe the structural differences between two objects.
  • When structural differences represent change, apply change from one object to another.
  • When structural differences represent change, selectively apply change from one object to another.

Installation

npm install deep-diff

Importing

nodejs

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';

browser

<script src="https://cdn.jsdelivr.net/npm/deep-diff@1/dist/deep-diff.min.js"></script>

In a browser, deep-diff defines a global variable DeepDiff. If there is a conflict in the global namespace you can restore the conflicting definition and assign deep-diff to another variable like this: var deep = DeepDiff.noConflict();.

Simple Examples

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

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/element
    • D - indicates a property/element was deleted
    • E - indicates a property/element was edited
    • A - indicates a change occurred within an array
  • path - 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 occurred
  • item - when kind === 'A', contains a nested change record indicating the change that occurred at the array index

Change 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.

Changes

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);
  }
});

API Documentation

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.

diff

The diff function calculates the difference between two objects.

Arguments

  • 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.
}

Pre-filtering Object Properties

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');

Contributing

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!