There are three primitive wrapper types: String, Number, and Boolean.
They are reference types existing to work with primitive values.
The primitive wrapper types are automatically created behind the scenes whenever strings, numbers, or Booleans are read.
We can create a primitive string value and assign it to a variable. Then treats the variable like an object and calls its function using dot notation.
var name = "Javascript";
var firstChar = name.charAt(0);
console.log(firstChar);
The code above generates the following result.
The following code is what happens behind the scenes:
var name = "Javascript";
var temp = new String(name);
var firstChar = temp.charAt(0);
temp = null;
console.log(firstChar);
To test this out, try adding a property to a string as if it were a regular object:
var name = "Javascript";
name.last = "CSS";
console.log(name.last); // undefined
The code above generates the following result.
The code above attempts to add the property last
to the string name
.
When working with regular objects, we can add properties at any time.
With primitive wrapper types, properties disappear because the object on which the property was assigned is destroyed immediately afterward.
Here's what's actually happening in the JavaScript engine:
// what the JavaScript engine does
var name = "Javascript";
var temp = new String(name);
temp.last = "CSS";
temp = null; // temporary object destroyed
var temp = new String(name);
console.log(temp.last); // undefined
temp = null;
Although reference values are created automatically for primitive values, instanceof
these values returns false:
var name = "Javascript";
var count = 10;
var found = false;
console.log(name instanceof String); // false
console.log(count instanceof Number); // false
console.log(found instanceof Boolean); // false
The code above generates the following result.
The instanceof
operator returns false because a temporary object is
created only when a value is read.
We can create primitive wrapper types manually, but there are certain side effects:
var name = new String("Javascript");
var count = new Number(10);
var found = new Boolean(false);
console.log(typeof name); // "object"
console.log(typeof count); // "object"
console.log(typeof found); // "object"
The code above generates the following result.
We can't use String, Number, and Boolean objects as you would primitive values.
For example, the following code uses a Boolean object.
var found = new Boolean(false);
if (found) {
console.log("Found"); // this executes
} else{
console.log("Not Found"); // this executes
}
The code above generates the following result.
The Boolean object is false
, but if(found)
return true
.
It doesn't matter that the object represents false; it's an object, so it evaluates to true.
We should avoid creating primitive wrapper in the code.