[javascript] Underscore prefix for property and method names in JavaScript

Is the underscore prefix in JavaScript only a convention, like for example in Python private class methods are?

From the 2.7 Python documentation:

“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member).

Does this also apply to JavaScript?

Take for example this JavaScript code:

function AltTabPopup() {
    this._init();
}

AltTabPopup.prototype = {
    _init : function() {
        ...
    }
}

Also, underscore prefixed variables are used.

    ...
    this._currentApp = 0;
    this._currentWindow = -1;
    this._thumbnailTimeoutId = 0;
    this._motionTimeoutId = 0;
    ...

Only conventions? Or is there more behind the underscore prefix?


I admit my question is quite similar to this question, but it didn't make one smarter about the significance of the underscore prefix in JavaScript.

This question is related to javascript scope naming-conventions

The answer is


JavaScript actually does support encapsulation, through a method that involves hiding members in closures (Crockford). That said, it's sometimes cumbersome, and the underscore convention is a pretty good convention to use for things that are sort of private, but that you don't actually need to hide.


JSDoc 3 allows you to annotate your functions with the @access private (previously the @private tag) which is also useful for broadcasting your intent to other developers - http://usejsdoc.org/tags-access.html


import/export is now doing the job with ES6. I still tend to prefix not exported functions with _ if most of my functions are exported.

If you export only a class (like in angular projects), it's not needed at all.

export class MyOpenClass{

    open(){
         doStuff()
         this._privateStuff()
         return close();
    }

    _privateStuff() { /* _ only as a convention */} 

}

function close(){ /*... this is really private... */ }

"Only conventions? Or is there more behind the underscore prefix?"

Apart from privacy conventions, I also wanted to help bring awareness that the underscore prefix is also used for arguments that are dependent on independent arguments, specifically in URI anchor maps. Dependent keys always point to a map.

Example ( from https://github.com/mmikowski/urianchor ) :

$.uriAnchor.setAnchor({
  page   : 'profile',
  _page  : {
    uname   : 'wendy',
    online  : 'today'
  }
});

The URI anchor on the browser search field is changed to:

\#!page=profile:uname,wendy|online,today

This is a convention used to drive an application state based on hash changes.


That's only a convention. The Javascript language does not give any special meaning to identifiers starting with underscore characters.

That said, it's quite a useful convention for a language that doesn't support encapsulation out of the box. Although there is no way to prevent someone from abusing your classes' implementations, at least it does clarify your intent, and documents such behavior as being wrong in the first place.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to scope

Angular 2 - Using 'this' inside setTimeout Why Is `Export Default Const` invalid? How do I access previous promise results in a .then() chain? Problems with local variable scope. How to solve it? Why is it OK to return a 'vector' from a function? Uncaught TypeError: Cannot read property 'length' of undefined Setting dynamic scope variables in AngularJs - scope.<some_string> How to remove elements/nodes from angular.js array Limiting number of displayed results when using ngRepeat A variable modified inside a while loop is not remembered

Examples related to naming-conventions

How to name Dockerfiles What is the difference between .yaml and .yml extension? Is there a naming convention for git repositories? What's the name for hyphen-separated case? Should I use "camel case" or underscores in python? Is there a naming convention for MySQL? What is the javascript filename naming convention? REST URI convention - Singular or plural name of resource while creating it What is the standard naming convention for html/css ids and classes? What are naming conventions for MongoDB?