Hacker News new | ask | show | jobs
by jkrems 1562 days ago
Important footnote: Unless you are in an JavaScript module file. They work in scripts only. E.g. the following is a syntax error in a module but a valid script:

    <!-- ok if it's a script only
    --> console.log("ok");
2 comments

Strict mode is forced in modules, while you need to "use strict" in scripts. That might explain it.
It's actually not related to strict mode. HTML comments work fine in strict mode as well as sloppy mode in scripts. The difference here is that modules are a different file format / syntax and they fundamentally don't include parts of the syntax that was supported in the older script file format (and vice versa: they allow syntax like top-level await that wasn't/isn't valid in the script file format).
Technically, they "work" in both scripts and modules, they just work differently in each case. This is valid Javascript that returns true if running in script mode or false if running in module mode:

    const isScript = (x = true) => x <!--x
    console.log(isScript()) // true or false depending on whether the code is ESM
What's happening is that `<!--` is a comment token in script mode, but it's parsed as `< ! --` in module mode.