Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why In JS -> {} + {} gives [Object object] [ Object object]?

I am new to JS and I’d like to know why I am facing this situation.
Let’s assume we have something like this :

var ids = [10,20,30];
var types= ['PIZZA','HAMBURGER','AVOCADO'];
var payload=[];

for(let i = 0; i <= ids.length; i++){
    var id= ids[i];
    var type= types[i];
    var couple= {"id":id ,"type":type};
    console.log(couple);
    payload.push(couple);}
           
console.log('result is ' + payload);

result is :
[object Object],[object Object],[object Object],[object Object]

I was expecting something like :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{ "id" : 10, "type" : "PIZZA" },
{ "id" : 20, "type" : "HAMBURGER" },
{ "id" : 30, "type" : "AVOCADO" }

Do you know why
{} + {} gives "[Object object][Object object]" ?
can you please explain to me how can I avoid this in JS?

Thank you as always for your time, waiting for some cool feedback!
have a great day!

>Solution :

With Js being weakly typed, string + object will convert the object to a string. What you want to do is `console.log(‘the resulst is’,payload)

var ids = [10,20,30];
var types= ['PIZZA','HAMBURGER','AVOCADO'];
var payload=[];

for(let i = 0; i <= ids.length; i++){
    var id= ids[i];
    var type= types[i];
    var couple= {"id":id ,"type":type};
    payload.push(couple);}
           
console.log('result is ', payload);
console.log('object to string', payload.toString())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading