In Javascript, what does this underscore mean?

JavascriptOopbackbone.js

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

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.

Solution 4 - Javascript

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).

Solution 5 - Javascript

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

Solution 6 - Javascript

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

Solution 7 - Javascript

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).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTIMEXView Question on Stackoverflow
Solution 1 - JavascriptDrStrangeLoveView Answer on Stackoverflow
Solution 2 - JavascriptoliView Answer on Stackoverflow
Solution 3 - JavascriptRyan GibbonsView Answer on Stackoverflow
Solution 4 - JavascriptThiefMasterView Answer on Stackoverflow
Solution 5 - JavascriptJan DragsbaekView Answer on Stackoverflow
Solution 6 - Javascripticc97View Answer on Stackoverflow
Solution 7 - JavascriptBeosFreakView Answer on Stackoverflow