Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an array inside a template string displayed as a normal string?

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?

like image 606
iamPavan Avatar asked Dec 20 '25 03:12

iamPavan


1 Answers

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.

like image 178
CertainPerformance Avatar answered Dec 21 '25 19:12

CertainPerformance