JS: Introduction to Object Oriented Programming (OOP)
Theory: Boxing and unboxing (wrapper objects)
Methods are functions stored in object properties. If this is the case, then why does this code works:
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:
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:
What's interesting is how the unboxing happens. To do this, JavaScript automatically calls valueOf():
Unlike boxing, unboxing is performed for absolutely all objects. This allows you to define valueOf() yourself:
Various libraries like moment.js use this to convert the date (as an object) into a value (timestamp):
Although it works, many developers discourage this approach. It looks more like a hack than good code.

