Shallow Equality
EasyPrompt
Write a JavaScript function shallowEqual(obj1, obj2) that checks if two given objects are shallowly equal.
Two objects are shallowly equal when:
- They have the same keys.
- The value under each key is the same value in both objects.
NaNcounts as equal toNaN, and0and-0count as different.
Nested objects and arrays are compared by reference, not by content. You can assume both arguments are plain objects.
Example
shallowEqual({ a: 1, b: 2 }, { a: 1, b: 2 }); // trueshallowEqual({ a: 1, b: 2 }, { a: 1, b: 3 }); // falseshallowEqual({ a: 1 }, { a: 1, b: 2 }); // falseshallowEqual({ a: undefined }, { b: undefined }); // falseshallowEqual({ a: NaN }, { a: NaN }); // trueshallowEqual({ a: { x: 1 } }, { a: { x: 1 } }); // falseconst nested = { x: 1 };shallowEqual({ a: nested }, { a: nested }); // true