Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this syntax? ; (function ($, undefined) [duplicate]

; (function ($, undefined)
{

    // all the variables and functions of the js document

})(jQuery);

I've seen this twice now in the jquery/javascript files for a zoom script. I don't understand what this is exactly. I can't seem to google it, I don't remember coming across this on tizag or w3schools while recently learning jquery and js.

There's nothing before or after this code (other than some comments). So I'm utterly lost as to what (function())(jQuery); is or does.

like image 349
Eric Avatar asked Apr 19 '13 12:04

Eric


People also ask

Why is function undefined JavaScript?

A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .

What is undefined error in JavaScript?

Undefined means that a variable has been declared but has not been assigned a value. In JavaScript, properties and functions can only belong to objects. Since undefined is not an object type, calling a function or a property on such a variable causes the TypeError: Cannot read property of undefined .

Why is my array undefined?

You get undefined when you try to access the array value at index 0, but it's not that the value undefined is stored at index 0, it's that the default behavior in JavaScript is to return undefined if you try to access the value of an object for a key that does not exist.


2 Answers

(function ($, undefined)
{

    // all the variables and functions of the js document

})(jQuery);

calls a block of code ensuring that inside

  • $ is usable to refer to jQuery
  • undefined is undefined (edit: this was useful because undefined could be redefined at that time in the oldest browsers, it's now useless)

and that any minifier can change undefined to a shorter label.

The initial ; ensures you can concatenate this file with another one : without this, you'd have an error executing the concatened file if the one just before was something like

(function (){

})()
like image 100
Denys Séguret Avatar answered Oct 05 '22 23:10

Denys Séguret


This is a way to ensure that $ is indeed the jQuery object and to ensure that any local variables and methods are privately scoped, that is, do not pollute the global namespace.

It is a self-calling anonymous function, with the parameter passed being jQuery, meaning that the $ will be the jQuery object.

Being declared inside a function means that the inner variables and methods will not be visible outside of it.

like image 23
Oded Avatar answered Oct 06 '22 00:10

Oded