Difference between String object and string literal in JavaScript

Possible duplicate:
Difference between a Javascript type string and a String object?

Write this simple code in Firebug:

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

What do you see:

enter image description here

Why do these two calls to console.log() produce a different result? Why doesn't the string literal match the way how to create a string through a String object? Is it a Firebug presentation style? Or are they different in nature?

+7
source share
4 answers

They are different. A string literal is a primitive value, and an instance of "String" is an object. If necessary, the primitive string type automatically advances to the String object.

Similarly, there are numerical primitives and instances of "Number", as well as logical primitives and "Boolean" instances.

+6
source

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

"..." returns the string primitive .

Some differences are as follows:

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

and

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

In most cases, you just need a primitive value because of these "quirks." Note that string objects are automatically converted to primitive strings automatically when they are added, by calling String.prototype functions on them, etc.

Additional information in the specifications .

+2
source

console.log("string instance"); prints the string litral, but console.log(new String("string instance")); is an object, so it prints all the details of the string, like every index and character. View the screenshot below with each character "string instance" .

enter image description here

+1
source

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

In any case, because new String("string instance") is an object, and console.log does not automatically build objects

+1
source

All Articles