The primitive types (or primitives). There are 7 of them:
- The references (or objects).
const text = 'SUN'; const new_text = text.toLowerCase();
In the previous code, the variable text is assigned a string (Primitive type) on the 1st line.
On the 2nd line, we call the method
on a primitive value, and no error is thrown.
const text = 'SUN'; let temp = new String(text); const new_text = temp.toLowerCase(); temp = null;
This String object has access to all the methods of
String.prototype, just like all String objects.
temp.toLowerCase() works fine.
Notice that the temporary String object only exists for one statement. After that, it is automatically destroyed (or dereferenced). This process of destroying the temporary object right after its first (and unique) use is called autoboxing.
Autoboxing is also the reason why we cannot add a property to a primitive type. Consider the following code:
const number = 5; number.type = 'odd'; console.log(number.type); // undefined
The previous code prints
const number = 5; let temp = new Number(5); temp.type = 'odd'; temp = null; // temp is dereferenced right away temp = new Number(5); console.log(temp.type); // undefined
When we try to access the
property of the
it no longer exists since a brand new object has been assigned to it.