Search code examples
javascripttheory

Why is the HTML comment open block valid JavaScript?


In some old code, I found a JavaScript file with it's contents surrounded by HTML comments.

I understand the reasons for doing that in old browsers, but not how it is valid JavaScript in any way.

The expression <!-- is undefined in Chrome and IE's console.

Is this a special case handled by the interpreter (http://javascript.about.com/library/blhtmcmt.htm) still defined in the ECMAScript standards and working in modern browsers, or does the combination of these symbols happen to result in something that's undefined?

I read this as something like "less-than NOT decrement", which seems nonsensical with no operands. Any of these by themselves return a syntax error.

I get why things like "use strict"; are valid, but do nothing, but I can't tell what this code actually does.

I'm probably overthinking it, but would like to understand what's going on


Solution

  • This is a non-standard feature that browsers and JavaScript engines have always implemented. Nowadays, it cannot be removed from the Web platform, as that would break backwards compatibility. It’s detailed in the JavaScript / Web ECMAScript spec:

    <!-- must be treated as the start of a SingleLineComment — equivalent to //.

    var x = true;
    <!-- x = false; // note: no syntax error
    x; // true
    

    --> at the start of a line, optionally preceded by whitespace or MultiLineComments, must be treated as a SingleLineComment — equivalent to //.

    var x = true;
    --> x = false; // note: no syntax error
    x; // true
    
    var x = 1;
    /*
    multiline comment!
    x = 2;
    */ --> x = 3;
    x; // 1