Free Tutorial 4 All


RESOURCES

10 JavaScript Quick Tips and Best Practices

Posted by admin | Ajax&Js | Wednesday 8 July 2009 9:54 pm

JavaScript Quick Tips and Best PracticesRecently, a few blogs and tutorial sites have posted some really good articles on JavaScript tips and best practices, and I thought that was a good topic that could easily be expanded upon. So I put together a list of 10 fairly simple JavaScript tips and best practices of my own.

I tried to include stuff that was not mentioned in those other posts, but I’m sure there is a little bit of overlap. Keep in mind that these are brief tips and recommendations, so I don’t go into great detail about the reasons and such, but I may go into some of them in depth in future articles and tutorials.

In the meantime, please enjoy this list of tips, recommendations, and best practices for JavaScript coding.

1. Use the defer Attribute for IE-Only External Scripts

This is not necessarily a must-do, and neither is it a best practice, but it could come in handy at times. The defer attribute is declared inside of a <script> tag in XHTML like this:

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

The purpose of defer is to tell the externally linked script to wait until the page finishes loading until it runs. The same thing can be accomplished via good unobtrusive JavaScript methods, which usually include code that prevents scripts from executing until the DOM is finished loading.

The advantage of defer occurs in connection with Internet Explorer, since that browser is the only one that supports the defer attribute. So, if you need a quick script to run only in IE, and you don’t mind if the entire page loads before it starts to execute, then simply add defer="defer" in your <script> tag and that will quickly take care of that problem. Fixing a transparent PNG issue in IE6 is one possible practical use for defer.

(Edit 8/3/09: The defer attribute must be used when hiding a script from other browsers with a conditional comment that targets an IE-only script — otherwise the script will run normally in other browsers.)

2. Use a CData Section to Prevent XHTML Strict Validation Errors

Most of the time your scripts will reside in external files, and will be called in a <script> tag either in the <head> of the document, or right before the closing </body> tag.

But there may be an instance where you’re including JavaScript right in the HTML page itself, inside of <script> tags, like this:

<div>
<p>
<script type="text/javascript">
var my_variable = 100;
if (my_variable < 50) {
	// do something here...
}
</script>
</p>
</div>

Do you notice the “less than” symbol, which is part of the if statement? That symbol will cause the page to have validation errors, unless you wrap your code in a CData section, like this:

<div>
<p>
<script type="text/javascript">
//<![CDATA[
var my_variable = 100;
if (my_variable < 50) {
	// do something here...
}
//]]>
</script>
</p>
</div>

3. Avoid JavaScript’s Keywords When Creating Custom Identifiers

Many words are reserved as keywords in JavaScript, so you should avoid using them as variable names or other custom identifiers. The complete list of JavaScript keywords is as follows:

break
case
catch
continue
default
delete
do
else
finally
for
function
if
in
instanceof
new
return
switch
this
throw
try
typeof
var
void
while
with

4. Avoid JavaScript’s Reserved Words When Creating Custom Identifiers

There are also JavaScript reserved words, which are not necessarily currently used in the language, but are reserved for future use as keywords. Those words are as follows:

abstract
boolean
byte
char
class
const
debugger
double
enum
export
extends
final
float
goto
implements
import
int
interface
long
native
package
private
protected
public
short
static
super
synchronized
throws
transient
volatile

5. Don’t Change a Variable’s Type After Initial Declaration

In JavaScript, technically, the following is perfectly legal:

var my_variable = "This is a String";
my_variable = 50;

After the variable’s initial declaration as a string on line 1, on line 2 its value is changed and its data type is also changed. This is not good practice and should be avoided.

6. Don’t Use Global Variables

To prevent possible conflicts, in 99% of cases, use the var keyword when initially declaring variables and their values. This ensures that your variables are localized and are not accessible outside of the function in which they are declared. So, if you happen to use the same variable name in two different functions, there won’t be a conflict since each variable will be abolished the moment its function finishes executing.

7. JavaScript is Case-Sensitive

Remember that the following two variables represent two completely different place holders:

var myVariable = "data";
var myvariable = "more data";

So, use good, consistent practices in your custom identifiers, to ensure that you don’t accidentally declare two different variables when you actually meant to create just one.

8. Use the switch Statement to Handle Multiple Conditions

Don’t do this:

if (example_variable == "cyan") {
	// do something here...
} else if (example_variable == "magenta") {
	// do something here...
} else if (example_variable == "yellow") {
	// do something here...
} else if (example_variable == "black") {
	// do something here...
} else {
	// do something here...
}

Do this:

switch (example_variable) {
	case "cyan":
		// do something here...
		break;
	case "magenta":
		// do something here...
		break;
	case "yellow":
		// do something here...
		break;
	case "black":
		// do something here...
		break;
	default:
		// do something here...
		break;
}

The second block of code does the exact same thing as the first — but the second one is cleaner, easier to read, and easier to maintain and modify.

9. Use try-catch to Prevent Errors From Displaying to the User

By wrapping all your code in a try-catch statement, you can ensure that the user never sees an ugly JavaScript error. Like this:

try {
	nonExistentFunction();
} catch (error) {
	document.write("An error has occured.")
}

In the code above, I’ve attempted to call a function that doesn’t exist, to force an error. The browser will not display the typical “not an object” or “object expected” error, but instead will display the custom error that I’ve included in the catch section. You could also leave the catch section empty, and then nothing will happen on the client side, or you could create a function to call inside the catch section to handle the error quietly for your own debugging purposes.

Keep in mind that this could cause errors to be hidden from the developer as well, so good code documentation and commenting would be helpful here.

10. Make Multi-Line Comments Readable, But Simple

In JavaScript, you can comment a line of code by putting // at the beginning of the line. You can also comment out a block of code as shown here: /* [code goes here] */. Sometimes you’ll need to include a longer, multi-line comment. A good method to use that is not too visually overwhelming, but is easy to spot in the code is as follows:

/*
 * This is a multi-line comment ...
 * cont'd...
 * cont'd...
 * cont'd...
 * cont'd...
 */

That’s it, 10 easy JavaScript tips and best practices. Hopefully this article has added to the recent “best practices” articles that have been published and promoted. Please offer any suggestions or corrections in the comments, to add to the discussion, as I plan to expand on this in the future.



[Post to Twitter] Tweet This Post  [Post to Plurk] Plurk This Post  [Post to Yahoo Buzz] Buzz This Post  [Post to Delicious] Delicious This Post  [Post to Digg] Digg This Post  [Post to Ping.fm] Ping This Post  [Post to Reddit] Reddit This Post  [Post to StumbleUpon] Stumble This Post 

No Comments »

No comments yet.

RSS feed for comments on this post.

Leave a comment

atriumax wordpress theme