skip to Main Content

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.

2

Answers


  1. Because length is a property of String. It needs O(1) time to get it’s value.

    Login or Signup to reply.
  2. In fact

    "string".length;
    ["hello"].length
    

    are built in property inside of string and array prototypes and this value being calculated has nothing to do with array or the string size due to this fact O(1) is correct for this.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search