Best Practices JavaScript Coding
One of the strengths and unfortunate weaknesses of JavaScript is its easy, almost casual structure and rules when compared to some more formally structured languages. This makes it very welcoming to newcomers to programming but it also makes developing bad habits very easy. I know I’m personally guilty of several of these, whether out of early endeavors, quick/dirty updates or just going with the flow of pre-existing code. However, this will come back to haunt you and the longer you avoid learning and using best practices, the harder it will be to correct these habits. The following are some of the basic issues you should be aware of and try to follow.
Naming Conventions
Although you are officially only required to use numbers, letter, underscores, the dollar sign and NOT start a variable name with a number, following only these bare minimums can lead to some ugly and unintuitive names. Basic best practices for naming convention:
- Use camel case for readability and add additional context to names: bestPractices, checkBalance, mapLocation
- Avoid underscores. Although this is pretty common some other programming languages, it isn’t in keeping with JavaScript’s inherent naming structure.
- Implement noun and verb format to provide additional contextual meaning to names: createElement, appendChild, calculateTotal
Structure and Format
Defining Functions
Minification
General Benefits of Best Practices
- Your code will be easier for others to understand and maintain; vital in any collaborate programming or where you will be handing off your creations.
- Accessing and understanding code examples, snippets and pre-existing code. This will help you greatly when attempting to learn by example, understand tutorials and integrate techniques into your creations.
- Makes it easier for you to review your own code, identify problems, perform updates and make enhancements, even if you haven’t work on a particular project in some time.
References:
- Yahoo JavaScript Developer Center
- Google JavaScript Style Guide
- jQuery Core Style Guidelines
- JavaScript DOM Reference