JavaScript Naming Conventions – Best Practices and Standards

coding-standardsconventionsjavascriptnaming

I am from Java background and am new to JavaScript. I have noticed many JavaScript methods using single character parameter names, such as in the following example.

doSomething(a,b,c)

I don't like it, but a fellow JavaScript developer convinced me that this is done to reduce the file size, noting that JavaScript files have to be transferred to the browser.

Then I found myself talking to another developer. He showed me the way that Firefox will truncate variable names to load the page faster. Is this a standard practice for web browsers?

What are the best-practice naming conversions that should be followed when programming in JavaScript? Does identifier length matter, and if so, to what extent?

Best Answer

You will find that the developers themselves are not using short variable names. Whilst developing, they are using meaningful and detailed variable names.

Then, in the build/release process, the code they've written is ran through a minifier/obfuscator with the intention of minimizing the size of the file, as a best practise to speed up a website. This is an optional step if you care that much about performance. Most small websites don't do this.

You, as a developer, should not care about the minification/ obfuscation process; write your code so that it is readable, meaningful, well documented and well structured. Then if you care so much about performance (optional, don't forget!), introduce a minifier/ obfuscator into your release process to minize the code (remove white space, new lines, comments etc) and to obfuscate it (e.g. shorten variable names). A good article which explains obfuscation vs minification can be found here.

Additionally, Desktop FireFox will not truncate variable names period. The truncation of variable names is there to speed up the page download. By the time FireFox gets the file, it has already been downloaded therefore there is no need to do so. Your friend may run a plugin which is doing this; in which case, tell him to uninstall it, because it's useless.

For completion, some (mobile) browsers have the option to use middle-man servers, which intercept the responses of resources you requested, and compress them for you (which could include the minification of JavaScript files). Note that the compression is done on the server (i.e. before you have downloaded the page), hence the potential benefit of downloading a smaller file, rather than in the browser once you have already downloaded the file (as suggested in the question). Such mobile browsers include Opera Mini, and newer versions of Google Chrome (on iOS at least; not sure about Android). For more info, see here.

Related Topic