8

Possible Duplicate:
Difference between the javascript String Type and String Object?

Write this simple code in Firebug:

console.log(new String("string instance"));
console.log("string instance");

What you see is:

enter image description here

Why these two console.log() calls result in different output? Why string literal is not the same as creating a string through String object? Is it a Firebug representation style? Or do they differ in nature?

3
  • Please visit the post stackoverflow.com/questions/2051833/… Commented Dec 28, 2011 at 15:07
  • 2
    @TomalakGeret'kal duplicates don't warrant downvotes, just vote to close as duplicate if you have the rep, or just point it out and someone else will. Commented Dec 28, 2011 at 15:50
  • @Davy8: Yes they do. It's the most obvious indication of "no research effort". I closevoted and downvoted, as is usual. Thanks for your input. Commented Dec 28, 2011 at 16:16

4 Answers 4

7

They differ. A string literal is a primitive value, while a "String" instance is an object. The primitive string type is promoted automatically to a String object when necessary.

Similarly, there are numeric primitives and "Number" instances, and boolean primitives and "Boolean" instances.

Sign up to request clarification or add additional context in comments.

2 Comments

For what it's worth, to get a string literal from a String object, you can call the toString() function on the String object. For example, new String("bork") === "bork" is false, while new String("bork").toString() === "bork" is true. Oh, javascript...
And how does this "promotion" occur?
3

new String("...") returns a string object.

"..." returns a string primitive.

Some differences are:

  • new String("foo") === new String("foo") - false; object reference equality rules
  • "foo" === "foo" - true; string equality rules

and:

  • new String("foo") instanceof Object - true; it's an object derived from Object
  • "foo" instanceof Object - false; it's not an object but a primitive value

Most of the times you just want a primitive value because of these "quirks". Note that string objects are converted into primitive strings automatically when adding them, calling String.prototype functions on them etc.

More information in the specs.

Comments

1

console.log("string instance"); prints string litral but console.log(new String("string instance")); is object so its printing all the details of string like each index and character. Watch out the screen shot below, its showing each character of "string instance".

enter image description here

Comments

1

try console.log((new String("string instance")).toString())

Anyways, it's because new String("string instance") is an Object, and console.log doesn't automatically stringify objects

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.