BRUCE_FEBRUCE_FE

EN/CH Mode

BRUCE_FE JS Interview Notes - Strict vs Loose Comparison and Object.is() Analysis

In-depth analysis of JavaScript's ==, ===, Object.is() comparison methods, practical applications, and differences between shallow and deep comparison.

影片縮圖

Lazy to read articles? Then watch videos!

== vs ===

  • == performs type coercion, suitable for loose comparison.
  • === returns true only when both type and value match, recommended as the default approach.
0 == '0'         // true
false == 0       // true
null == undefined // true
[] == false      // true

0 === '0'        // false
false === 0      // false
null === undefined // false

Object.is Precise Comparison

Object.is() is almost equivalent to ===, but correctly handles edge cases like NaN and +0/-0.

  • Object.is(NaN, NaN) // true
  • Object.is(+0, -0) // false
  • Suitable for React.memo, useMemo, and when frameworks need precise change detection
Object.is(NaN, NaN);    // true
Object.is(+0, -0);      // false
Object.is(42, 42);      // true

const obj1 = { a: 1 };
const obj2 = { a: 1 };
Object.is(obj1, obj2);  // false(不同參考)

Object.is is Shallow Comparison

Object.is() only compares first-level references or values, without deep recursion into object contents.

const a = { x: 1 };
const b = { x: 1 };

Object.is(a, b); // false
Object.is(a, a); // true

For deep comparison, use lodash's isEqual:

import isEqual from 'lodash.isequal';
isEqual(a, b); // true

🔥 Common Interview Questions

(1) What's the difference between == and ===? Please provide examples.

Answer: == performs type coercion, while === does not.

0 == ''            // true
false == 'false'   // false
'123' === 123      // false

(2) What's the result of NaN === NaN?

Answer: NaN is defined in IEEE 754 as not equal to any value (including itself), so NaN === NaN is false. However, for precise comparison, you can use Object.is(NaN, NaN), which will return true.

(3) When should we use Object.is?

Answer: For example, React internally uses Object.is() to determine if state or props have changed and if re-rendering is needed. This prevents errors in edge cases like NaN and +0/-0, ensuring precision and performance.

useEffect(() => {
  // some code...
}, [.....]) // <--- Dependencies compared using Object.is internally

// Simple overview of internal implementation
// If new value equals old value via Object.is, don't update
if (!Object.is(prevValue, nextValue)) {
  updateState(nextValue);
}