What is both the naming and formatting standard for global variables in JavaScript?
For example:
var global_var // ?
var _global_var // ?
var GLOBAL_VAR // ?
var _GLOBAL_VAR // ?
...
Note: I am NOT talking about constants, just simply variables that have global scope.
There are no standards as such. The most common practice is to use lower camel case (e.g. var fooBarBaz;
) for all variables and property names, irrespective of scope, but this is by no means universal. The only exception is to capitalize the name of a function that is intended to be used as a constructor:
function SomeClass() {}
var someClassObj = new SomeClass();
I've also seen block capitals and underscores used for variables that the author considers constants, or alternatively for all global variables:
var EARTH_RADIUS = 6378100;
Another reasonably common convention (although not one I use myself) is to prefix properties of objects that author wishes to be considered private with an underscore:
this._leaveThisAlone = "Magical property";
Douglas Crockford published his own take on JavaScript code standards several years ago that covers most of this, but as ever this is just one man's opinion, so take with a pinch of salt.
The requisite comment about rethinking the design if you're needing to use global variables, blah blah...
The global variables I've seen are normally prefixed with g
or gbl
. Sometimes this is modified with an underscore: _g
, _gbl
. IIRC, the underscores were used when 'global' was confined to some scope and not 'truly' global.
If you are going to use a global variable in a fashion where EVERYTHING shouldn't be able to use the variable, I'd go with using the underscore. In javascript (IIRC) the convention of using an underscore as a prefix implies that the variable is 'private' or shouldn't be used externally. If you are, alternately, declaring it in a fashion that everyone should be able to access and modify then I'd go with just the prefix and no underscore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With