Alexander Gelbukh
Alexander Gelbukh

Reputation: 2240

Does HTML comment <!-- act as a single-line comment in JavaScript, and why?

How specifically does JavaScript understand the construct <!--? From the point of view of JavaScript, is it yet another comment in addition to // and /* */?

From testing it seems that JavaSript treats <!-- like //: a one-liner

<script> <!-- alert('hi') //--> </script>

does nothing, while

<script> <!-- 
alert('hi') //--> </script>

works as expected.

Where is this behavior documented?

This is not a duplicate of other questions: I don't ask why or whether or how it should be used. I ask what syntax and semantics it has in JavaScript, formally. The question is non-trivial and is not answered in other questions: for example, the behavior indicated above cannot be guessed from the other questions and their answers (in fact this was my motivation: my program with a one-liner as above did not work, and those questions and answers were no help in understanding why).

Upvotes: 12

Views: 2446

Answers (1)

Felix Kling
Felix Kling

Reputation: 817030

From testing it seems that JavaSript treats <!-- like // a one-liner

Yes it does, as specified in the ES6 spec, annex B:

B.1.3 HTML-like Comments

Comment ::
    MultiLineComment
    SingleLineComment
    SingleLineHTMLOpenComment
    SingleLineHTMLCloseComment
    SingleLineDelimitedComment

SingleLineHTMLOpenComment ::
    <!-- SingleLineCommentCharsopt

However, note the description of annex B:

This annex describes various legacy features and other characteristics of web browser based ECMAScript implementations. All of the language features and behaviours specified in this annex have one or more undesirable characteristics and in the absence of legacy usage would be removed from this specification. However, the usage of these features by large numbers of existing web pages means that web browsers must continue to support them. The specifications in this annex defined the requirements for interoperable implementations of these legacy features.

These features are not considered part of the core ECMAScript language. Programmers should not use or assume the existence of these features and behaviours when writing new ECMAScript code. ECMAScript implementations are discouraged from implementing these features unless the implementation is part of a web browser or is required to run the same legacy ECMAScript code that web browsers encounter.

So, this part only exists to describe existing "unofficial" behavior and as soon as browsers stop implementing this behavior, will be removed from the spec.

Upvotes: 12

Related Questions