Defining dynamic comments on the fly

I think first there is a problem how the ES parses the comments within tagged template literals.

Your overall premise seems to be that it makes sense to interpret JavaScript comments right in the middle of a tagged template literal, and the parser is currently acting in an unexpected way by not doing so. This premise doesn't really hold water.

For one, it's a template literal - comments are allowed in between tokens, not smack in the middle of something. For example, all of these are also illegal:

0./* whatever */2 // Can't put a comment in the middle of a numeric literal
fun/*!!*/ction() {} // Can't put a comment in the middle of a keyword
'ab/*whatever*/cd' // Can't put a comment in the middle of a string literal
`ab/*!!*/cd` // Can't put a comment in the middle of an untagged template string literal
/.+/* hi there */abc/ // Can't put a comment in the middle of a regex literal

There's nothing inconsistent about the way JavaScript does its comments, in fact, it's quite consistent and predictable, and it's very similar to comment systems of other languages. The ability to add comments to a template literal should be seen as an extra nice-to-have feature, not a "JavaScript is broken and must be fixed" thing.

With that said, I do agree that this sort of feature would be nice to have, so it's ok to have an open discussion around it - it's just not magically elevated to top priority due to a non-existent inconsistency.

Next - we have to keep JavaScript backwards compatable. What's valid as a string today needs to stay as a valid string tomorrow. In your duplicate post, @lightmare gave a number of examples of what would happen if we were to all of a sudden change the interpretation of "/*" within a string from a literal "/" and "*" character to the start of a comment. Lots of existing JavaScript would break. The only way to preserve backwards compatibility would be to make the start-of-a-comment character-sequence within the template string be something that's currently invalid JavaScript today. As far as I can tell, this leaves us with very few options - the start-of-comment sequence must contain a backtick (`) or this "${". Anything else would already be valid JavaScript and can't be used.

So, for example, we could make ${* be a comment-start, and *} be a comment end. This would be a valid solution we could discuss.

html`
<div>
  ${*
  <span id="xyz">${content}</span>
  *}
</div>

Or, if we accept that JavaScript is not broken in its current state (along with every other language with multi-line strings), then we could also discuss adding smarts to editors, so that they can do the ${''/* ... */} workaround.

2 Likes