12. Practice makes perfect .. Revised


The Corrected code is below one

var object1 = {
        age: 24,
    var object2 = {

        time: 5.30,
        location: "kolkata"
    var object3 = {
        time: 6.45,
        location: "kolkata"

Its giving output

{ name: 'amartya', age: 24, location: 'kolkata' }
{ fruits: 'banana', time: 5.3, location: 'kolkata' }
{ fruits: 'grapes', time: 6.45, location: 'kolkata' }

but whenever I like to print

console.log("This is object 1 " + object1);
console.log("This is object 2 " + object2);
console.log("This is object 3 " + object3);

Its printing

This is object 1 [object Object]
This is object 2 [object Object]
This is object 3 [object Object]

As a result am confused .. Someone please elaborate ..


I'm not very familiar with with JS, so I might be a bit off, but most likely this is what happens:

When you give console.log a non-built-in object, it does its own little thing and looks up its attributes and sticks them between {} and then prints that.

But when you concatenate an object to the end of a string, then your object's toString property is called, which in this case is inherited from Object since you haven't defined it yourself. So that'll return a very simplistic string to represent your object, which is then concatenated to your string. console.log then receives this string and prints it.

You could override toString to define how your object should be converted to string.

Perhaps this would do it:

object3.toString = function() {
    return JSON.stringify(this);


// a google search
// javascript why console.log displays [object Object] site:stackoverflow.com
// reveals
// http://stackoverflow.com/questions/4933217/print-json-parsed-object
// try
console.log("%s %o", "My Object", object1);