In my latest JavaScript projects I’ve tried to omit the semi-colon (;) on line endings. Why? I don’t know, because I can? I’m not going to go into a deep discussion about this subject here but rather warn others who follows this practice. I do have a solution at the end though so don’t give up just yet!
The following code (in Firefox 21.0) yields a null is not a function error message in Firebug.
var foo = null
(function($) {
// Do something
})(jQuery)
Notice the lack of a semi-colon when defining the variable “foo”.
The following code parses just fine:
var foo = null;
(function($) {
// Do something
})(jQuery)
Apparently the parser believes I’ attempting to run null as a function, ergo it thinks I want to do this:
var foo = null(function($) {
// Do something
})(jQuery)
Solution
What I suggest is to always start a closure with a semi-colon (as seen in the code below). This guarantees that you won’t run into this issue in the future. Of course, if you always end statements with semi-colons then nevermind..
var foo = null
;(function($) {
// Yay, it's working
})(jQuery)
Happy coding 🙂