javascriptecmascript-6

Why does an array embedded in a template literal not render inside square brackets?


When i try to put an array into a JavaScript array, a la,

> `${[1,2,3]}`

I get back this

'1,2,3'

and not

'[1,2,3]'

in the latest Node & Chrome.

I am missing something incredibly obvious, but need it spelled out to me nevertheless : )


Solution

  • By the default, the values that are interpolated into a template literal are converted to their string representation.

    For objects that means calling their .toString() method. The string representation of an array is simply a comma separated list of the strings representation of its elements, without leading [ or trailing ]:

    console.log(
      [1,2,3].toString()
    );