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 | let str="apple"; |
Then , how does this happen ?
Let’s check another example
1 | let str = '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 | let str = new String("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.