Chapter 13. Working with Primitive String, Number, and Boolean Values
Primitive/Literal Values Are Converted to Objects When Properties Are Accessed
Do not be mystified by the fact that string, number, and boolean
literals can be treated like an object with properties [e.g., true.toString()]. When these primitive values
are treated like an object by attempting to access properties, JavaScript
will create a wrapper object from the primitive’s associated constructor,
so that the properties and methods of the wrapper object can be accessed.
Once the properties have been accessed, the wrapper object is discarded.
This conversion allows us to write code that would make it appear as if a
primitive value was, in fact, an object. Truth be told, when it is treated
like an object in code, JavaScript will convert it to an object so
property access will work, and then back to a primitive value once a value
is returned. The key thing to grok here is what is occurring, and that
JavaScript is doing this for you behind the scenes.
String:
<!DOCTYPE html><html lang="en"><body><script> // string object treated like an object var stringObject = new String('foo'); console.log(stringObject.length); // logs 3 console.log(stringObject['length']); // logs 3 // string literal/primitive converted to an object when treated as an object var stringLiteral = 'foo'; console.log(stringLiteral.length); // logs 3 console.log(stringLiteral['length']); // logs 3 console.log('bar'.length); // logs 3 console.log( ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access