0

i am a newbie to Js. I am reading an book and it says that a string object created like this var stringObj = new String(); contains string methods like .topUpperCase etc.. but i see that primitive string also contains that..

eg.

var primitive = 'Hello';
console.log(primitive.toUpperCase());
var stringObj = new String();
stringObj = "halo";
console.log(stringObj.toUpperCase());

So why is this? i mean is this because of the wrapper objects on primitives.. And is there any use of creating string Obect. thanks.

Cloudboy22
  • 1,496
  • 5
  • 21
  • 39
  • @Jonathan Thanks so well identically they are the same thing. i mean creating a primitive or an object right? – Cloudboy22 Nov 19 '15 at 04:14
  • Note: The line `stringObj = "halo";` actually discards the object by reassigning `stringObj`. So, both `console.log()` statements are using primitive values. To create a string object with a value, the value should be provided as an argument to the constructor – `var stringObj = new String("halo");`. – Jonathan Lonowski Nov 19 '15 at 04:15
  • This is known as autoboxing. Primitives get implicitly "objectified" so you can access their prototypes without adding unnecessary "noise" to your code. To autobox a number, wrap it in parentheses. Ex: `(2).toFixed` This is so there is no ambiguity with decimal syntax. – Shashank Nov 19 '15 at 04:16
  • @MarcAndreJiacarrini They aren't precisely the same. The [`typeof`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof) for the values will be different – `'string'` for the primitive vs. `'object'` for the `new String`. And, when comparing objects, two different instances are never equal, regardless of the similarity in values they may hold – `new String("") === new String("") // false` vs `"" === "" // true`. – Jonathan Lonowski Nov 19 '15 at 04:38

0 Answers0