The first example is a closure, it's a design pattern commonly used in JavaScript. In the second one you're calling the $
function giving another function as parameter (jQuery will execute it as soon as the document is ready, since it's an alias of $(document).ready(function () {})
).
This is an example of closure:
(function () {
var foo = 'foo';
var bar = 'bar';
window.foo = foo;
})(); // Those () mean that you're calling this anonymous function
console.log(typeof foo); // Logs 'string'
console.log(typeof bar); // Logs 'undefined', since 'bar' is internal to the closure's
// scope and was not exposed like was 'foo'
And this is an example of $(function () {})
:
$(function () {
alert('Document ready');
});
Check these pages: