Reputation: 8240
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:
Upvotes: 6
Views: 287
Reputation: 1995
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.
Upvotes: 9
Reputation: 47
When you print an object, often the console print the object's properties.
If is a primitive the console just print the value.
The primitive is not boxed, but if you create a string with a constructor the string is boxed in the object and always have properties.
If is just a literal, it only have properties when you access to a string's property with .
operator because boxing occurs, but after that, it still being a literal with nothing additional added, because of that when you print "The cat is very grumpy"
, just print the value and nothing more. primitives literals are not always objects with properties, are only objects when are boxed.
Upvotes: 0
Reputation: 126
The String object lets you work with a series of characters; it wraps Javascript's string primitive data type with a number of helper methods.
As JavaScript automatically converts between string primitives and String objects, you can call any of the helper methods of the String object on a string primitive.
Upvotes: 0
Reputation: 2198
You are working with two different things.
The var str1 = "abc"
gives you a primitive.
While the var str2 = new String("def");
gives you a string object.
These two types behave differently
Upvotes: 2
Reputation: 400
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.
Upvotes: 4