start javascript code with $(function, etc


I guess it makes sense to start out, by realizing that $ = jQuery. The purpose of which down below when reading about namespaces within anonymous functions will make more sense. But in essence, you can use either of them. One would use jQuery() instead of $() if they were using multiple libraries, and wanted the $ to be used by the other one.

    // Here we have jQuery(document) firing off the ready event
    // which executes once the DOM has been created in 
    // order to ensure that elements you are trying to manipulate exist.

$(function () {
    // Short-hand version of $(document).ready(function () { });

More information on Document.ready()

Putting the $ within the parenthesis ensures the jQuery $ alias (you can be safe it always signifies jQuery this way).

$(function ($) { /* code here : $ always means jQuery now */ }); 

Lastly you have an IIFE (Immidiately-Invoked Function Expression) - IIFE explanation

(function (myNameSpace, $) {
    // This is an anonymous function - it is ran instantly
    // Usually used for namespaces / etc
    // This creates a scope/wrapper/closure around everything inside of it
}(window.myNameSpace, jQuery));

The $ at the top (with it's matching jQuery on the bottom) signify that the $ (dollar sign) stands for jQuery within the scope of the namepsace. This is done to ensure that other libraries do not collide with what the developer intends/wants the $ to be used with.

(function (myNameSpace, $) {
    // Now because of all of this scope/wrapper/closure awesome...
    // you can create -INTERNAL- variables (sort of like Private variables from other langs) 
    // this variable cannot be accessed outside the namespace unless it is returned / exposed

    var internalVariable = '123'; // Internal

    // Even Internal functions!
    function privateFunction () {
        console.log('this is private!');

    // --------------------------------------------------------
    // Public -method- of nameSpace exposing a private variable
    // Notice we're using the myNameSpace object we exposed at the top/bottom

    myNameSpace.nameSpaceMethod = function () {
        privateFunction(); // we can call the private function only inside of the namespace
        return internalVariable; // now we could get this variable
}(window.myNameSpace, jQuery)); // notice these mirror the above arguments in the anon function

More information on anonymous functions

Now if we're outside of the namespace, we can see how these internal/public methods and variables are effected:

// This will come up undefined

// This will trigger a -method- of the myNameSpace namespace - and alert "123"
// Showcasing how we access a Public method - which itself has access to the internal variable
// and exposes it to us!

I am studying Backbone and the todo example apps from I have noticed there are 3 severals ways of starting the code in the files:

$(function() {
 // code here

$(function( $ ) {
 // code here

(function() {
 // code here

I do not understand the differences and when I should use one over the other.

I also saw some people using this to start their code:

  // code here

From what I have seen, this is the full way of writing it right?

In a more general way, should I always include my javascript code into something like that in each files?

Thanks for your advice.

(function() { }) and $(document).ready(function() { }) could be used interchangeably and its upto us to choose the one we like. I feel $(document).ready(function() { }) mode readable and understandable when going through code.

this is assigning a function to a variable:

var test = function () { alert('testing'); }
test(); // will alert testing

A function assigned to a variable is also called an 'anonymous function' because it does not have a name, is is often used to pass a function as a parameter to another function.

In javascript, a variable may start with a $, and this is used by jQuery. jQuery is an object, which has properties, one of which is called fn. this property can also have properties, in this case idle.

so $.fn.idle = function () {}; comes down to this:

$ = {
    fn: {
        idle: function () {}

This is also referred to as 'namespacing' although that can have other nuances aswell. Also be aware that the you can only assign properties to existing objects:

var myVar = {}; = {}; // results in error because myVar.test is undefined
myVar.test = {
    foo: {}
}; // this is correct

What is the purpose of a self executing function in javascript?

Its all about variable scoping. Variables declared in the self executing function are, by default, only available to code within the self executing function. This allows code to be written without concern of how variables are named in other blocks of javascript code.

Self-invocation (also known as auto-invocation) is when a function executes immediately upon its definition. This is a core pattern and serves as the foundation for many other patterns of JavaScript development.

I am a great fan :) of it because:

  • It keeps code to a minimum
  • It enforces separation of behavior from presentation
  • It provides a closure which prevents naming conflicts

Enormously – (Why you should say its good?)

  • It’s about defining and executing a function all at once.
  • You could have that self-executing function return a value and pass the function as a param to another function.
  • It’s good for encapsulation.
  • It’s also good for block scoping.
  • Yeah, you can enclose all your .js files in a self-executing function and can prevent global namespace pollution. ;)

More here.

What is the significance of this function definition?

An immediately invoked function expression which aliases jQuery to $ inside its scope:

(function($) {}(jQuery));

It creates and executes a function immediately. This way you can use $ inside the function to reference jQuery regardless of what the global $ references to. Useful for pages using jQuery.noConflict(). Also the variables declared inside that IIFE don't leak to the global scope.

As for the other part of the question, $.fn === jQuery.prototype. So by adding a method to the jQuery prototype, you may call it on any jQuery object. E.g.:

$.fn.doSomething = function(){}; //add a method to the jQuery prototype
$('selector').doSomething(); //then you may call it on any jQuery object

More on jQuery plugin authoring.