88
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?

TIMEX
  • 217,272
  • 324
  • 727
  • 1,038
  • 2
    the underscores have no syntactical meaning, it's probably a convention for that particular programmer to signify the type of the variables – Nate Koppenhaver Nov 27 '11 at 20:29
  • possible duplicate of [Underscore prefix for property and method names in JavaScript](http://stackoverflow.com/questions/4484424/underscore-prefix-for-property-and-method-names-in-javascript) – BuZZ-dEE Jan 06 '14 at 13:03

7 Answers7

167

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.

vinzee
  • 10,965
  • 9
  • 34
  • 51
DrStrangeLove
  • 9,927
  • 15
  • 55
  • 68
  • 4
    at least, the idea of private fields is there, but they aren't really private, you can access them anyway. the author of the above code just meant for them to be private. that's all. – Sander Nov 27 '11 at 23:29
  • Awesome, don't know why it took me so long to look this up! Thanks. – droid-zilla Oct 07 '15 at 18:27
21

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

oli
  • 3,401
  • 1
  • 25
  • 34
  • 3
    I like the link: "Avoid conventions that demonstrate a lack of competence." :-) – Arek Dec 22 '15 at 12:47
  • I use them as shortcuts when debugging, particularly with Promises and other async stuff. e.g. the "official" way to access some attribute of my object might be `myObj.getSmePromise().then( function(o) { do stuff } );` but that's a pain to type at the Chrome console, so I set `myObj._someValue` on the understanding that "proper code" won't actually access it - this is, however, with the luxury of my co-workers also knowing this convention, if you're writing the next jQuery/lodash/angular/react or whatever I wouldn't rely on all your users knowing or respecting this! – FredL Jun 28 '16 at 14:58
8

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.

Ryan Gibbons
  • 3,227
  • 27
  • 31
4

It's probably used to mark internal/private properties. Just like in python prefixing a variable with a underscore is an easy way to tell developers that a variable is internal and they better not tamper with it (and if they do so, even a minor update of the involved library may break things).

ThiefMaster
  • 285,213
  • 77
  • 557
  • 610
2

Usually _ is used to tell the user/programmer that it is a private/protected variable in question.

Jan Dragsbaek
  • 7,746
  • 2
  • 23
  • 45
0

As mentioned, it's a practice among many developers, a bad one at that. If you have to resort to conventions like this in your programming methods then you should learn the language, methods and patterns before attempting to use the language. If someone can't distinguish between public/private methods in your code with out the use of the "underscore", then your documentation skill are extremely lacking. Many of the public projects on the web are very poorly documented which is probably why the "underscore" conventions was "accepted" by most under educated developers while others decided to go with the flow rather than keeping the formal design patterns and methods. There is a reason why "underscore" was not written into ES6/7 versions.

In a blog I recently came across an Software Engineer Manager who stated: "The underscore naming convention makes it really easy to tell, at a glance, whether a variable function is intended to be public or private.". My response is: "Comments are like pictures, in this case they are worth a thousand underscores.

There is a free documentation tool called Doxygen. While it does not specifically support JavaScript, it can generate professional documentation for your JavaScript applications when you use Doxygen prefix's in your comments. It's really simple to create JavaScript applications with documentation, for both developers and users when you put a little effort into your code comments.

Remember, there are tools that can remove comments, and console statements for "Production Releases". That being said, the use of source maps are a waste of time and resources also. Don't minify until your ready to publish.. i.e. Dev Build (no minification, keep comments and console statements), Release Build (remove comments, and console statements and minify the Dev build. No need to recompile the Dev Build when its release quality code, just prepare it for release and deploy it).

BeosFreak
  • 17
  • 1
  • 2
    You won't see a comment unless you're looking at the source code of a function. If you're using somebody else's library/code it adds some value to be able to see the method's intent without reading the source or documentation. Imo the underscore prefix says that it's a non-public API that shouldn't be relied upon. – Sam P Jul 21 '16 at 12:51
0

This is a slight addendum. As already answered these are pseudo private variables. But it is then possible to write pseudo public functions that access these private variables.

I got confused by a colleagues code that effectively has this (but buried very deep in a separate library):

class x { 
  constructor(id) {this._id = id} 
  get id() {return this._id}
}
let y = new x(3)

Now you have both y.id and y._id that work and return the same value. But if you do console.log(y) it only shows up the _id key.

enter image description here

icc97
  • 8,746
  • 6
  • 60
  • 75