Coersion (CR22)
1: const obj1 = { valueOf() { return 5; } };
2: console.log(obj1 < 10); // Output: true (valueOf() returns 5)
3:
4: const obj2 = { toString() { return "10"; } };
5: console.log(obj2 > 5); // Output: true ("10" coerced to 10, and valueOf() will be executed first, but returns object, so toString() is called.)
6:
7:
8: const obj3 = {
9: valueOf() { return {}; }, // returns an object, not a primitive
10: toString() { return "20"; }
11: };
12: console.log(obj3 > 10); // Output: true (toString() is called)
Object Comparisons (valueOf/toString): If an object is involved, the Abstract Relational Comparison Algorithm attempts to convert it to a primitive value using either its valueOf() or toString() method or [Symbol.toPrimitive] if defined. true true true
Coersion context:
ES6 context:
- (2024) Notes about JS Closures. #ES6
- (2024) Notes about Javascript asynchronous programming. #ES6
- (2022) Modern Javascript books #ES6 #Doc
- (2021) JS learning start point #ES6
- (2021) Maximilian Schwarzmüller Javascript lecture #ES6
- (2021) Javascript interview question from Happy Rawat #ES6
- (2021) Javascript tests #ES6
- (2016) New unique features of Javascript (updated). #ES6
Comments (
)

Link to this page:
http://www.vb-net.com/JavascriptES6/CR22.htm
|