Let's assume we have an object:
var pet = {
"name": "Barky",
"species" : "dog",
"foods": {
"likes": ["bones", "carrots"],
"dislikes": ["tuna"]
}
};
console.log(pet.foods.likes); //returns [ 'bones', 'carrots' ]
console.log(`${pet.foods.likes}`) //returns "bones,carrots"
If I use template string, it is displaying as a normal string, why?
Inside the template literal, the expression inside gets implicitly coerced to a string (because template literals always evaluate to strings). So, the array gets .joined by commas as part of the interpolation process, and becomes a string (without []s, and without string delimiters between items).
console.log(`${pet.foods.likes}`) //returns bones,carrots
is equivalent to
console.log(pet.foods.likes.join(','))
or
console.log(pet.foods.likes.toString())
In contrast, the plain pet.foods.likes is an array, and so gets logged as an array with array delimiters.
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