The JS runtime is not perfect at guessing where semi-colons should go.
When it sees this:
eval('console.log(0)')
(function(x){console.log(x)})(1)
It incorrectly assumes that the result of the immediately invoked function expression is part of the eval
line (a potential parameter to be passed to the potential function that the eval
evaluates to).
Here's an example of when that would work:
eval("(function(message){ alert(message); })")
("Hi there!");
But, in your case, eval
is not evaluating to a function, so trying to pass an argument to it fails, thus your error message.
But, it actually has less to do with eval()
, in particular. This can pop up anytime a semi-colon is omitted just prior to an IIFE or any expression starting with a (
.
Adding the semi-colon, allows the runtime to know that the IIFE is separate.
The rule is that you must insert semi colons on any line that is followed by a (
(as this is how an expression can begin) in order to keep them separate . But, the better rule is to not rely on automatic semi-colon insertion at all and always put them in yourself.