I was trying to create string data-types variables with values in 2 ways.
But to me it seems that these both are different in representation on console.log. Can someone tell me if 2nd way doesn't return string or is it someway different?
var str1 = "abc";
var str2 = new String("def");
console.log(str1);
console.log(str2);
Expected:
abc, def
Output:
JavaScript has two main type categories, primivites and objects.
typeof new String(); // "object"
typeof ''; // "string"
For statements of assigning primitive values to a variable like:
var str1 = "Hi";
JavaScript will internally create the variable using:
String("Hi")
Using the new keyword works differently and returns an object instead.
Calling new String(something)
makes a String instance object.
The results look the same via console.log() because it'll just extract the primitive string from the String instance you pass to it.
So: just plain String() returns a string primitive. new String('xyz') returns an object constructed by the String constructor.
It's rarely necessary to explicitly construct a String instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With