While most of the popular languages (Java, .NET, C++) have elaborate documents on the naming conventions to follow, I couldn't find any such good document for javascript. All I could find was bits and pieces here and there. This is the main reason why I am creating this page listing the javascript naming conventions I follow. This may not be complete but I shall try to make it as comprehensive as possible.
1. All variables should be prefixed with a letter indicating the data type of the variable (Hungarian notation). These would be as below:
s - String
n - number
b - boolean
a - Array
o - object (Native Objects, Host Objects and user-defined objects)
Further, the first letter of each of the words should be capitalized.
Ex:
var sSampleText = "Hello";
2. Apart from this a letter indicating the scope of the variable should also be prefixed. This will help in differentiating the local variables from the global variables.
g - global
m - All member variables (private and public)
Ex:
var gsSampleText = "Hello";
3. Further all private member variables and methods of classes should be prefixed with _ to distinguish them from public member variables (Please note that the arguments of a constructor and all the variables initialized inside the constructor are actually private members of the object).
Ex:
function Person(_msFirstName, _msLastName) { this.msFirstName = _msFirstName; this.msLastName = _msLastName; }
4. All class names should be a combination of words with the first letter of each word capitalized.
Ex:
function XmlParser() { // Do something }
5. The function names and method names should also be a combination of words with the first letter of each word capitalized except for the first word. Function and method names should generally indicate the action they are meant to perform. It is a very common practice to begin functions with get/set/is word depending upon whether the function is returning a value, setting a value or returning a boolean result.
Ex:
function Animal(_mnAge) { this.getAge = function() { return _mnAge; } this.setAge = function(nAge) { _mnAge = nAge; } this.isAgeValid = function() { if (_mnAge < 0) { return false; } return true; } } function doSomething() { // Do something }
Apart from the above mentioned naming conventions, I also follow the below coding practices.
1. All statements should end with a semicolon.
2. Comments should be used properly. Every function and method should being with a comment indicating the action to be performed by it. Every logic should be commented properly.
3. Use single quotes for javascript literals and doubles quotes for HTML element attribute values. While this is not reallly necessary it makes it easy and consistent to write javascript code in-place within event handlers as well as html text in javascript code.
Ex:
HTML snippet: <a href="http://www.google.com" onclick="alert('You will be redirected to Google');" /> Javacript snippet: divElement.innerHTML = '<input type="text" name="age" id="age"/>';
4. For inline javascript (no need for js written in external file), make sure it does not cause a problem when validating the page for XHTML compliance. This can be achieved by writing the javascript code as shown below.
<script type="text/javascript"> //<![CDATA[ /* Your javascript code -- variables, functions, classes and everything else */ //]]>
As far as I remember, this also hides the javascript code from old browsers.
6. Follow proper indentation
Indentation should be consistent. Use an indentation length of 2 or 4 spaces.
Ex:
if (sAge != null) { if (!isNaN(sAge)) { if (parseInt(sAge) > 0) { return parseInt(sAge); } } }
References:
http://www.peachpit.com/articles/article.asp?p=24273&seqNum=5&rl=1
http://www.sitepoint.com/article/oriented-programming-1
http://www.crockford.com/javascript/private.html
http://www.irt.org/articles/js169/index.htm
Comments
Thanks for the post. I
Thanks for the post. I couldn't find a document regarding javascript naming conventions, either.
Oh, I forgot...
These prefixes:
'e': Event (for on* events)
'n': Node/Element (for handling DOM nodes/elements) [wich are technically objects, but then, almost everything is technically an object]
I agree with some of your points, but not all of them.
Oops, something went wrong. Here's my full reply:
While I do agree with some of your points, I do not agree with all of them. I've seen some bad code in my life, and not only in the JavaScript language. However, when someone (usually a classmate) asks something about his or her code (they are good at other stuff, I'm good at coding) I usually give it a glance and come up with one or more of the following:
1) I agree about the variable prefixes. Though JavaScript is loosely typed, forgetting what type a variable should be, could create all sorts of nasty critters in your script.
Your prefixes:
'n': Number
's': String
'a': Array
'o': Object
'b': Boolean
However, you forgot a few:
'f': Function (for callback)
'v': Variable (for accepting multiple types)
'e': Event (for on* events)
'n': Node/Element (for handling DOM nodes/elements)
2) There is no excuse for old-style global variables.
If you put your functions in one (or a few) objects with good, descriptive and relatively unique names, you can access your functions like: 'foo.bar();' or 'foo.bars.get();' and it's relatively hard to interfere with other scripts (added in the future, perhaps).
Also, if one or more variables are needed by different functions, attach them to your master object, etc 'foo.variableobject = {};' instead of 'document.variableobject', wich it would get attached to otherwise. The only name that should be visible from the document level is the name of the object containing the functions; in this example: 'foo'.
As such, there is no real need to differentiate between global or local variables using a 'g' or 'm' prefix, since you always call global variables with the prefix 'foo.' and local variables as is.
There are ways to make functions inside an object private (by putting it inside a function object and immediately calling it), but that makes an unreadable mess of the code.
And it's not needed: If a function that's called by another function must never, ever be called outside of the function's scope, then usually (but not always) there is something wrong. In such a case, you should refactor the offending code instead of making the function private by prefixing it with '_'.
However, there is a case where I could see it useful: if you declare a 'initialization' function (or something similar) and need to run it immediately. In such a case, it could be unwise to have it possibly be called again in the script by some intern, so you could notate such a function like this:
var lib = {
_init: function() {
// code here
}()
};
Call it, and it will auto-selfdestruct. In such a case, it's a good idea to prefix it with '_', because without further work, it will still show up in the dom (with the value 'null'). Do remember, however, that the 'lib' object isn't accesible yet since it hasn't fully been parsed yet. I believe you can access the functions above (that have been parsed) by using the 'this.' keyword, but I'm not completely sure about that.
3) On the same token, variables should -of course- always, always be initialized before using. But I'm sure you agree.
4) I disagree with you on the third point; the capitalization of the first letter: 'Foo();' is usually used exclusively on Constructors: 'var x = new Foo();'. To use it on class names as well may confuse things. If you really need to differentiate, use the prefix 'c' for classes.
5) In a project where object notation is not possible (eg: a large, existing project you need to do maintenance on), I wholly agree with CamelCasing the functions names. It's more readable then using underscores (eg: 'CamelCaseName' instead of 'camel_case_name'). However, when using object notation, it is not needed, provided you use short, descriptive names:
var lib = {
age: {
get: function() {},
set: function() {}
},
address: {
get: function() {},
set: function() {},
merge: function() {}
}
};
Since you need to access the functions by object notation, it's clear what they do: 'lib.age.get();' gets an age, and 'var result = lib.address.merge(one, two);' merges two addresses into one and passes the result back.
6) As for the rest: I agree with you, but single quotes is not necessary. Personally, I use double quotes, but single quotes are just as good. There is no real speed difference between the two (it's not PHP you know!). HTML manipulation should be done through the DOM, so you don't need to escape anything (usually). However, wichever you choose, single quotes or double quotes, do use them consistently throughout a script.
7) A CDATA tag is usually not needed, since inline scripting is bad practice anyway. Always use external JS files. In the case that you really can't, you don't need a CDATA tag either, since browser that don't support javascript have been dead for the last 10+ years (Netscape 4, anyone?). In the case of XML, the CDATA tag is indeed necessary. In that case, use it.
8) When working alone on a project, indentation doesn't really matter. But when there's a possibility of one or more other developers coming on board on the project, it becomes essential. Everyone has his or her own style and the only way to facilitate that is to use tabs. Most editors can't (reliably) convert 2 to 4 spaces or 4 to 6 or whatever the developer's preference is. They can, however, convert a tab to exactly the amount of spaces the developer wants, and save them back as tabs.
This way, the code is easily readable and editable for every developer, even though some might use one space, 6 space or 256 spaces as indentation.
I believe (it has been some time since I've viewed code that way) that it does make matters more difficult if you view the code in a linux text editor (for example through putty on a live server), but in real-world situations such old-school methods aren't neccesary. This is also the reason that a 40 character line limit is not done nowadays. Don't rape up your functions and contenate substrings because you really need to stay within those 40 characters, it makes code unreadable in modern editors.
9) Functions should have no space after the function name and before the '()'. When calling a function, however, there should be a space.
If/else loops, for loops, etc. should always have a space before the '(' and after the
')'. In both functions and loops, the trailing '{' should be on the same line, and the closing '}' should be on the start of a newline, at the same indentation as the declaration.
This way, constant variables inside the function can be 'hung' on the top of the function (without a empty line first), and a 'return' or 'throw' can be fixed to the bottom of the function. If there is no 'return' or 'throw' at the end of the functions, the last line should be an empty one (except for the indentation, ofcourse). It's the same with the first line if there are no global variables used in the function.
This increases readability about what a function does and if it does or should return a value or not.
10) Documentation should not be used sparingly. However, the words that make up the documentation should. I've seen code where a wannabe-pocketbook-writer declared a 50-line commentblock for a simple 'alert();'. Really. I'm not kidding here.
It's best to generate documentation with appropriate tools (there are a few available, search google for 'em) and/or write documentation in that style. This way, it can be machine-read, parsed and you can do all kinds of nice stuff with it (generate diagrams, a help library etc).
Hoewever, the documentation comments should be in a block, like: '/** whatever **/'. If you need, for whatever reason, additional documentation inside the function, always use '// whatever' lines after the line number you are writing about (with a space between it and the comment ofcourse). But please, do use these sparingly.
If you need a 'post-it note' from yourself to yourself (about eg. something you really need to change today) and your desk is full ;), then use a '/* NOTE: whatever */' styled commentblock. If you temporarily edit out a code block, then also use the '/* */' style tags. Most editors display these in a different color then the regular '/** **/' blocks (or you can set your editor to).
11) Nowadays, most Javascript developers without expensive integrated IDE's (I like the lean Notepad++ myself) need a way to debug their JS and easily traverse the DOM. The answer has come (atleast for Gecko variants) in Firebug. I agree with others that it's a wonderful plugin for Firefox, but please, Please don't forget to remove 'console.whatever();' calls when deploying the software (or atleast use a 5 lined Firebug Lite script to reset those commands to empty objects). I have seen web applications break and abort on simple 'console.log();' commands, since Firebug is usually not installed by the end-user.
You don't want anything related to debugging in your deployed application!
12) Instead of using old-style Constructors, use literals wherever possible. This increases readability a thousandfold. For example, dont do this:
var newfunc = new Function() {};
var newobj = new Object() {};
var newarr = new Array() [];
var newreg = new Regexp("");
Instead, do this:
var newfunc = function() {};
var newobj = {};
var newarr = [];
var newreg = //;
This counts in particular for regular expressions. Regular Expressions are good. Regular Expressions are fun. But, as said above, use the object literal!!
When you get to sufficiently complex regexp functions -in a application you barely know- and you need to understand the regular expressions used, you really don't want to struggle to all escapes because someone used the string method to instantiate the Regexp object: 'var foo = new Regexp();'. When you use the literal: 'var foo = /regexphere/', it's much more readable.
13) Generating code on the fly is a bad idea. Eval(); is a bad idea (except for JSON operations). Generating code from pre-regexped strings, regexping them on the fly back to a readable piece of code and eval()ing that code is a horrendously stupid idea. I've seen someone do it once. He defended himself with: "I don't want anyone seeing my code". Ugh.
If you really need to hide your code before deployment, use an obfuscation (and usually compression) tool. This has the added effect of minimizing the kB footprint of your code.
But when you program in javascript, you should realize your code is always visible, even if it is obfuscated, because it's interpreted at run-time. It's the nature of the beast, and if you don't like it then don't code in JavaScript!
A few simple search and replace regexps and a minimized piece of code is back to something readable (even if the function names and variables are named 'aa', 'ab', 'ac' etc).
14) It's generally not a good idea to extend the default structures. Yes, object doesn't have a '.merge();' function, but that doesn't mean you should put it in there. It's quite possible (even very likely!) other scripts may break. This counts in particular for objects! Almost everythin in JavaScript is an object; it isn't a 'object oriented language' for nothing. If you tamper with the base Object, you tamper with the whole foundation of the language. Not a good thing.
If you really need a 'object.merge();' function, make a function in your library object, like: 'lib.object.merge();'. It isn't that much different in syntax, but atleast you show respect for the language and play nice with other scripts.
That goes for anything, ofcourse. Keep it in your library object!.
Well, uhm, that's how I think about it... *grin*.
Oh, one last thing:
15) Any if/else, for etc. blocks must have curly braces! This way you avoid bugs when developers add a line to the statement without checking if the curly braces exist (and thus generate an error; without curly braces, only one line is valid in the loop).
And, ofcourse, don't rely on auto semicolon insertion to do the job for you. This makes for some of the most nasty to track bugs there are. Just do it yourself, it isn't that hard. The button can use a little pressing now and then;;;;;; :)
Hmm, now that i read it...
... my post does seem a bit... preachy. But it wasn't meant that way. :)
It's just horrible that JavaScript is always mentioned in the same sentence as the words 'foul' 'soup' and 'messy', usually by people who code without any conventions.
So yeah, thumbs up for your article. Everybody who uses JavaScript in a strict, sensible way is a good person in my book.
Guidelines
Since you posted this on my actual birthday, here's a present (or maybe not, who knows) :-) Some time ago, I published the JavaScript guidelines that we use in one of our big ASP.NET projects. They may not totally match what you write here (I didn't check explicitly though), but they are what we used, and each and every one of them was carefully discussed and reviewed by experienced programmers, so they may help.
I agree that JavaScript is a great language, and needs guidelines!!
http://www.galasoft-lb.ch/myjavascript/Siemens_SBT_JavaScript_Coding_Gui...
Greetings,
Laurent
hi raul ! can i translate this document to korean?
hi raul.
i really agree with your Trys.
i want make korean javascript dev guide line for me or for our company.
and i want research guide lines .
can i translate this document to korean? if you approve , i'll send the url.
thanks.
Hi Jason, please feel free to
Hi Jason, please feel free to translate it to any language you like. The whole purpose of writing this article is that it could be of use to others. Also I'd appreciate it if you could link your translated article from here so that more users can reach it.
Hi Rahul , Thanks your approve. document translated.
Thans Rahul. I translated to korean. here is the link http://www.m3ant.co.kr/devguide/javascript-naming-conventions.html
Every time in developing , i think that why everybody do make same logic different languages in same language. We have to something to prove this dilemma.
1)how to convert the two date
1)how to convert the two date into a day?
Types in naming convention, what?
I can always tell someone who's never really programmed in a dynamic (not "loosly", whatever that means) typed language. They look for all sorts of ways of assigning a type to a variable. I've seen variables with the type they want in them (userNameString, ageInteger), I've seen, like you've done, with prefixes (sUserName, iAge); all attempts to make the dynamic language be more like the language they'd prefer to be using (usually Java, VB, or c#).
What you need to understand is type isn't important in a dynamically-typed language, like it is in a statically typed language. If your method/function needs the user name, which you will display as text to the user, why do you care if it's a string or not? Why this obsession with the type? All you care about is that it can become a string when needed; so you care about the interfaces the object responds to, not what type it is, or more specifically the methods it has.
The power of a dynamically typed language has nothing to do with the fact that you don't have to type the "type", but rather its ability to allow objects to automatically implement interfaces, to be dynamically changed at runtime, meta-programming, and the ability to use either prototype or class-style structure.
Look at any of the advanced javascript libraries (jQuery or prototype for examples), and you'll see it doesn't look just like Java but with var instead of int. It's a totally different paradigm, one that is very powerful, and worth the time to learn correctly.
So please, leave the type information off of the variable names, you're making the Ruby/Python/Perl/Smalltalk/Javascript people laugh at you.
Beware of errors and misconceptions in this entry
Mr. Amaram
I read with attention your entry and can't help highlighting some misconceptions or bad practices:
1. Hungarian Notation
1.1 I've seen source code from major JavaScript frameworks (Dojo, YUI, Jquery, etc.) and none of them uses Hungarian Notation.
1.2 Is strange to see Hungarian Notation in a dynamic typed language, it is simply not used in popular dynamic languages like Perl, Python, Ruby.
1.3 As most people do, the author misses the point about the purpose of Hungarian Notation. Cf. http://www.joelonsoftware.com/articles/Wrong.html
2. More Hungarian Notation
2.1 Ditto.
3. Private members
3.1 The example is misleading, private members are not accessible from the outside, and in the code the private members are passed as parameters.
3.2 Prefixing a name with an underscore doesn't turn it automagically in a private member. Please read http://javascript.crockford.com/private.html
4. Prefixes
4.1 Again, an incorrect use of the prefix for private members.
4.2 In JavaScript is not a common practice to prefix with get, set and is. This wordy way is a common practice in Java, because the language lacks true properties. Even the Dojo Style guide warns against this practice unless a private member is involved.
http://dojotoolkit.org/developer/StyleGuide#Specific_Naming_Conventions
5. Inline JavaScript
5.1 It is well documented by the standards body why it is common for scripts to fail when validating, and the best practice is not the recommended in your blog entry. See:
http://validator.w3.org/docs/help.html#faq-javascript
http://www.w3.org/TR/xhtml1/#C_4
5.2 In ancient times, the way to hide scripts from prehistoric browsers was using a combination of HTML and JavaScript comments.
Regards
Javier Castañón
Feedback on comments
It has been long since I had posted this article. It surprises me that my page is the first to turn up in google today when searched for "javascript naming conventions" or "javascript naming standards" (considering the fact that this was written only to help a few colleagues of mine to follow a common standard and hence is not as comprehensive as the coding standards for other languages).
I am really happy that this article has received so many comments (some supporting it and some against it). Either way I think it is good because it helps those programming in javascript to take a better decision (though it might also add to their confusion :)).
I do not have the time to reply to all of the comments. So I will just talk about the most debated topic - the Hungarian Notation.
One needs to understand the difference betwen statically/dymanically typed and strongly/weakly(loosely) typed before I can justify why I had used the Hungarian Notation. Referring http://diveintopython.org/getting_to_know_python/declaring_functions.html:
statically typed language: A language in which types are fixed at compile time. Most statically typed languages enforce this by requiring you to declare all variables with their datatypes before using them. Java and C are statically typed languages.
dynamically typed language: A language in which types are discovered at execution time; the opposite of statically typed. VBScript and Python are dynamically typed, because they figure out what type a variable is when you first assign it a value.
strongly typed language: A language in which types are always enforced. Java and Python are strongly typed. If you have an integer, you can't treat it like a string without explicitly converting it.
weakly typed language: A language in which types may be ignored; the opposite of strongly typed. VBScript is weakly typed. In VBScript, you can concatenate the string '12' and the integer 3 to get the string '123', then treat that as the integer 123, all without any explicit conversion.
Javascript is a dynamically but weakly typed language unlike Python which is a dynamically and strongly typed language. I think the above definitions adds some sense as to why I preferred using Hungarian notation. For ex. if I am adding two variables and let us say one of it is a string and the other a number, then in a programming language like Python it throws an error (and this is what I expect to see). But in javascript it just treats the number as a string and concatenates it to the other string.
Anyway, I do not deny the fact that Hungarian notation has its own set of disadvantages. Here is an interesting post arguing against Hungarian notation - http://www.nczonline.net/blog/2006/11/01/the-case-against-hungarian-nota.... Also Joel Spoelsky wrote an interesting article on Hungarian notation saying that the Hungarian Notation which was invented and popularized by Microsoft programmer Charles Simonyi was Apps Hungarian and not Systems Hungarian (the one I have used above is Systems Hungarian). Here is the link to his article - http://www.joelonsoftware.com/articles/Wrong.html. For understanding the difference between Apps Hungarian and Systems Hungarian and knowing opinion of some famous people on it, you might refer http://en.wikipedia.org/wiki/Hungarian_notation.
Finally the choice of whether to use Hungarian notation or not is left to the developer. But I do agree that Hungarian notation (especially Systems Hungarian notation) seems to become more and more unpopular and after working with Python and Dojo, I really doubt if I'd like to code in Hungarian notation again :).
Fanfabulous, I've been
Fanfabulous,
I've been looking for something like this. It will make it easier to make a quick guide for coding Javascript - good work!
Add new comment