Reputation: 7892
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.
Upvotes: 0
Views: 5033
Reputation: 33870
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.
After seeing your code, here how it is interpreted :
storage = {/**/}(function($){})(jQuery);
So Object
({} === Object
) is not a function
Upvotes: 3
Reputation: 160191
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 ;
Upvotes: 1