0 added
0 removed
Original
2026-01-01
Modified
2026-02-21
1
<p>Methods are functions stored in object properties. If this is the case, then why does this code works:</p>
1
<p>Methods are functions stored in object properties. If this is the case, then why does this code works:</p>
2
<p>From this code, one might draw the erroneous conclusion that a string is also an object, but that's not the case. In JavaScript, strings, logical values, null, and numbers are implemented as primitive values with no methods. On the other hand, each such type has its own constructor that boxes the primitive type with a wrapper object:</p>
2
<p>From this code, one might draw the erroneous conclusion that a string is also an object, but that's not the case. In JavaScript, strings, logical values, null, and numbers are implemented as primitive values with no methods. On the other hand, each such type has its own constructor that boxes the primitive type with a wrapper object:</p>
3
<p>JavaScript automatically boxes primitives into relevant objects when it encounters method calls on them (and then automatically unboxes them). In other words, all the methods we call on strings the String constructor prototype contains. The same goes for all other types:</p>
3
<p>JavaScript automatically boxes primitives into relevant objects when it encounters method calls on them (and then automatically unboxes them). In other words, all the methods we call on strings the String constructor prototype contains. The same goes for all other types:</p>
4
<p>What's interesting is how the unboxing happens. To do this, JavaScript automatically calls valueOf():</p>
4
<p>What's interesting is how the unboxing happens. To do this, JavaScript automatically calls valueOf():</p>
5
<p>Unlike boxing, unboxing is performed for absolutely all objects. This allows you to define valueOf() yourself:</p>
5
<p>Unlike boxing, unboxing is performed for absolutely all objects. This allows you to define valueOf() yourself:</p>
6
<p>Various libraries like<a>moment.js</a>use this to convert the date (as an object) into a value (timestamp):</p>
6
<p>Various libraries like<a>moment.js</a>use this to convert the date (as an object) into a value (timestamp):</p>
7
<p>Although it works, many developers discourage this approach. It looks more like a hack than good code.</p>
7
<p>Although it works, many developers discourage this approach. It looks more like a hack than good code.</p>