Here's my reply, edited a little, to a recent code review where I got taken to the woodshed for using the underscore prefix for private variables in es5 JavaScript code used in an AngularJS project.

Stick around until the end. Spoiler: A, um, widely recognized AngularJS style guide author agrees with me.

The john papa style guide allows them.

"disallowDanglingUnderscores": null,

An underscore prefixed to a variable means the items are intended purely for internal use. They should not be directly exposed.

Here's a good sum from a StackOverflow answer on the underscore convention:

[An underscore prefix] 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.

That's an important distinction for me. If I have side-effects for specific calls that I don't want to expose to a consumer, I want to ensure those things are "hidden" (not exposed outside of the file's scope). This helps me both declare and double-check that.

I don't have to do it, but it's not random and it's not a made up practice.

Your TypeScript reference is Google's (as in not Microsoft's). Nothing inherently wrong with that, but, um, why?

Though I disagree with some of the stuff already (there's nothing wrong with interfaces starting with I. Fight me ;^D), I can see why you wouldn't use _ in TypeScript -- TypeScript has a concept of and enforces that concept of private fields.

https://www.typescriptlang.org/docs/handbook/classes.html#ecmascript-private-fields

For example, if I want _myProp to be private, I just say so: private: myProp. That's a little different than my usage here, but you can twist it into the same thing.

Make sense? My point here isn't that I can't remove the _ if it's driving the team crazy. The point is that there is a clear reason to use it, and it is a popular, useful convention.


Fun update: John Papa from 2016 says exactly the same thing as me:

johnpapa commented on Mar 28, 2016 โ€ข

I don't like underscores personally ... but since there is no real private nor public in javascript, it is very helpful to have a way to differentiate them. So I use them

UPDATE: i was referring to ES5 ... with Typescript I don;t use underscore

I'm biased, but well said.

Though, again, this is why I hate working in dated codebases. The code doesn't rust, but it kinda feels like your career is stuck in an episode of Doctor Who.

Labels: , ,