A hashbang (or shebang) comment is a line starting with #! as the first two code points of a source text:
#!/usr/bin/env node
It serves two readers. On Unix-like systems, the OS sees #! when you run an executable file directly and uses the rest of the line as the interpreter command; /usr/bin/env node finds node on the PATH. The engine then reads the same file, and the spec defines HashbangComment as #! followed by the rest of the line, discarded like any other comment.
Why it's in the grammar at all: CLI hosts such as Node.js already accepted the line, but # isn't valid JavaScript there, so each host stripped it before handing the text to the engine. The Hashbang Grammar proposal moved that into the language so every engine parses the same text the same way. It reached Stage 4 and shipped in ES2023.
The rules are tight on purpose:
- Only at the very start. The lexical grammar uses the
InputElementHashbangOrRegExpgoal only at the start of a Script or Module. One leading space or blank line makes#!a SyntaxError. - Scripts and modules, not function bodies.
evalparses a Script, so it accepts a hashbang;new Functionparses a function body, so it doesn't. - It's a comment. It has no effect on how the engine runs the code; the OS and the host decide what runs it.
You'll meet it in npm packages with a bin entry: npm's docs require the file to start with #!/usr/bin/env node, otherwise the script isn't started with Node.