Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript function to return object returns [object Object]

Tags:

javascript

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();
like image 728
kilojoules Avatar asked Jan 03 '16 05:01

kilojoules


People also ask

Can a JavaScript function return an object?

To return an object from a JavaScript function, use the return statement, with this keyword.

Can we return an object from a function?

In C++ we can pass class's objects as arguments and also return them from a function the same way we pass and return other variables.

What is return {} in JavaScript?

The return statement stops the execution of a function and returns a value. Read our JavaScript Tutorial to learn all you need to know about functions.

What happens when an object is returned from a function?

When an object is returned by value from a function, a temporary object is created within the function, which holds the return value. This value is further assigned to another object in the calling function.


1 Answers

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"
like image 195
m0meni Avatar answered Oct 06 '22 00:10

m0meni