JavaScript Best Practices for Beginners

September 8th, 2012 Leave a comment
Like the article?
JavaScript Best Practices for Beginners

When you are just learning a new programming language it can be daunting to think you may be picking up bad habits or not learning something the right way. With JavaScript, there are a lot of quirks and different ways to accomplish things that you may not realize. In this article I am going to discuss some best practices for beginners so you can start gaining knowledge of JavaScript without having to worry you are doing something wrong.

1. Remove the “language” attribute from the <script> tag.

Years ago, the language attribute was required on the <script> tag to ensure the browser understood the language it should be interpreting.

<script type="text/javascript" language="javascript">

However, the language attribute has been deprecated for a while and is no longer needed. You can leave this one off.

2. Raw JavaScript is always faster

It may be cool to use JavaScript libraries such as jQuery and Mootools, but when it comes to script execution time, nothing will be able to beat raw JavaScript. You can see this for yourself if you compare jQuery’s “each” method in a loop against JavaScript’s native “for” statement. It’s OK to use these tools when other functionality is available but if you are going for speed, be sure you are taking this into account.

3. Learn to use self-executing functions

If you are calling a function automatically when the page loads (which is a common thing to do), or you need to call a parent function during a function call, you can wrap your function in parenthesis and append an additional set of parenthesis to the end, which will call the function. Here is an example:

(function callMyself() {  
	return {  
		name: 'Bob',  
		lastName: 'Self'  

4. Use “For In” Statements

If you are looping through item in an object, you may find that you will also retrieve method functions as well. In order to work around this, you should always wrap your code in an “if” statement which filters out this information. For example:

for (key in object) {  
	if (object.hasOwnProperty(key) {  
		//...then do something...  

5. Semicolons are not optional!

While most browsers will let you get away with not using semi-colons it is a very bad habit to get into. It could eventually lead to a much bigger and harder problem to find. So something like this:

var someItem = 'some string'  

function doSomething() {  
	return 'something'  

Should look like this:

var someItem = 'some string'; 

function doSomething() {  
	return 'something'; 

6. var can be optional

One of the important things to remember about writing code is that it should be neat and readable. If you have a long list of JavaScript variables, you can create a comma-separated list instead of a pile of “var” lines. For example:

var someItem = 'some string';  
var anotherItem = 'another string';  
var oneMoreItem = 'one more string';  

Can be turned into:

var someItem = 'some string',  
anotherItem = 'another string',  
oneMoreItem = 'one more string';  

7. Use arrays, not objects

It is a common problem in JavaScript to use objects instead of arrays. Many developers that learned programming in an object-oriented language just immediately turn to objects to solve problems. In JavaScript, you can use an array any time you have small items of the same data type to store, instead of an object. For example:

var myArray = new Array();  
myArray[0] = "Joe";  
myArray[1] = 'Plumber'; 

Is better off as:

var myArray= ['Joe', 'Plumber']; 

8. Use object literals, not objects

Just like in the above example, programmers will sometimes create objects with the “new” keyword where an object isn’t required. It is recommended that you use object literals instead. Object literals allow us to write code that can support a lot of features without being hard to implement or understand. If you are not using objects, you do not need to invoke constructors directly or maintain the correct order of arguments passed to functions. For example:

var o = new Object(); = 'Jeffrey';  
o.lastName = 'Way';
o.someFunction = function() {  

Is better off as:

var o = {  
	firstName: 'Jeffrey',  
	lastName: 'Stall',  
	someFunction: function() {  

9. Don’t use “With”

To new developers in JavaScript, the “with” statement seem like a good idea.

with ( {  
	arms = true;  
	legs = true; 

Instead of: = true; true;  

However, after doing some testing it has been found that “with” does not perform well when setting new members. You should use “var” instead. For example:

var o =;  
o.arms = true;  
o.legs = true; 

10. Reduce global variables

Sometimes in our applications, we need to use variables that are global in scope so they are available to the entire program. However, this can sometimes lead to problems. Have less global variables can reduce the chance of bad interactions between your application and other widgets or libraries.

11. Place scripts at the bottom

Many JavaScript developers first learn how to write scripts at the top of the page, with the <script> tag residing in the <head> section of the document. Since our primary goal is to make the page load as quickly as possible, putting the scripts in at the top actually works against that. The browser cannot load the body of the page until the <head> section is finished, and if your JavaScript is slow, the user will have to wait longer for the page to load. For the best performance, place your <script> tags at the bottom, just before the closing <body> tag.

12. Always use curly brace blocks

Just like semi-colons, we can get away with omitting most curly braces in our JavaScript. However, this can lead to problems and logic issues. For example:

if (someVariableExists)  
 	x = false; 

Some may think this is the same thing as:

if (someVariableExists) { 
 	x = false;  

Which creates a logic problem. In reality, this is the equivalent of:

if (someVariableExists) { 
 	x = false;

As you can see, by omitting the curly brace blocks leaves the program open to error. Always think about the future maintainability of your code as well.

13. Eval is Bad

For those unfamiliar, the “eval” function gives us access to JavaScript’s compiler. Essentially, we can execute a string’s result by passing it as a parameter of “eval”. Not only will this decrease your script’s performance substantially, but it also poses a huge security risk because it grants far too much power to the passed in text. Avoid it!

14. Use triple equals (===) instead of double equals (==)

JavaScript has two different kinds of equality operators. The triple-equals (===) checks for both equality of data and equality of type. The double-equals (==) only checks for equality of data. It is considered best practice to use the triple-equals instead of the double when comparing so you do not run into issues when working with different types.

I hope you have enjoyed this list of JavaScript best practices. Picking up these good habits early is the key to writing better code in the future as you become more proficient with JavaScript. I’m sure as you progress that you will find many more quirks and dangers in the JavaScript language to look out for!

Help us spread the word!
  • Twitter
  • Facebook
  • LinkedIn
  • Pinterest
  • Delicious
  • DZone
  • Reddit
  • Sphinn
  • StumbleUpon
  • Google Plus
  • RSS
  • Email
  • Print
Don't miss another post! Receive updates via email!