3

I have this question in mind since I started learning JavaScript last month.

What I have tried?: I researched for it online almost on all good sites but didn't get satisfactory answer in laymans language.

Question: When I create variable let suppose

let name = "mit"
name.toUpperCase()

I am using dot notation to access the method here and I know we use it for something in object. I was confused if the browser creates different object for name variable (which is of string data type here) or what?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Mit Rao
  • 33
  • 7
  • 3
    When calling prototype methods of primitives, the primitives are coerced to an object corresponding to their respective type; in this case a `String`. In Java this would be called _boxing_. – Sebastian Simon Nov 23 '20 at 07:45
  • [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+how+do+method+calls+on+primitives+work) of [Why does a primitive variable act like an Object?](https://stackoverflow.com/q/35680344/4642212). – Sebastian Simon Nov 23 '20 at 07:48
  • Gotcha, so there is an Object for string already created and chrome just kinda resolves the primitives to its respective object. If i am getting it right? – Mit Rao Nov 23 '20 at 07:49
  • 1
    Not really “Chrome”; the behavior is specified in ECMAScript and implemented in the JS engine (V8, in this case). It’s the same kind of behavior for `"4" - 3` resulting in `1`: the `"4"` is coerced to a number. – Sebastian Simon Nov 23 '20 at 07:51
  • 1
    @MitRao When you do `name.toUpperCase()` it *acts as if* you've done `(new String(name)).toUpperCase()`. So, it's *as if* the string primitive is converted to an object for this one operation, the method is called and then the object is removed. However, the exact implementation might be different - an engine might very well optimise the operation to avoid creating an extra object since if you do that a lot in a loop, you'd create *many* temporary objects that will need to be garbage collected. – VLAZ Nov 23 '20 at 07:55
  • 2
    @MitRao see [this answer](https://stackoverflow.com/a/9110389/5648954) for further details on how things work behind the scenes – Nick Parsons Nov 23 '20 at 07:56
  • @VLAZ Thanks man, Now Its Clear! We using constructor to construct an object out of String variable but it is going to be a temporary one so that we can use methods like toUpperCase() on it. Not that advance in JS as i am a beginner but made things bit clear. – Mit Rao Nov 23 '20 at 07:59
  • 1
    Thank you @NickParsons for the resource. – Mit Rao Nov 23 '20 at 08:05

0 Answers0