1

The following code including an IIFE causes an error in Node(node: v8.6.0) environment.

function A(){}
A()
(function(){})()

​​​​​​A(...) is not a function​​

This error information is confusing for me.

If I change the position of IIFE, the code runs successfully in Node.

(function(){})()
function A(){}
A()

I have searched the answer on google but didn't find why.

A.Chao
  • 313
  • 3
  • 12

2 Answers2

2

In this snippet:

function A(){}
A()
(function(){})()

you are starting third line with ( which is interpreted by JS parser as a function invocation. In this case automatic semicolon insertion lets you down.

You could try this instead:

function A(){}
A(); // <-----
(function(){})()

or

function A(){}
A()
;(function(){})()

both will fix the problem.

Avoid staring line with ( or [.

dfsq
  • 187,712
  • 24
  • 229
  • 250
0

If you use a ; you can get around this.

Expressions should end with ; to avoid this problem:

function A(){}
A();
(function(){})()
Ovidiu Dolha
  • 4,966
  • 1
  • 19
  • 30