JavaScript best practices I
Now that we’ve seen the basic JavaScript concepts, we’ll go through some recommendations to make a good code. These are some practices that should be followed if you want to make a readable and maintainable code. It is based on my knowledge and experience of JavaScript over several years of practical experience:
- Always use ‘var’: although it is not compulsory, the use of the ‘var’ keyword is always recommended. By using it, your code will execute faster, and you will avoid some potential problems.
- Feature-detect rather than browser-detect: before using any advanced feature that an older browser may not support, check to see if the function or property exists first, instead of writing code to detect browser versions.
- Avoid ‘eval’: the eval() function in JavaScript allows a programmer to run arbitrary code at run-time, by interpreting a string as if it was code. If it exists in your page, there is almost always a more correct way to accomplish what you are doing. “Eval is evil.” Don’t use it unless you are an experienced developer and know that your case is an exception.
- Use unobstrusive JavaScript: now, this is an important one: HTML and JavaScript code should not be mixed together. You should always follow the “separation of concerns” mantra: HTML defines the structure and content of a web page, and JavaScript defines the behavior. Therefore, do not use inline event handlers. Attach your event-handling code by JavaScript. This way, you’ll improve readability and maintainability.
- Avoid cluttering the global namespace: global variables and functions are rarely required. Using globals may cause naming conflicts between JavaScript source files and cause code to break. You should always use object oriented programming and write all your code in classes when writing JavaScript code.
- Use JSON: when storing data structures as plain text or sending/retrieving data structures via Ajax, use JSON instead of XML when possible. JSON (JavaScript Object Notation) is a more compact and efficient data format, and is language-neutral.
- Make you code understandable: choose easy to understand and short names for variables and functions. Think of your code as a story – a story that should be easy to read and understand, the names you choose shouldn’t make it more complicated.
In my next post I’ll discuss some more recommendations. Stay tuned!


February 7, 2011 - 08:33
very cool & good JS tips for beginners, thank you very much for sharing.