11

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();
2
  • 1
    How do you know what the function returns? Are you using a console? Are you alert()ing the result? Commented Jan 3, 2016 at 5:57
  • I'm using freecodecamp's coding console Commented Jan 3, 2016 at 6:02

2 Answers 2

11

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"

Sign up to request clarification or add additional context in comments.

2 Comments

How would you call the object when you don't know the key values? I.e I want to console.log the contents of the object since I don't know what it contains
@DCoderT you can use Object.entries(). Check out the example here developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
4

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.