JavaScript Best Practices for Beginners

September 8th, 2012 Leave a comment 6 comments
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();  
o.name = 'Jeffrey';  
o.lastName = 'Way';
o.someFunction = function() {  
	console.log(this.name);  
} 

Is better off as:

var o = {  
	firstName: 'Jeffrey',  
	lastName: 'Stall',  
	someFunction: function() {  
		console.log(this.name);  
	} 
};

9. Don’t use “With”

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

with (being.person.man.bodyparts) {  
	arms = true;  
	legs = true; 
}

Instead of:

being.person.man.bodyparts.arms = true;  
being.person.man.bodyparts.legs= 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 = being.person.man.bodyparts;  
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; 
	anotherFunctionCall(); 

Some may think this is the same thing as:

if (someVariableExists) { 
 	x = false;  
	anotherFunctionCall(); 
}

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

if (someVariableExists) { 
 	x = false;
}
anotherFunctionCall();

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!

6 comments

  1. javiertapia says:

    Good article, thanks!
    But, in the 8th point, the 2nd code must say “someFunction : function() { …”, (colon, not equal) in line 5

  2. 1) You can also remove the “type” attribute. The value “text/javascript” is default.

    4) Variables in JavaScript aren’t block scoped, they are closure scoped. So you should use var also in the for…in statement:

    for (var key in map) {

    Also you shouldn’t use hasOwnProperty as method because it could be overwritten:

    var owns = Object.prototype.hasOwnProperty;
    for (var key in map) if (owns.call(map, key) {

    }

    7) Arrays in JavaScript ARE objects, so this point is a little bit pointless. Array literals are just faster when you are immediately storing some data. But when you need to create an array of some size, this is little bit faster:

    var array = new Array(1000);
    for (var i = 0; i < 1000;) {
    array[i] = ++i;
    }

    And you omitted one bracket in the "if" statement.

    13) Yeah, it's evil, but you should also mention the good usage to parse JSON in older browsers.

  3. Jamon says:

    regarding multiple “var” statements, I used to do what you do here, but noticed that as I make changes to the vars over time, I spend a lot of time screwing with the list… it’s a lot of maintenance.

    If you use var on each line, you can simply add/remove without dealing with the other lines and making sure you don’t have a trailing comma, etc.

  4. opensas says:

    very good article

    as always, there are some tips that are quite debatable…

    1, 2 OK

    3, you should explain why this approach is better…

    4 ok

    5. semicolons are not optional…

    well in pragmatic.js the say quite the contrary (https://github.com/madrobby/pragmatic.js and http://mislav.uniqpath.com/2010/05/semicolons/)

    in short, they argue that you should only need them at the beginning of lines starting with ( or [

    6. NO. var ARE NOT OPTIONAL (please don’t spread it)

    what you are showing is just another syntax for the var statemes, but it’s there anyway, and if you omit it bad things might happen (you know what I mean…)

    7. sure, specially if you need to keep the order of items, in that case you have no other choice

    8, 9, 10, 11 ok

    12. well, once again pragmatic js argues to keep oneliners conditional in the same line with no curly brackets… I think they are even more readable and hard to confuse…

    13, 14 OK

    I would also add to use jslint or similar tool, it enforces many of the tips you provide

    I hope you write more articles like this ;-)

    saludos

    sas

    • Denny says:

      Thanks for saving me a lot of time by posting my exact thoughts… Except for #5. You’re right – they are technically optional but personally I like them to be there if not only to emphasize the intent of the author to end that line. I can’t even count how many times I found a bug in code because I noticed the lack of a semicolon, then noticed that the developer forgot something else on that line.

Comment