Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a string is not an object, how am I able to use built-in methods? [duplicate]

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?

like image 897
Hayden Avatar asked Jan 28 '23 19:01

Hayden


1 Answers

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.

like image 166
T.J. Crowder Avatar answered Jan 30 '23 08:01

T.J. Crowder