Part 06 · Values · 6.1.02

Primitive, object, coercion và equality algorithms

JavaScript có dynamic values nhưng semantics cụ thể; production bug thường đến từ implicit conversion, reference aliasing và numeric limits.

Boundary rule: validate/normalize input tại boundary, dùng equality algorithm có chủ đích và đừng suy luận value semantics từ console display.

1. Primitive và object

Undefined, Null, Boolean, String, Symbol, Number và BigInt là primitive; Object giữ properties/internal slots. typeof null là legacy result; arrays và functions vẫn là objects. Primitive immutable, còn object variable giữ reference nên assignment/copy có thể alias cùng state.

2. ToPrimitive và implicit coercion

Operator có thể gọi ToPrimitive rồi ToString/ToNumber theo hint. + vừa numeric addition vừa string concatenation; boolean falsy set nhỏ, trong khi "0", []{} là truthy. Convert explicit tại boundary để code review nhìn thấy intent.

"5" + 1   // "51"
"5" - 1   // 4
Boolean("0") // true
Number.isNaN(value) // không ép kiểu ngầm

3. Equality algorithms

AlgorithmKey behaviorTypical use
===Không coerce; NaN khác chính nó; +0/-0 bằngDefault strict comparison
Object.isNaN bằng chính nó; phân biệt +0/-0Exact identity edge cases
SameValueZeroNaN bằng; +0/-0 bằngSet/Map/includes semantics
==Abstract equality có conversion rules phức tạpChỉ dùng khi rule được intentional/documented

4. Number, BigInt và precision

Number là IEEE-754 binary64; integer an toàn tới 2^53 - 1 và decimal rounding cần domain policy. BigInt không trộn trực tiếp với Number trong phép toán và không tự giải quyết decimal money; dùng integer minor units hoặc decimal library có quy tắc rounding/serialization rõ.

Interview answer: “I name the equality/coercion rule I need, convert external data explicitly, and treat numeric precision as a domain invariant rather than a JavaScript accident.”
Tài liệu: MDN Data Types · ECMAScript Type Conversion · MDN Object.is