enzyme-shallow-equal provides a shallow equality comparison utility function that compares objects by examining their top-level properties. It's adapted from React's shallowEqual implementation and is used internally by the Enzyme testing library for performance-critical scenarios where deep equality checks would be too expensive.
npm install enzyme-shallow-equalimport shallowEqual from "enzyme-shallow-equal";For CommonJS:
const shallowEqual = require("enzyme-shallow-equal");import shallowEqual from "enzyme-shallow-equal";
// Compare simple objects
const obj1 = { name: "Alice", age: 25 };
const obj2 = { name: "Alice", age: 25 };
const obj3 = { name: "Bob", age: 30 };
console.log(shallowEqual(obj1, obj2)); // true
console.log(shallowEqual(obj1, obj3)); // false
// Compare with different references but same content
const a = { user: { id: 1 } };
const b = { user: { id: 1 } };
console.log(shallowEqual(a, b)); // false - shallow comparison only
// Compare primitives
console.log(shallowEqual(42, 42)); // true
console.log(shallowEqual("hello", "hello")); // true
console.log(shallowEqual(null, null)); // truePerforms shallow equality comparison between two values using SameValue equality for primitives and property-by-property comparison for objects.
/**
* Performs shallow equality comparison between two objects
* @param {any} objA - First value to compare
* @param {any} objB - Second value to compare
* @returns {boolean} true if values are shallowly equal, false otherwise
*/
function shallowEqual(objA, objB);Comparison Algorithm:
Object.is() for initial comparison (handles NaN, +0/-0, etc.)Object.is() and hasOwnProperty()Handles Edge Cases:
Usage Examples:
import shallowEqual from "enzyme-shallow-equal";
// Primitives - uses SameValue equality
shallowEqual(42, 42); // true
shallowEqual(NaN, NaN); // true
shallowEqual("hello", "hello"); // true
shallowEqual(null, null); // true
shallowEqual(undefined, undefined); // true
// Objects - shallow property comparison
shallowEqual({}, {}); // true
shallowEqual({ a: 1 }, { a: 1 }); // true
shallowEqual({ a: 1, b: 2 }, { b: 2, a: 1 }); // true (sorted)
// Different lengths
shallowEqual({ a: 1 }, {}); // false
shallowEqual({}, { a: 1 }); // false
// Different values
shallowEqual({ a: 1 }, { a: 2 }); // false
shallowEqual({ a: 1 }, { b: 1 }); // false
// Nested objects (shallow only)
const nested1 = { user: { id: 1 } };
const nested2 = { user: { id: 1 } };
shallowEqual(nested1, nested2); // false - different object references
// Same reference
const obj = { a: 1 };
shallowEqual(obj, obj); // true
// Arrays (treated as objects)
shallowEqual([1, 2], [1, 2]); // true
shallowEqual([1, [2]], [1, [2]]); // false - nested array has different reference
// Falsy values
shallowEqual(false, 0); // false
shallowEqual(null, undefined); // false
shallowEqual("", 0); // false
// Mixed types
shallowEqual(1, "1"); // false
shallowEqual({}, []); // false