4

I have an object with the following structure

var obj = {
    toString: function(){ return "20" },
    valueOf: function(){  return 10; }
};

alert(obj) //20
console.log(obj) //Object {toString: function, valueOf: function}

unlike alert(obj) why console.log(obj) shows object structure instead of return value of toString()??

In both scenario expecting string text.

Alex Mathew
  • 3,925
  • 5
  • 21
  • 25

4 Answers4

2

It is only for the good of debugging.
Would like to to see obj.toString() in console? Use:

Console.count(obj); //also will show how many times obj has been invoked

Usefull links:

  1. Firebug Console API
  2. Chrome Console API
  3. Mozilla Dev Docs
Ruslan Ismagilov
  • 1,360
  • 7
  • 14
1

console.log intended for debugging, and alert intended for showing text, so alert seek toString function if it exists then show it result, instead it will show [Object object].

Sergey92zp
  • 589
  • 4
  • 22
1

If you want to get text in console then just add empty string like bellow

console.log(obj + "");
Mitul
  • 3,431
  • 2
  • 22
  • 35
0

In the words of Tim Down, the method

alert() converts the object passed to it into a string using the object's toString() method [whereas] console.log() is not only used to display a simple string but it can also allow you to interact with the object passed to it.

Also console.log() is used for debugging. In the words of Jan Hančič,

You can for instance log something to the console when something happens.

You use console.log to view full object structure.

Community
  • 1
  • 1
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331