Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference of "String" object, and string literal in JavaScript [duplicate]

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?

like image 692
Saeed Neamati Avatar asked Dec 28 '11 15:12

Saeed Neamati


4 Answers

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.

like image 125
Pointy Avatar answered Sep 30 '22 12:09

Pointy


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.

like image 37
pimvdb Avatar answered Sep 30 '22 12:09

pimvdb


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

like image 39
dku.rajkumar Avatar answered Sep 30 '22 11:09

dku.rajkumar


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

like image 40
ᅙᄉᅙ Avatar answered Sep 30 '22 12:09

ᅙᄉᅙ