Immediately invoked function expression throws "object is not a function"
Asked Answered
Y

1

6

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.

Yogi answered 9/1, 2014 at 21:42 Comment(3)
possible duplicate of Why is this grouping operator + function immediatly invokedAdrianaadriane
You should always use semicolons after your statements - https://mcmap.net/q/81993/-do-you-recommend-using-semicolons-after-every-statement-in-javascriptRefrigerator
Related: TypeError: console.log(…) is not a function.Ankney
Y
14

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

Yogi answered 9/1, 2014 at 21:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.