In Javascript, what does this underscore mean?

var Gallery = Backbone.Controller.extend({
    _index: null,
    _photos: null,
    _album :null,
    _subalbums:null,
    _subphotos:null,
    _data:null,
    _photosview:null,
    _currentsub:null,
    routes: {
        "": "index",
        "subalbum/:id": "subindex",
        "subalbum/:id/" : "directphoto",
        "subalbum/:id/:num" : "hashphoto"
    },
    initialize: function(options) {
        var ws = this;
        if (this._index === null){
            $.ajax({
                url: 'data/album1.json',
                dataType: 'json',
                data: {},
                success: function(data) {
                    ws._data = data;
                    ws._photos =
                    new PhotoCollection(data);
                    ws._index =
                    new IndexView({model: ws._photos});
                    Backbone.history.loadUrl();
                }
            });
            return this;
        }
        return this;
    },
    //Handle rendering the initial view for the
    //application
    index: function() {
        this._index.render();
    },

I'm reading a tutorial on backbone.js here: http://addyosmani.com/blog/building-spas-jquerys-best-friends/

What are the underscores? (_index, _photos, _album) Why use them?


Solution 1:

It means private fields or private methods. Methods that are only for internal use.

They should not be invoked outside of the class.

Private fields contain data for internal use.

They should not be read or written into (directly) from outside of the class.

Note: It is very important to note that just adding an underscore to a variable does not make it private, it is only a naming convention.

Solution 2:

As far as I'm aware, it's generally used to indicate a private variable (but doesn't actually provide any privacy, just a convention).

It's discussed briefly here, though they're advised against: http://javascript.crockford.com/code.html

Solution 3:

When used like _varname it's just part of the variables name, and has no javascript meaning. Developers use it to signify the meaning or scope of the variable. In this case it looks like it is telling the developer this variable should be a local or private variable.

A few things to note, in this particular example using _.varname would signify a variable or function with the underscore.js library. Also one could use _varname to signify a variable holding an underscore object, similarly at our office, we use $varname to signify a variable containing a Jquery object.