iamPavan
iamPavan

Reputation: 275

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?

Upvotes: 3

Views: 1419

Answers (1)

CertainPerformance
CertainPerformance

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 .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.

Upvotes: 4

Related Questions