Primitive Data Type Wrapper Objects

When we discussed strings earlier in this chapter, I pointed out a strange feature of that data type: to operate on strings, you use object notation. For example, a typical operation involving strings might look like the following:

var s = "These are the times that try people's souls.";
var last_word = s.substring(s.lastIndexOf(" ")+1, s.length);

If you didn’t know better, it would appear that s was an object and that you were invoking methods and reading property values of that object.

What’s going on? Are strings objects, or are they primitive data types? The typeof operator (see Chapter 5) assures us that strings have the data type “string”, which is distinct from the data type “object”. Why, then, are strings manipulated using object notation?

The truth is that a corresponding object class is defined for each of the three key primitive data types. That is, besides supporting the number, string, and boolean data types, JavaScript also supports Number, String, and Boolean classes. These classes are wrappers around the primitive data types. A wrapper contains the same primitive data value, but it also defines properties and methods that can be used to manipulate that data.

JavaScript can flexibly convert values from one type to another. When we use a string in an object context -- i.e., when we try to access a property or method of the string -- JavaScript internally creates a String wrapper object for the string value. This String object ...

Get JavaScript: The Definitive Guide, Fourth Edition 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.