javascriptnode.jsiife

Immediately invoked function expression causing error?


Can someone explain why this could happen?

If I write something like this in a file named like test.js,

const anyObject = {}
(function(){ 
  console.log('hello world!') 
}())

run it through console with $node test.js

then in the console, a hello world! will be printed, but followed with this: TypeError: (intermediate value) is not a function

Idon't know what exactly happend there, I guess somehow node is taking the function expression as a function call expression ?

I'm using node v6.9.1


Solution

  • You could use void for calling without semicolon.

    This forces the expression to evaluate and return undefined.

    void (function() { 
        console.log('hello world!') 
    }());

    It works even without outer parenthesis.

    const anyObject = {}
    void function() { 
        console.log('hello world!') 
    }();