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?

8
  • 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. Commented Nov 23, 2020 at 7:45
  • 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. Commented Nov 23, 2020 at 7: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. Commented Nov 23, 2020 at 7:55
  • 2
    @MitRao see this answer for further details on how things work behind the scenes Commented Nov 23, 2020 at 7:56
  • 1
    Thank you @NickParsons for the resource. Commented Nov 23, 2020 at 8:05

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.