lukash lukash - 1 month ago 9
Javascript Question

Is it possible to have a comment inside a es6 Template-String?

Let's say we have a multiline es6 Template-String to describe e.g. some URL params for a request:

const fields = `
id,
message,
created_time,
permalink_url,
type
`;


Is there any way to have comments inside that backtick Template-String? Like:

const fields = `
// post id
id,
// post status/message
message,
// .....
created_time,
permalink_url,
type
`;

Answer

No.

That syntax is valid, but will just return a string containing \n// post id\nid, rather than removing the comments and creating a string without them.

If you look at §11.8.6 of the spec, you can see that the only token recognized between the backtick delimiters is TemplateCharacters, which accepts escape sequences, line breaks, and normal characters. In §A.1, SourceCharacter is defined to be any Unicode point (except the ones excluded in 11.8.6).