1

I've read some code (seems ES6) from some JavaScript/Node.js project, and I am confused with the syntax:

var c  = `
   export const imports = () => {
     const mods = []
     ${files.map((v) => `
['1234', 333]
`)}
     return Promise.all(mods)
   }
   export default imports
 `

This will give me

> c
'\n   export const imports = () => {\n     const mods = []\n     \n[\'1234\', 333]\n,\n[\'1234\', 333]\n\n     return Promise.all(mods)\n   }\n   export default imports\n '

if run in Node.js.

I've guessed this is an multiline string, and I tried this:

var s = `
    some multiline
    indented string`
['1234', 333]
`another multiline
    indented string
  `

but I got three clauses:

> var s = `
...     some multiline
...     indented string`
undefined
> ['1234', 333]
[ '1234', 333 ]
> `another multiline
...     indented string
...   `
'another multiline\n    indented string\n  '

Anyone can help me with the syntax? Which ECMAScript spec does it use? Hopefully someone can give me the link of the specific spec anchor.

cmal
  • 2,062
  • 1
  • 18
  • 35
  • Your `var s`'s isn't valid https://jsfiddle.net/a7yod154/ (did you mean to escape the backtick in the middle, or use a semicolon, or something?) – CertainPerformance May 10 '19 at 02:45
  • it's valid. only thing is var s = '' statement will assign the valud to s variable and the statement itself doesn't return anything so undefined is printed. – gp. May 10 '19 at 02:46
  • 1
    this is template literals. where ${} can be used to do any string substitution. https://stackoverflow.com/questions/27678052/usage-of-the-backtick-character-in-javascript – gp. May 10 '19 at 02:49
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals – gp. May 10 '19 at 02:55

1 Answers1

2

This is an example of template literals.

Note that the section within ${ ... } is string interpolation--what is confusing in this case is that that interpolation itself (the code below) includes a literal string.

 files.map((v) => `
['1234', 333]
`)
sinaraheneba
  • 781
  • 4
  • 18