Working With Primitive String, Number and Boolean Values

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 objects by attempting to access their 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 convert it back to a primitive value once a value is returned. The key thing to notice here is what is occurring, and that JavaScript is doing this for you behind the scenes.


Primitive Value Samples

Here's a few samples to demonstrate what I'm talking about:

String Sample: sample56.html

Number Sample: sample57.html

Boolean Sample: sample58.html

When accessing a property on a primitive number directly (not stored in a variable), you have to first evaluate the number before the value is treated as an object (e.g., (1).toString(); or 1..toString();). Why two dots? The first dot is considered a numeric decimal, not an operator for accessing object properties.


You Should Typically Use Primitive String, Number, and Boolean Values

The literal/primitive values that represent a string, number, or Boolean are faster to write and are more concise in the literal form.

You should use the literal value because of this. Additionally, the accuracy of the typeof operator depends on how you create the value (literal versus constructor invocation). If you create a string, number, or Boolean object, the typeof operator reports the type as an object. If you use literals, the typeof operator returns a string name of the actual value type (e.g., typeof 'foo' // returns 'string').

I demonstrate this fact in the following code.

Sample: sample59.html


Conclusion

If your program depends upon the typeof operator to identify string, number, or Boolean values in terms of those primitive types, you should avoid the String, Number, and Boolean constructors.

Tags:

Comments

Related Articles