Can I add a string property?
importance: 5
Consider the following code:
let str = "Hello";
str.test = 5;
alert(str.test);
What do you think, will it work? What will be shown?
Try running it:
let str = "Hello";
str.test = 5; // (*)
alert(str.test);
Depending on whether you have use strict or not, the result may be:
undefined(no strict mode)- An error (strict mode).
Why? Letâs replay whatâs happening at line (*):
- When a property of
stris accessed, a âwrapper objectâ is created. - In strict mode, writing into it is an error.
- Otherwise, the operation with the property is carried on, the object gets the
testproperty, but after that the âwrapper objectâ disappears, so in the last linestrhas no trace of the property.
This example clearly shows that primitives are not objects.
They canât store additional data.