Duration: 2-3 minutes
However, JS provides a large tools for manipulating booleans, numbers and especially strings. Let’s see an example:
var s1 = "hello world"; var s2 = s1.substring(6); console.log(s2); // "world"
“There is no way string is a primitive!” would say almost every developer with experience in other languages. If I would tell you that this example works, you would starting to thing that I contradict myself. And you have every right to do so. Seeing this code makes you convinced that string cannot be a primitive data type, it has a function .substring. Actually it has many others, so how is possible that string is still a primitive? The short answer is: object wrappers for primitives.
What are object wrappers?
Let’s see what really happens in the example above! Any time a string value is accessed in read mode, the following steps occur:
- create an instance of type String()
- call the specific method on instance
- destroy the instance
The code is actually equivalent to:
var s1 = "hello world"; var wrapper = new String(s1); // this happens behind the scenes var s2 = wrapper.substring(6); delete wrapper; // this happens behind the scenes console.log(s2);
Also, the lifecycle of an automatically generated wrapper is very short. The object is used for one line of code and then is deleted, so you can use them without worrying about the memory.
Although is possible to use the wrappers explicitly, it’s better to avoid them because they could generate confusion. An object wrapper is still an object and cannot be used as the native data types in every condition.
Here are the things you need to remember from this short article:
- numbers, booleans and strings are primitive data types
- JS provide three special objects, named object wrapper – Number(), Boolean() and String() – used to perform the work behind the scenes.
- the object wrappers are automatically created when an operation is explicitly used in code and automatically destroyed after that.
- it’s good to avoid using the wrappers explicitly in code (but is very important to understand how they work)
Thank you for your time!
Please subscribe for more weekly web wisdom!