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?

4
  • 2
    As You are getting the string interpretation of an array. Commented Jul 28, 2019 at 7:49
  • Because you're building a string? Why would you expect the template string to be displayed as something else? Commented Jul 28, 2019 at 11:31
  • @Bergi, here the data type of likes is an array. It is not a string. Commented Jul 29, 2019 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. Commented Jul 29, 2019 at 14:46

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

... or in any way the console wants to log it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.