Strings are primitives, meaning they don’t actually have methods or properties associated with them. According to MDN
In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup on the wrapper object instead.
So if I’m understanding correctly, whenever you read the length property of a string primitive, JS under the hood creates a new instance of the String object from that passed in string. In other words, when I write this code
console.log('hello world'.length);
javascript does this
const stringObject = new String('hello world');
console.log(stringObject.length);
But since a string primitive doesn’t have a length property, doesn’t that mean that the length has to be calculated directly whenever you’re instantiating the string object? In other words, I would think it has to get recalculated every time you read the length property. I’d also guess that calculating the length property for that object would take linear time.
But the few sources I found say that reading the length property has O(1) time complexity, so what am I misunderstanding? Unfortunately, I’m not smart enough to interpret the source code, but I’m pretty curious about how it all works.