Javascript - Primitive Wrapper Types

Introduction

Three reference types are wrapper of primitive values:

  • Boolean type,
  • Number type, and
  • String type.

These types can act like the other reference types and they have a special behavior related to their primitive-type equivalents.

Every time a primitive value is read, an object of the corresponding primitive wrapper type is created behind the scenes.

In this way it allows access to its methods for manipulating the data. Consider the following example:

var s1 = "some text";
var s2 = s1.substring(2);

In this code, s1 is a variable containing a string, which is a primitive value.

On the next line, the substring() method is called on s1 and stored in s2.

Primitive values aren't objects, so they shouldn't have methods.

When s1 is accessed in the second line, it is being accessed in read mode, which is to say that its value is being read from memory.

Any time a string value is accessed in read mode, the following three steps occur:

  • Create an instance of the String type.
  • Call the specified method on the instance.
  • Destroy the instance.

You can think of these three steps as:

var s1 = new String("some text");
var s2 = s1.substring(2);
s1 = null;

This behavior allows the primitive string value to act like an object.

The same three steps are repeated for Boolean and numeric values.

The difference between reference types and primitive wrapper types is the lifetime of the object.

When you instantiate a reference type using the new operator, it stays in memory until it goes out of scope.

The automatically created primitive wrapper objects exist for only one line of code before they are destroyed.

This means that properties and methods cannot be added at runtime. For example:

var s1 = "some text";
s1.color = "red";
console.log(s1.color);   //undefined

Here, the second line attempts to add a color property to the string s1.

When s1 is accessed on the third line, the color property is gone.

Because the String object that was created in the second line is destroyed by the time the third line is executed.

The third line creates its own String object, which doesn't have the color property.

Related Topics