-
Notifications
You must be signed in to change notification settings - Fork 0
/
primitives.js
89 lines (66 loc) · 2.52 KB
/
primitives.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
valueOf() method returns the primitive value of the specified object.
Symbol.toPrimitive is a symbol that specifies a function valued property that is called to convert an object to a corresponding primitive value.
The function is called with a string argument hint, which specifies the preferred type of the result primitive value. The hint argument can be one of "number", "string", and "default"
Let's break it down case by case
Case 1
For obj1, we have defined valueOf and toString. While adding we use valueOf to get the primitive value and add 1 to it thus logging 2. parseInt will convert the input using toString method that gives '100' converting it to number gives 100
Case 2
For obj2, we have defined Symbol.toPrimitive, valueOf and toString methods. In this example, both operations viz. addition and parseInt make use of toPrimitive method i.e. using 200
Case 3
For obj3, we have only defined toString. All three operations here, Unary operator, Addition and parseInt will use toString method i.e. "100"
Case 4
For obj4, we have only defined valueOf. So addition uses this value 1. But in parseInt, since we have not defined toString method, the string value of obj4 will be [object Object] hence parseInt returns NaN
Case 5
For obj5, we have only defined Symbol.toPrimitive with custom handling for hints. For Addition(+), the hint is implicitly number, which means toPrimitive returns 1 and 1+1=2. parseInt implicitly uses toPrimitive method with the hint passed as string and thus it uses "100" returning 100
*/
// case 1
const obj1 = {
valueOf() {
return 1
},
toString() {
return '100'
}
}
console.log(obj1 + 1) // 1 + 1 = 2
console.log(parseInt(obj1)) // parseInt("100") = 100
// case 2
const obj2 = {
[Symbol.toPrimitive]() {
return 200
},
valueOf() {
return 1
},
toString() {
return '100'
}
}
console.log(obj2 + 1) // 200 + 1 = 201
console.log(parseInt(obj2)) // parseInt(200) = 200
// case 3
const obj3 = {
toString() {
return '100'
}
}
console.log(+obj3) // +"100" = 100
console.log(obj3 + 1) // "100" + "1" = "1001"
console.log(parseInt(obj3)) // parseInt("100") = 100
// case 4
const obj4 = {
valueOf() {
return 1
}
}
console.log(obj4 + 1) // 1 + 1 = 2
console.log(parseInt(obj4)) // parseInt("[object Object]") = NaN
// case 5
const obj5 = {
[Symbol.toPrimitive](hint) {
return hint === 'string' ? '100' : 1
},
}
console.log(obj5 + 1) // 1 + 1 = 2
console.log(parseInt(obj5)) // parseInt('100') = 100