Deadpool
Deadpool

Reputation: 8240

Difference in these 2 Strings (JavaScript)

I was trying to create string data-types variables with values in 2 ways.

  1. As string-literal
  2. Using New Keyword

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:

enter image description here

Upvotes: 6

Views: 287

Answers (5)

xMayank
xMayank

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

Unknow
Unknow

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

Akhil Ravindran
Akhil Ravindran

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

Lars Kakavandi-Nielsen
Lars Kakavandi-Nielsen

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

Gaurav Mogha
Gaurav Mogha

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

Related Questions