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:
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?
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.
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 rulesand:
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 valueMost 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.
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"
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With