Interpolation problem

I was completing one of the projects and found something completely incomprehensible to myself. So, I created an object “people”, added a property “_children”, initialized it to an array with objects and created a getter.

const people = {

  _children: [{name: 'Pablo'}, {name: 'Alex'}, {name: 'John'}],

  get children() {

    return this._children;

  }

};

Then, I wanted to printed the value of “_children” and it’s completely fine.

console.log(people.children);

//prints [{name: 'Pablo'}, {name: 'Alex'}, {name: 'John'}]

What is interesting for me, after that I tried to use interpolation but I recieved different result

console.log(`${people.children}`);

//prints "[object Object],[object Object],[object Object]

My question is why I have this kind of stuff logged in the console when I use interpolation, thanks in advance!

Hi @adelorian, welcome to the forums!

It’s great to see you trying different things, and being curious to learn what is going on.

I don’t pretend to be an expert, but here is my thought process…

What do you think is the difference between console.log(people.children)? and console.log(${people.children})? I don’t mean “one is using string interpolation”, but rather what does string interpolation do that makes them different?

Try running this:

console.log(typeof people.children);
console.log(typeof `${people.children}`);

typeof gives you a clue about what type of value/data you are working with (though it is not perfect). More info here.

Logically, when you use people.children you are calling an object’s property - a getter function - which then outputs an array of objects (with the data associated revealed - the key/value pairs)…

However, when you use interpolation `${people.children}`, the return value is turned into string form…

When an object is turned into a string, instead of printing out the values, it usually returns [object Object].

I had trouble finding an online resource to explain this well, but here is a post that mentions the conversion a bit, if you scroll down to the Objects section , it talks about the toString() method in relation to objects… a number of methods including string interpolation use toString() under the hood.

So for example you would have the same [object Object] output if you were in-browser using an alert(people.children) because alert uses toString() under the hood to convert the output into string form, and objects turned into strings print out their type rather than their data value.

It is something that has caught me out more than once, if we’re not carefully thinking about what we are doing.

3 Likes