0

I have a very elementary query on how the object is being handled by console.log in Javascript. Lets assume there is an object called

    let details = {name: 'tom', lname: 'cruise'};
    console.log('DETAILS OBJECT IS:-'+details) // Will print object Object
    console.log('DETAILS OBJECT IS:-',details) // Will print {name: 'tom', lname: 'cruise'}.

Why the first console.log statement prints the object Object whereas the second statement prints the actual value of an Object?

Ary
  • 181
  • 4
  • 14
  • The first will convert `details` to a string, since you are performing string concatenation. The second will just print the object contents – VLAZ Sep 17 '19 at 07:53
  • 2
    `({}).toString()` -> [object Object] – phuzi Sep 17 '19 at 07:54
  • @Ary marking it as duplicate is to *help you*. It doesn't mean your question was invalid but it's completely neutral - there is another question that already answered it, that's all it means. It doesn't mean your question was bad or that you did something wrong. Ultimately, it helps other people who search for this - if anybody enters a search query that lands them on your question, they will also find the dupe target. And it's easier to maintain one question than multiple repeated ones. – VLAZ Sep 17 '19 at 08:08
  • 1
    Basically it's not duplicate, "duplicate" question asks how to convert object to string, and not about difference between those two statements.. – mayakwd Sep 17 '19 at 08:16

2 Answers2

2

In the first option you passing string and asking to concatenate string with Object, object will be automatically converted to string via toString() method.

Second option asks to log object via reference. In this case object structure will be logged in console. You should take in account that fields values of Object could be changed after "console.log" and you'll see updated values in object structure instead of values which was at the moment of "console.log".

mayakwd
  • 530
  • 3
  • 7
0

"+" will just concatenate and make it a string.

"," will log your object in console.

Pushprajsinh Chudasama
  • 7,772
  • 4
  • 20
  • 43
  • 3
    "console" as a verb means to make someone feel better about something. You probably meant "log the object to the console" or something like this. – Joachim Sauer Sep 17 '19 at 07:57