Reputation: 275
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?
Upvotes: 3
Views: 1419
Reputation: 370779
Inside the template literal, the expression inside gets implicitly coerced to a string (because template literals always evaluate to strings). So, the array gets .join
ed 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.
Upvotes: 4