JavaScript, generally, allows executing a simple expression, even though it has no side effects and is generally pretty useless. For example, the following are valid JavaScript files:
42
and
'abc'
What I mean by that is that if I put one of these in a file and execute it via:
node file.js
of
deno run file.js
I get no errors (and, of course, no output).
However, if I put the following expression in a JavaScript file, I get an error when attempting to execute the file via either of the above 2 methods:
function*(line) {
yield 42;
return;
}
NodeJS says "SyntaxError: Function statements require a function name" deno says "The module's source code could not be parsed: Expected ident at..."
However, this will parse and execute without error:
let f = function*(line) {
yield 42;
return;
}
Here, there is no identifier required in the function statement - an anonymous function is created and assigned to the variable f. So, why was an identifier required before?
Before you answer, consider the JavaScript code below, which is where I came across this problem:
let f = function*(line) {
yield 42;
return;
}
console.log(f.toString());
The code parses and executes without error. However, it outputs this:
function*(line) {
yield 42;
return;
}
which, as you can see above, is considered invalid JavaScript. So, I've created a perfectly valid function, but JavaScript's buildin toString() method returned invalid JavaScript code!
So, e.g., if I try to minimize it using uglify-js, gives me an error. And, of course, I couldn't execute it since it's invalid JavaScript code.
function, it's a function declaration statement, not an expression.(character opens the statement, making it be an expression statement.(function () {...})()and notfunction () {...}()