0

Why do I get the following error...

Uncaught TypeError: object is not a function

...at the following line, of a certain JS script?

(function($){

And why do I get that error only when JS are concatenated? (I'm using Gulp)

And why does it work if I add ; before that line, like that:

;(function($){

?

update

The preceding line - that is, the object which is not a function, according to the runtime error - on the concatened script was a }, as in:

storage = {
   //...
}

I'm used to always put semicolon, but not after curly braces.

Turns out the curly braces could delimit the end of a statement, like in this case, and then it's recommended to use the semicolon to avoid this error. Here's a good explanation.

Community
  • 1
  • 1
zok
  • 6,065
  • 10
  • 43
  • 65
  • please provide a full example – sina72 Jul 30 '14 at 19:16
  • 1
    http://stackoverflow.com/questions/7145514/whats-the-purpose-of-starting-semi-colon-at-beginning-of-javascript – eithed Jul 30 '14 at 19:18
  • 1
    Have a look at the previous line and you'll see the object that is not a function. Put a semicolon *there* (not in front of the IIFE) – Bergi Jul 30 '14 at 19:19
  • possible duplicate of [What does the leading semicolon in JavaScript libraries do?](http://stackoverflow.com/questions/1873983/what-does-the-leading-semicolon-in-javascript-libraries-do) – Dave Newton Jul 30 '14 at 19:29
  • @eithedog Or the question it's a dupe of; when questions are dupes, vote to close. – Dave Newton Jul 30 '14 at 19:29
  • @Bergi it is a bad practice to put semicolon before the IIFE too, just in case? – zok Jul 30 '14 at 19:46
  • 1
    @zok: Not really, but it *should* be an unnecessary practise :-) – Bergi Jul 30 '14 at 19:48

2 Answers2

3

Javascript ignore missing semi-colon and try to interpret it. So if you don't input the semi-colon, it use the next line to see if it should end the line or chain it.

That allow you to use thing like this :

String
.split();

and it will be interpreted like that :

String.split();

But, this would also work :

String
.split
();

Now, If you have something like this :

var a = 'a';
var b = a
(function(){})

JavaScript has no way to know what you really want to do, so it will interpret it like that :

var a = 'a';
var b = a(function(){});

Giving you the error [place object type here] is not a function

Bottom line, always put your semi-colon.


Edit

After seeing your code, here how it is interpreted :

storage = {/**/}(function($){})(jQuery);

So Object ({} === Object) is not a function

Community
  • 1
  • 1
Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
1

When concatenated it believes you're trying to call whatever precedes the (function($) {...}.

If you put () after a reference it tries to call whatever the reference is. This is why you'll see a lot of JavaScript libraries precede their code with a lone ;

Dave Newton
  • 158,873
  • 26
  • 254
  • 302