Convert string to object in javascript

Convert string to object in javascript
0.0 0


I just stumble upon this code snippet in YDKJS this and object prototypes.

var strPrimitive = "I am a string";
typeof strPrimitive; //"String"
strPrimitive instanceof String; //false

var strObject = new String("I am a string");
typeof StrObject; //"object"
strObject instanceof String; //ture; //[object string]

Can I understand this code snippet as it just converted the string value to an object value?


All primitive values get converted (boxed) to objects so that you can use methods on them - "hello".toUppercase() for example - then get unboxed back to a primitive once the operation is complete.

This is how JS works, this is why you can apply methods to strings or numbers: everything gets treated as an object (even if it isn’t) when you want to do anything interesting to it.


thanks! your explanation plus this answer I found on stackoverflow helped me understood this fully.

for anyone that is interested.