3

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?

anegru
  • 1,023
  • 2
  • 13
  • 29
iamPavan
  • 255
  • 4
  • 15
  • 2
    As You are getting the string interpretation of an array. – Pratik Jul 28 '19 at 07:49
  • Because you're building a string? Why would you expect the template string to be displayed as something else? – Bergi Jul 28 '19 at 11:31
  • @Bergi, here the data type of likes is an array. It is not a string. – iamPavan Jul 29 '19 at 13:59
  • @iamPavan `likes` might an array, but the data type of the result of the template literal evaluation is a string. Don't wrap the array in a string if you want to keep it as an array. – Bergi Jul 29 '19 at 14:46

1 Answers1

4

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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320