A Perplexing JavaScript Parsing Puzzle
Published on: 2025-06-21 00:46:02
Show answer
It prints 1 .
wait wtf
At the beginning of a line (and only at the beginning of a line), --> starts a comment. The JavaScript is parsed as
x = 1 ; x ; // 0
The browser then displays the value of the last expression, which of course is 1.
but why
It’s a legacy hack.
Netscape Navigator 2 introduced both JavaScript and the
Old browsers would parse the content as an HTML comment and ignore it, new browsers would parse the content as JavaScript and execute it. I’m not quite sure why weren’t syntax errors; presumably there was special code in the js engines to handle them, but I can’t figure it out where.
All modern browsers at least recognize