5

I'm defining various modules in a Javascript file:

var module = {/* ... */}

(function(){
    console.log('Invoked');
})()

However the IIFE throws an error:

> TypeError: object is not a function

I tried just copy and pasting the IIFE code and there is no issue.

Samira Khorshidi
  • 965
  • 1
  • 9
  • 27
Matt Zeunert
  • 14,721
  • 6
  • 47
  • 77
  • possible duplicate of [Why is this grouping operator + function immediatly invoked](http://stackoverflow.com/questions/14810951/why-is-this-grouping-operator-function-immediatly-invoked) – cookie monster Jan 09 '14 at 21:57
  • You should always use semicolons after your statements - https://stackoverflow.com/a/444082/1766230 – Luke Feb 20 '18 at 14:31
  • Related: [`TypeError`: `console.log(…)` is not a function](https://stackoverflow.com/q/31013221/4642212). – Sebastian Simon Aug 30 '18 at 08:57

1 Answers1

13

The module definition needs a semicolon at the end of the declaration:

var module = {/* ... */}; // <======= Semicolon!

(function(){
    console.log('Invoked');
})()

Without it Javascript is trying to call the object:

var module = {/* ... */}(function(){console.log('Invoked');})()

Or shortened:

var module = {/* ... */}()

You'd get the same problem when trying to writing two IIFEs next to each other:

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

This doesn't work because a single function declaration returns undefined:

TypeError: undefined is not a function

Matt Zeunert
  • 14,721
  • 6
  • 47
  • 77