257

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.

Community
  • 1
  • 1
Kenny Meyer
  • 7,076
  • 6
  • 42
  • 62

6 Answers6

266

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.

Frédéric Hamidi
  • 240,249
  • 39
  • 455
  • 462
  • 5
    Yup. Even if the language doesn't "support" it, it's a really handy convention to have. – Juho Vepsäläinen Dec 19 '10 at 18:47
  • Serious prob. http://jsfiddle.net/VmFSR/ As you can see there, value created name is only accessible by prefixing new value, created, using `_` i'd love to know what's going on!? why it is not `this.name` instead? – Muhammad Umer Jul 26 '13 at 23:14
  • 1
    @Muhammad Umer, I'm not sure I understand your comment. `console.log(someone._name = "Jean Dupont");` works as well as `console.log(someone.name);`, and it both assigns and evaluates the underscore-prefixed member behind the property. [As you can see](http://jsfiddle.net/VmFSR/1/), theres is no guaranteed encapsulation through underscores :) – Frédéric Hamidi Jul 26 '13 at 23:25
  • wow i totally missed the part that mere assigning of a value is enough to declare something. My bad. Thanks for pointing out i was going crazy. :D – Muhammad Umer Jul 26 '13 at 23:35
  • 3
    By default, Visual Studio try to help you respect this. The javascript IntelliSense engine show you "private" properties, from inside the object, when using the "this" variable. But, when called from the outside, it hides all underscored attributes. – foxontherock Dec 17 '15 at 19:30
  • It appears the language now supports this. See [answer](https://stackoverflow.com/a/56205859/6448384) below. – Karuhanga May 19 '19 at 08:05
  • 1
    @Karuhanga he answered this back in 2010 - of course things have changed in 10 years – Kenny Meyer Jul 15 '19 at 14:40
101

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.

Bob Stein
  • 12,526
  • 8
  • 72
  • 91
Zach
  • 6,942
  • 3
  • 19
  • 26
  • 21
    Up vote for clarifying how to achieve closures, down vote for saying underscores are good convention. So I won't vote either way :) – Jason Jun 17 '11 at 03:14
  • 3
    Hiding members in closures can sometimes hinder testability. Check out this article: http://www.adequatelygood.com/2010/7/Writing-Testable-JavaScript – Zach Lysobey Feb 05 '13 at 18:46
  • 5
    @Jason - Just curious, why you consider underscore a bad convention? – Tamás Pap May 21 '13 at 14:57
  • 5
    @TamasPap - A few reasons, but just my option: 1) A crutch to force JS into a style of other languages 2) If it's accessible, it will be used. The underscore can litter up and convolute outside code. 3) Confusing to new JS programmers. – Jason Jun 05 '13 at 02:38
  • 2
    @Jason Well obviously private is accessible in all languages, why is that a downside? – Esailija Aug 14 '13 at 22:59
  • 10
    Even with a closure, it's still *technically* possible to gain access to the so called "private" variable. The _convention at least lets devs know to do so at their own risk (or something like that). – sarink Dec 05 '13 at 05:24
  • @KabirSarin *technically* speaking, how exactly do you access a private variable (var declared in a closure) from outside the closure? It's my understanding that you can't, unless you inherit scope (which you won't, even in methods that are part of the func/object's prototype. – Vince Jul 29 '14 at 15:19
  • 3
    @Sorenly, a hack like this https://gist.github.com/sarink/7394867 is always possible. you could guard against it in a framework, of course. but if someone can see the source, surely they could figure out a way. – sarink Jul 30 '14 at 13:27
  • 3
    "... things that are sort of private , but that you don't actually *need* to hide." ...or things that you'd like to be private, and also inheritable. Variables in closures are not inheritable AFAIK. – trusktr Oct 26 '14 at 01:20
  • 1
    @trusktr, ah, *protected* then :) – Frédéric Hamidi Nov 20 '14 at 21:38
  • @FrédéricHamidi Yeah, protected. :D There's no way to do it in JavaScript as far as I know (is there?). – trusktr Nov 23 '14 at 23:31
  • 3
    @Jason if you've ever programmed with many people, you would understand why it's a good convention. Traditionally, it means something is *private*, but in JavaScript it could also mean, *be aware, this could change, so you should probably write your own method/function that may be more stable*. What you're trying to avoid (and convey to fellow developers) is that it may change in the future, and you aren't going to maintain it for backwards compatibility; meaning it's up to them to fix their stuff if it breaks their code. – vol7ron Mar 07 '16 at 15:40
  • @KabirSarin that example is allowing a person to set a *key*, which could be called by another method (in this case the key is *push*). It's more poor programming, than private/public exposure and not something that's ***always*** possible. If `_array[_array.length]=v` was used in *append* -or- if key validation was used in *store* preventing the use of *push* (e.g., `if(i!=='push')`), it would not be an issue in that example (https://gist.github.com/sarink/7394867). Private methods can still affect global scoped variables, even in other languages. – vol7ron Mar 07 '16 at 16:02
47

Welcome to 2019!

It appears a proposal to extend class syntax to allow for # prefixed variable to be private was accepted. Chrome 74 ships with this support.

_ prefixed variable names are considered private by convention but are still public.

This syntax tries to be both terse and intuitive, although it's rather different from other programming languages.

Why was the sigil # chosen, among all the Unicode code points?

  • @ was the initial favorite, but it was taken by decorators. TC39 considered swapping decorators and private state sigils, but the committee decided to defer to the existing usage of transpiler users.
  • _ would cause compatibility issues with existing JavaScript code, which has allowed _ at the start of an identifier or (public) property name for a long time.

This proposal reached Stage 3 in July 2017. Since that time, there has been extensive thought and lengthy discussion about various alternatives. In the end, this thought process and continued community engagement led to renewed consensus on the proposal in this repository. Based on that consensus, implementations are moving forward on this proposal.

See https://caniuse.com/#feat=mdn-javascript_classes_private_class_fields

Karuhanga
  • 1,781
  • 1
  • 18
  • 25
15

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

Pablo
  • 77
  • 1
  • 7
philrabin
  • 759
  • 2
  • 10
  • 20
10

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

Kenny Meyer
  • 7,076
  • 6
  • 42
  • 62
Sam Araiza
  • 346
  • 5
  • 11
8

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... */ }
Nicolas Zozol
  • 6,609
  • 1
  • 46
  • 66
  • I don't think that import/export offers support for private class methods in any way. I mean, it does support a similar functionality on class level, but it does not offer hiding the contained methods. (i.e. all contained methods are always public) – bvdb Oct 11 '18 at 09:17
  • 1
    You export the class, and inner function call outside function. These functions are privates. – Nicolas Zozol Oct 15 '18 at 07:06