Understanding strings as objects

Understanding strings as objects


I’m trying to better understand the internal structure of a string.

In the following code, I initialize a string. To see what’s inside, I use Object.getOwnPropertyNames() and Object.values().

var str = 'hi';

My output is:

[ '0', '1', 'length' ]
[ 'h', 'i' ]

Why doesn’t Object.values() show a value for the property length?

Now I want to build an object of type string “from scratch,” but I can’t figure out how. I figure I first have to create an object that might “look” like a string object, then explicitly convert it to a string. Something like:

var hey =  {
    0 : 'h',
    1: 'e',
    2: 'y',
    length: 4
// to get it to type string
hey = String(hey);

But that doesn’t work. Neither does the other 100 things I’ve tried. I’m basically blindly throwing darts at this point, so hoping someone can explain this.



see the section titled:
Distinction between string primitives and String objects

explains it better than I can!


Strings aren’t objects, they’re primitive values. They don’t have a representation like you think: they aren’t like an array of characters, they’re a single immutable value.

var myStrObj = new String("hello");

You can’t build one from scratch because of that.

What JavaScript does is when you use a method on a string, it does a thing called [if you want to use Java terminology] autoboxing. It wraps the string in the String object wrapper (that bit you have correct), and that object wrapper allows you to use methods and access properties. As soon as that method has been executed or property accessed, JavaScript unboxes the string back to a primitive, so the object only exists for a split second. There are ways to keep that object alive, but you can’t create a string the way you’re trying to.

What’s happening when you inspect the string using the object inspection methods is that it’s boxing the string, executing the methods, then unboxing the string. This is implicit behaviour, you can’t really start from the object behaviour and create a string from it


@DanCouper great explanation. thanks.