kilojoules
kilojoules

Reputation: 10093

javascript function to return object returns [object Object]

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

function myfunc() {
   return {"name": "bob", "number": 1};
}
myfunc();

Upvotes: 11

Views: 43402

Answers (2)

m0meni
m0meni

Reputation: 16455

Haha this seems to be a simple misunderstanding. You are returning the object, but the toString() method for an object is [object Object] and it's being implicitly called by the freecodecamp console.

Object.prototype.toString()

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

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

function myfunc() {
   return {"name": "bob", "number": 1};
}

var myobj = myfunc();
console.log(myobj.name, myobj.number); // logs "bob 1"

Upvotes: 11

aliasm2k
aliasm2k

Reputation: 901

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

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

Upvotes: 4

Related Questions