The javascript function to return an object returns an object [object Object]

The intended output of my function is {"name": "bob", "number": 1} , but it returns [object Object] . How to achieve the desired result?

 function myfunc() { return {"name": "bob", "number": 1}; } myfunc(); 
+6
source share
2 answers

Haha, this seems like a simple misunderstanding. You return an object, but the toString() method for the [object Object] and it is implicitly called by the freecodecamp console.

Object.prototype.toString ()

 var o = {}; // o is an Object o.toString(); // returns [object Object] 

You can easily verify that you are actually returning the object using your own code:

 function myfunc() { return {"name": "bob", "number": 1}; } var myobj = myfunc(); console.log(myobj.name, myobj.number); // logs "bob 1" 
+7
source

If you try console.log(ob.name) it should display bob

{} in JS is an abbreviation for an object. You can convert your object to a string using the toString() method.

+2
source

All Articles