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.

4
  • Your var s's isn't valid jsfiddle.net/a7yod154 (did you mean to escape the backtick in the middle, or use a semicolon, or something?) Commented May 10, 2019 at 2: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. Commented May 10, 2019 at 2:46
  • 1
    this is template literals. where ${} can be used to do any string substitution. stackoverflow.com/questions/27678052/… Commented May 10, 2019 at 2:49
  • developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented May 10, 2019 at 2:55

1 Answer 1

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]
`)
Sign up to request clarification or add additional context in comments.

Comments

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.