Search code examples
javascriptobjectloggingconsolereturn

JavaScript return object


I am digging into some JavaScript at the moment and I have a given function from which I want to return an object similar to HashMap. Here are the contents of the function:

function(video){
    var obj = {"title":video.title, "id":video.id};
    console.log(obj);
    return obj;
}

The problem is that the console.log prints the correct values, but the return does not return them. Here is an example output:

console.log:

{title: "Die Hard", id: 2}
{title: "Avatar", id: 3}

return:

{[Object]}
{[Object]}

Solution

  • I suspect you are alerting the results to the screen.

    function video(){
      return {title: "Die Hard", id: 2}
    }
    
    a = video();
    
    console.log(a); // Object {title: "Die Hard", id: 2}
    alert(a); // [object Object]
    

    You can read up on why that is, as well as possible solutions here: Print content of JavaScript object?

    However, the bottom line is: just use console.log() to inspect objects (and anything else really).