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:

Live Code

<!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( ...

Get JavaScript Enlightenment now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.