Coersion (CR12)
1: const obj = {
2: valueOf() {
3: return 10;
4: },
5: toString() {
6: return "20";
7: }
8: };
9:
10: console.log(Number(obj)); // Output: 10 (valueOf() is called by Number())
11: console.log(5 + obj); // Output: 15 (valueOf() is called, as hint is "number")
12: console.log("Value: " + obj); // Output: "Value: 20" (toString() called due to string concatenation)
13:
14:
ToPrimitive Coercion: Object to Number (using valueOf and toString): 10 15 Value: 10
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/CR12.htm
|