Primitive and Compound data type in JavaScript

In JavaScript, data types are separated into two part, “Primitive data” and “Compound data”.

Primitive data

In ES5, there are five primitive data types:

  • number
  • boolean
  • string
  • null
  • undefined

Comopund data

  • object(array is also object)

But sometime you may feel weird about the data type, because you can hear people talk about “JavaScript has both primitive and object Strings.”. Shouldn’t String be the primitive data? Why people say string is also object?

Before answer the question we should talk about method first.

Method

“Functions define the behavior of an object. When they are part of an object, we call them methods. To call a method on an object, you access the method as though it is a property (it is!), and call it by appending parentheses.”

From the text above we can know, the receiver for a method should be ‘object’. For example we can use array as an receiver and call a concat() method to merge two arrays.

var array = [1, 2, 3];
array.concat([4, 5, 6]); // [1, 2, 3, 4, 5, 6]

If we can understand all the receiver for a method should be an object, then we can talk about why we may say JavaScript has both primitive and object Strings.

When you apply a method to a primitive, JavaScript automatically converts it to an object.

What we can do to test is create a string, check it type, convert it to object, and make it a receiver then invoke the method.

As we can see after we converted the primitive to an object, it should work when we append the toUpperCase() and call it.

Apart from null and undefined, each time you attempt to access a property on a primitive type (string, number and boolean), JavaScript will implicitly create a temporary wrapper object. But JavaScript engine doesn’t keep this wrapper object around. As soon as the work of the method (or other property) is done, it is disposed of.

So we can know why people say “JavaScript has both primitive and object Strings.”.

And there is one more thing need to note is, “the string can’t be a primitive and an object at the same time”, only one data type will exist on it at one time.

Reference

What is a wrapper object in Javascript? Provide an example of how a wrapper object would work.
JavaScript’s Primitive Wrapper Objects