I'm learning javascript and I'm struck at IIFE
syntax.
I have understood that to write IIFE
we need to make the function as expression and then invoke it.
We can make it as expression by wrapping function in between ()
. Or prefixing the function keyword with +
,-
,~
,!
.
Now for the problem, when I prefix with ++
I'm getting error in the console.
Code:
++function(){console.log("hello")}();
Error:
Uncaught ReferenceError: Invalid left-hand side expression in prefix operation
Why can't I use ++
? ++
is a unary operator and I thought it will make the interpreter to think anonymous function as function expression just like +
,-
etc., did.
Where am I going wrong?
As the error message says, the function()... is not a valid left-hand side expression, i.e., it cannot be assigned to.
+, -, ~, ! will cause the expression to be evaluated. On the other hand, the increment operator (++) will cause the expression not only to be evaluated, but also modified, which isn't allowed for this expression.