Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immediately invoked function expression throws "object is not a function"

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.

like image 544
Matt Zeunert Avatar asked Jan 09 '14 21:01

Matt Zeunert


People also ask

Why immediately invoked function expression?

Immediately invoked function expressions can be used to avoid variable hoisting from within blocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined within the function.

Do immediately invoked functions wait for a function call to be executed?

An Immediate-Invoked Function Expression (IIFE) is a function that is executed instantly after it's defined. This pattern has been used to alias global variables, make variables and functions private and to ensure asynchronous code in loops are executed correctly.

What is non function in JavaScript?

The JavaScript exception "is not a function" occurs when there was an attempt to call a value from a function, but the value is not actually a function.

What does it mean when something is not a function?

Relations That Are Not Functions. A function is a relation between domain and range such that each value in the domain corresponds to only one value in the range. Relations that are not functions violate this definition. They feature at least one value in the domain that corresponds to two or more values in the range.


1 Answers

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

like image 160
Matt Zeunert Avatar answered Oct 15 '22 19:10

Matt Zeunert