1

I know that you can perform String properties on string primitives as JavaScript temporarily treats string primitives as instances of String:

n = "string";
n2 = n.toUpperCase();

console.log(n2);

Behind the scenes, is JavaScript treating the primitive by doing something like this:

new String(stringPrimitive)? E.g.

n = "string";
n2 = new String(n).toUpperCase();

console.log(n2);

2 Answers2

1

You can instance the built-in String object and then apply any string method. For example:

let str = new String('stringPrimitive')
console.log(str)
console.log(str.split(''))
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35
  • Thanks @sonEtLumiere I've edited my question. I was hoping to know what JS was doing behind the scenes when it returns properties/methods on a string **primitive**. – tonitone117 Jul 27 '20 at 00:08
1

The term for this behavior is boxing.

In theory, it does exactly that - create a new string object, and use that. However it should be noted, that in reality, engines internally can take a lot of shortcuts, and make many optimizations.

When reading the spec for 6.2.4.8 GetValue, you can see this boxing in the steps (use ToObject(base), if it's a primitive), as well as an explicit note towards the permitted optimization:

The object that may be created in step 5.a.ii is not accessible outside of the above abstract operation and the ordinary object [[Get]] internal method. An implementation might choose to avoid the actual creation of the object.

Therefore, to know what really happens, you'd probably have to read the code of the related engine. For normal javascript programmers, knowing the engine internals is imho not necessary, but if you want to anyways, e.g. V8 is open source (written in c++).

ASDFGerte
  • 4,695
  • 6
  • 16
  • 33
  • Thanks @ASDFGerte I'll just leave it and trust the engine internals! – tonitone117 Jul 27 '20 at 00:19
  • The question here is about property access, where it's not all too relevant for the programmer. However, one place where you need to care about boxing, is passing a primitive as `this` to a function via `call`, `bind`, or `apply`, in non-strict mode (kind of weird scenario, using non-strict is a big no-no anyways). [This answer](https://stackoverflow.com/a/17217024/6692606) gives some additional information about the whole topic. It's a few years old, but most of it is probably still relevant. – ASDFGerte Jul 27 '20 at 00:33