Shallow Equality

Easy

Prompt

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. NaN counts as equal to NaN, and 0 and -0 count 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 }); // true
shallowEqual({ a: 1, b: 2 }, { a: 1, b: 3 }); // false
shallowEqual({ a: 1 }, { a: 1, b: 2 }); // false
shallowEqual({ a: undefined }, { b: undefined }); // false
shallowEqual({ a: NaN }, { a: NaN }); // true
shallowEqual({ a: { x: 1 } }, { a: { x: 1 } }); // false
const nested = { x: 1 };
shallowEqual({ a: nested }, { a: nested }); // true