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();
To return an object from a JavaScript function, use the return statement, with this keyword.
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.
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With