Fly with code

Get wet inside ocean of code

0%

What is Primitive Wrapper ?

JavaScript data type

We all know that in JS, there are 2 kinds of data types, Primitive and object.

  • Primitive

    • string
    • number
    • null
    • undefined
    • symbol
    • boolean
  • Object

    • everything which is not Primitive type, and some constructors as below
    • String()
    • Number()
    • Boolean()
    • Array()
    • Object()
    • Function()
    • RegExp()
    • Date()
    • Error()
    • Symbol()
    • And so on…

For all constructors, it all can be used to build an object using new key words.
But, for some constructors, it looks similar with Primitive, such as

  • String()
  • Number()
  • Boolean()

But, don’t get confused, they are not Primitive type.
Let’s make an example

1
2
3
4
5
let str="apple";
console.log(typeof(str)); // string

let strObj=new String('apple');
console.log(typeof(strObj)); // object

Then , how does this happen ?

Let’s check another example

1
2
3
4
let str = 'Hello';

console.log(str.length); // 5
console.log(str.toUpperCase()); // "HELLO"

The result seems reasonable, but str should be Primitive type,
How can it use methods and property of JS ?
Only object type can use methods and property.

Primitive Wrapper

It’s related with Coercion mechanism in JS.
In above example,when we try to load str.length
It will turn str into an object using String() constructor

1
2
3
4
5
let str = new String("Hello");
str.length;

str = null; // destroy the object made by constructor
str = 'Hello';

It also happens to Number and boolean type.
And we call this Coercion.
The object created by constructor is called Primitive Wrapper

Then why we don’t use new to build object in the beginning ?
Why still use Primitive ?

Because , in terms of efficiency, Primitive type is much faster than object type.