1

I have two fiddles that apply the code below, the only difference being that one uses console.log while the other uses alert to show the value of the variable myString. One fiddle alerts the string 'foo' while the other logs foo like this foo {0="f", 1="o", 2="o"} What accounts for this difference?

    var myString = new String('foo'); // produces a String() object

   alert(myString);​

http://jsfiddle.net/mjmitche/UdYXZ/

http://jsfiddle.net/javascriptenlightenment/XcfC5/

BrainLikeADullPencil
  • 11,313
  • 24
  • 78
  • 134

3 Answers3

4

console.log outputs the actual content of the variable, which in this case is an object with properties.

alert on the other hand casts everything to a primitive string first.

Wolfgang Stengel
  • 2,867
  • 1
  • 17
  • 22
0

From the the firebug documentation of the console object:

If objects are logged, they will be written not as static text, but as interactive hyperlinks that can be clicked to inspect the object in Firebug's HTML, CSS, Script, or DOM tabs. You may also use the %o pattern to substitute a hyperlink in a string.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Kiersten Arnold
  • 1,840
  • 1
  • 13
  • 17
  • 1
    I'm not sure that addresses the OP's question. It appears as though they are asking why `console.log` would output the String object as an array of characters, as opposed to a String "primitive." – Palpatim Oct 12 '12 at 20:46
0

alert() converts the object passed to it into a string using the object's toString() method. Unlike alert(), console.log() is not limited to displaying a simple string and can allow you to interact with the object passed to it, for example letting you inspect its properties.

BrainLikeADullPencil
  • 11,313
  • 24
  • 78
  • 134