For example:
var a = "hello world";
var b = 3.14159;
a.length; // 11
a.toUpperCase(); // "HELLO WORLD"
b.toFixed(4); // "3.1416"
The “how” behind being able to call a.toUpperCase()
is more complicated than just that method existing on the value.
Briefly, there is a String (capital S) object wrapper form, typically called a “native,” that pairs with the primitive string type; it’s this object wrapper that defines the toUpperCase()
method on its prototype.
When you use a primitive value like "hello world" as an object by referencing a property or method (e.g., a.toUpperCase()
in the previous snippet), JS automatically “boxes” the value to its object wrapper counterpart (hidden under the covers).
A string value can be wrapped by a String object, a number can be wrapped by a Number object, and a boolean can be wrapped by a Boolean object. For the most part, you don’t need to worry about or directly use these object wrapper forms of the values—prefer the
primitive value forms in practically all cases and JavaScript will take care of the rest for you.
From You Don't Know Js: Up & Going