Kyle Zhang
Kyle Zhang

Reputation: 31

JavaScript Object output

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

Upvotes: 1

Views: 116

Answers (2)

Addis
Addis

Reputation: 2530

  • 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.

Upvotes: 0

jack
jack

Reputation: 622

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

Upvotes: 1

Related Questions