0

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.

6
  • There's a syntax difference between a function declaration statement and a function instantiation expression. They look similar but they are not the same thing. Commented Jun 9 at 12:06
  • JavaScript statement syntax is driven by the first token of each statement. When the first token is the keyword function, it's a function declaration statement, not an expression. Commented Jun 9 at 12:06
  • 2
    Note that you can add parentheses around your generator function expression and it'll be correct, because the ( character opens the statement, making it be an expression statement. Commented Jun 9 at 12:09
  • 1
    What said above is the reason why IIFE syntax is (function () {...})() and not function () {...}() Commented Jun 9 at 12:12
  • A generator declaration cannot both be an orphan and anonymous at the same time. What would be its purpose? It wouldn't make sense. Hence the error is valid. Commented Jun 9 at 13:09

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.