1

I am confused by JS object output.

First one:

var a = {}
console.log(a);

the output for the first one is {}.

Second one:

var a = {}
console.log(a + '123');

the output for the second one is [object Object]123

Third one:

var a = {
  toString: function() {
    return 'hello'
  }
}
console.log(a + '123');

the output for the third one is hello123

I don't understand why the second one is [object Object]123 while the third one is hello123

j08691
  • 204,283
  • 31
  • 260
  • 272
Kyle Zhang
  • 31
  • 5
  • console.log(a + '123'); => this means, convert a and '123' to string. in third sample you defined a toString method, that will be used to convert your object in string. – db1975 Feb 19 '20 at 22:02
  • 1
    because in #2 you are combining an object and a string where as in #3 you overrode the toString function of the object with a function that returns hello. When you combine with a string js is automatically calling the toString method on the object. – tstrand66 Feb 19 '20 at 22:02
  • Related https://stackoverflow.com/questions/4750225/what-does-object-object-mean – j08691 Feb 19 '20 at 22:02
  • my take on this.. console.log(a); should actually return Object { } (meaning empty object). if you do console.log(a.toString()); it will become "[object Object]", which is why if you do console.log(a + 123), the a becomes a.toString() and 123 also becomes string, you will get [obejct Object]123. when you override the original Object toString() method to return 'hello', now the a.toString() = hello, hence you will get the hello123 – wakakak Feb 19 '20 at 22:04
  • Try `var a = {} console.log(a.toString());` The toString happens implicitly in the second one. – LukStorms Feb 19 '20 at 22:08

2 Answers2

1

I suspect the part you're missing is that Objects already have a default toString() method, and its implementation returns [object Object]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString

jack
  • 573
  • 4
  • 12
0
  • In the first example the value of the object at the moment you open the console is displayed
  • In the second example, the toString method inside the Object prototype is called on the object because of concatenation(+) with a string, which converts the object to string and concatenates the result to '123', note that when calling toString to an object it just gives you [object Object].
  • In the third example, toString is again called on the object due to concatenation(+) with a string. The object has, however, overridden the toString method definition in the prototype by a custom toString method that returns 'hello', so it will concatenate 'hello' to '123'. Without the custom toString function definition it would have looked the function up in the prototype chain and would have printed [object Object] like the second example.
Addis
  • 2,480
  • 2
  • 13
  • 21