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
  • 333
  • 4
  • 15

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
  • 191,768
  • 25
  • 236
  • 258
0

If you use a ; you can get around this.

Expressions should end with ; to avoid this problem:

function A(){}
A();
(function(){})()
Ovidiu Dolha
  • 5,335
  • 1
  • 21
  • 30