4

When you create an object in JavaScript, you inherit properties from the Object prototype you can utilize.

But a string is a primitive type, thus there is no prototype. So how am I able to use methods such as substr() and repeat() on a string when there is no prototype the string can inherit those methods from?

For example, when I create a new array and assign it to a variable, I type the variable name into the console and the Array prototype is listed where I have access to methods I can use. But if I create a string and assign the string to a variable, then I type the variable into the console, there is no prototype attached to it.

Does that make sense?

Hayden
  • 779
  • 10
  • 18
  • See [Distinction between string primitives and `String` objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Distinction_between_string_primitives_and_String_objects) – str Jul 09 '18 at 08:56

1 Answers1

8

When you access a property on a primitive string, number, or other primitive, the JavaScript engine acts as though you've converted it to the equivalent object and then looks for the property. So for instance:

var str = "hi";
var upper = str.toUpperCase();

The JavaScript engine acts as though that code were written like this (for the purposes of accessing the toUpperCase property):

var str = "hi";
var upper = new String(str).toUpperCase();

Before ES5, the spec said that the JavaScript engine actually did create a string object there and then call the property. As of ES5 that changed slightly (because in strict mode it became possible for this to have a non-object value), but in essence the concept is still the same.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    To add: This is called ["boxing"](https://stackoverflow.com/questions/34067261/is-boxing-coercion-in-javascript) – Jonas Wilms Jul 09 '18 at 08:55
  • 1
    @JonasW. - It is in Java. That term doesn't appear anywhere in the ECMAScript specification and isn't commonly used in JavaScript circles in my experience. YMMV. – T.J. Crowder Jul 09 '18 at 08:57