If you can, bring up your browser's console and try creating a simple variable and give it a string value. How did you do it? Did you write something like
var myString = "That's my string";
or did you choose to go with
var myString = new String("That's my string");
let myString = "That's my string"; let yourString = new String("That's your string"); console.log(typeof myString); // outputs "string" console.log(typeof yourString); // outputs "object" //MDN says primitives and objects can SOMETIMES be interchangeably used let yourBigString = yourString.toUpperCase(); console.log(yourBigString); // outputs "THAT'S YOUR STRING" let myBigString = myString.toUpperCase(); console.log(myBigString); // outputs "THAT'S MY STRING"
You may have two question now:
- If the JS engine does this autoboxing internally everytime we use a primitive, isn't this more expensive than simply using String Objects?
To answer the first question, let me throw another example which is an extension to the very first example. The example shows a case where someone would try assigning a property to some primitive expecting it to be retrievable. If you assign some property to a string primitive with an intention of getting the value back at some point, you will only be returned 'undefined' because the temporary String Object was discarded then and there. Similarly such assumptions can misfire when using eval (which indeed should not be used). These examples may not be very relatable but I guess they are enough to warn us from assumptions.
To conclude I'd just highlight that MDN says "String primitives and string objects can be used interchangeably in most situations". We probably know why they say "most situations" and not "always".