Javascript - Create primitive wrapper objects

Introduction

You can create the primitive wrapper objects explicitly using the Boolean, Number, and String constructors.

Calling typeof on an instance of a primitive wrapper type returns "object", and all primitive wrapper objects convert to the Boolean value true.

The Object constructor acts as a factory method and returns an instance of a primitive wrapper based on the type of value passed in. For example:

var obj = new Object("some text");
console.log(obj instanceof String);   //true

When a string is passed into the Object constructor, an instance of String is created.

A number argument results in an instance of Number, while a Boolean argument returns an instance of Boolean.

Calling a primitive wrapper constructor using new is not the same as calling the casting function of the same name. For example:

var value = "25";
var number = Number(value);   //casting function
console.log(typeof number);   //"number"

var obj = new Number(value);  //constructor
console.log(typeof obj);      //"object"

In this example, the variable number is filled with a primitive number value of 25 while the variable obj is filled with an instance of Number.

Related Topic