0

In JavaScript everything is object like String literal, numbers, Object... And properties can be added to objects dynamically also, but I am adding property to object which refer to string then it seems it is not working Following is JS code which I am running

var aVar = "some string";
console.log(aVar);
aVar.name = 'raj';
console.log(aVar.name);

Output...

hi some string undefined

Shailesh
  • 405
  • 1
  • 5
  • 18
  • @ShanerM13 you're thinking of HTML, this question has nothing to do with HTML – Jamiec Feb 01 '21 at 17:14
  • 1
    You've declared a `string` primative, which is not implemented as an object, like `var aVar = new String("some string");` would do. – Scott Marcus Feb 01 '21 at 17:15
  • 1
    This has to do with boxing - i didn't read the dupe links, but judging from the titles, they are about something else. – ASDFGerte Feb 01 '21 at 17:15
  • 2
    Long story short (and accordingly inaccurate, please research), if the javascript engine encounters a property access on a primitive, boxing occurs, aka the property access is performed on a temporary boxed object, in this case something similar to `new String('some string')`. This temporary object is lost after the assignment, so you cannot recover the set property. – ASDFGerte Feb 01 '21 at 17:20
  • Thank you @ScottMarcus your answer is correct, I could verify it. Thanks again for clarification – Shailesh Feb 01 '21 at 17:28

0 Answers0