The 11 Javascript Mistakes You're Making

12:15PM 14/06/2011, Lập trình web

JavaScript is relatively easy to learn. However, gotchas abound in this tricky language. Are you sure that you’re not following any bad practices? Today, I’ll point out ten big mistakes you could be making.

Mistake 1 - You’re Using Global Variables

If you’re just getting started with JavaScript, you probably think it’s a great thing that all variables are global. Actually, if you’re just getting started, you might not know what that means. Global variables are variables that are accessible from anywhere in your JavaScript, even in different files loaded on the same page. Sounds great, doesn’t it? Any variable you might every want to change is always accessible.

Actually, no.

The reason this is a bad idea is because it’s easy to overwrite values unintentionally. Say you’ve got a web store, and you’re using JavaScript to display the price of all the items in the shopping cart (of course, you’ll recalculate this on the server side; this just enhances the user experience). Here’s some code you might have:

	var total = 0,    // total price      
	tax   = 0.05; // 5%

Now, let’s say that you’re also using some code you found online to display some tweets on the page … or to make a sharp little gallery for your products. They might have some code like this:

var total = 15; // number of tweets pulled from twitter

Or,

var tax = function () { /* ... */ }; // Trigger Animation eXperience function

Now, you’re in trouble: two important variables have been overwritten, and you might not even realize it; your code will be producing errors, and you’ll pay dearly in time and hair to get things working again.

So what’s the solution? In a word, encapsulation; but there are many ways to do this. Firstly, you could just write all your code within a self-invoking, anonymous function:

	(function () {      
		var total = 0, 
		tax = 0.05;        // other code  
	}());

This way, absolutely no code outside the function can get to the values you have inside the function. This works for “personal” code, but it’s not so great for functionality that you want to distribute. For example, if we wanted to create a shopping cart totaller that others could use, using the module pattern would be great:

	var cartTotaler = (function () {      
		var total = 0; 
		tax = 0.05;        // other code        
		return {        
			addItem : function (item) { },        
			removeItem : function (item) { },        
			calculateTitle : function () { }      
		};  
	}());

One more thing about global variable: note that if you don’t use the var keyword when creating a variable, the JavaScript engine will create a global variable by default. So:

	(function () {    
		tax = 0.05;  
	}());    
	var totalPrice = 100 + (100 * tax); // 105

The variable tax is available outside the function because it’s not declared with the var keyword. Watch out for this.


Mistake 2 - You’re Not Using Semicolons

Every statement in JavaScript must end with a semicolon. It’s that simple. The issue here is that is you don’t put it in, the compiler will: this is called semicolon insertion. So the question is, if the compiler will insert them for you, why waste your time?

Well, in some places, it’s absolutely necessary; for example, you must put semicolons between the statements in a for-loop’s condition, or you’ll get a syntax error. But what about at the end of lines?

The JavaScript community is really divided on this. I’ve read very well-respected professionals on both sides of the debate. Here’s my argument: whenever you’re relying on the JavaScript compiler to change your code (even in what seems like a small way), you’re in dangerous waters.

For example, look at this simple function:

	function returnPerson (name) {      
		return      
			{          
				name : name      
			};  
	}

This looks like it should return a cute little object … but in reality, the JavaScript compiler assumes you meant to put a semicolon after return, and will therefore return nothing; that object will get ignored. Your solution would be to do this:

return {      name : name  };

I’m going to go with “diligently insert semicolons”; honestly, it becomes habit pretty quickly. Also, as a web developer, you’ll probably use other languages (like PHP) where semicolons are required. Why switch back and forth when you don’t have to?

Editor’s Note- Another way to look at it: unless you’re aware of every single situation where they can successfully be omitted, don’t risk it.


Mistake 3 - You’re Using ==

If you left your computer right now and walked until you met any random JavaScript developer (that might take a while), and asked him/her to give you one common JavaScript mistake, this is probably what he/she would say: “using double-equals instead of triple-equals.” What’s this mean?

Try this:

	if (1 == 1) {      
		console.log("it's true!");  
	}

You’d expect that to work, right? Well, now try this:

	if (1 == '1') {      
		console.log("it's true!");  
	}

Yes, you got “it’s true!” output to the console … and yes, that’s a bad thing. What’s going on here is that the == equality operator is coercing the values: this means it’s actually changing them to try to make the two values more similar. In this case, it’s converting the string “1” to the number 1 … so that our if-statement condition passes.

The solution here is to use ===; this doesn’t perform any type coercion, so the values are what you expect them to be. Of course, this all goes for the != and !== operators as well.

Now, for your amusement, here’s a few of the incredible inconsistencies that you’ll get if you use double-equals:

	'' == '0' // false  
	'0' == ''  // true  
	false == '0' // true  
	' \t\r\n ' == 0   // true 

Mistake 4 - You’re using Type Wrapper Objects

JavaScript kindly (um?) gives us some type wrappers for easy (um?) creation of primitive types:

	new Number(10);  
	new String("hello");  
	new Boolean(true);  
	new Object();  
	new Array("one", "two", "three");

First off, this is just super inconvenient. All these things can be done with many fewer keystrokes:

	10;  
	"hello";  
	true;  
	{};  
	["one", "two", "three"];

But, wait, there’s more: these two things aren’t exactly equal. Here’s Douglas Crockford on the topic:

For example, new boolean(false) produces an object that has a valueOf method that returns the wrapped value.

- JavaScript: The Good Parts, page 114

This means that if you run typeof new Number(10) or typeof new String("hello"), you’ll get ‘object’—not what you want. Plus, using wrapper objects can cause behaviour that you’re not expecting if you’re used to primitive values.

So why does JavaScript provide these objects? It’s because they’re used internally. Primitive values don’t actually have methods (because they aren’t object); so, when you call a method on a primitive object (such as "hello".replace("ello", "i")), JavaScript creates a wrapper object for that string, does what you want, and then discards the object.

Leave the typed wrappers up to JavaScript and use the primitive values.

Note: this should go without saying, but I want to make this clear for the newbies: I’m not saying you shouldn’t use constructor functions and new (although some do recommend that). This advice specifically applies to primitive value types—numbers, strings, and booleans—arrays, and blank objects.


Mistake 5 - You’re not Property-Checking when Using For-In

We’re all familiar with iterating over arrays; however, you’ll probably find yourself wanting to iterate over the properties of an object. (Digression: the items in an array are actually just numbered properties in an object.) If you’ve done this before, you’ve used a for-in loop:

	var prop, 
		obj = { name: "Joe", job: "Coder", age: 25 };    
	for (var prop in obj) {    
		console.log(prop + ": " + obj[prop]);  
	}

If you run the above code, you should see this output:

	name: Joe  
	job: Coder  
	age: 25

However, browsers will include properties and methods from further up the prototype chain. Most of the time you won’t want to see these when enumerating properties. You should be using the hasOwnProperties to filter out properties that aren’t actually on the object:

	Function Dog (name) {      
		this.name = name;  
	}  
	Dog.prototype.legs = 4;  
	Dog.prototype.speak = function () {      
		return "woof!";  
	};    
	var d = new Dog("Bowser");    
	for (var prop in d) {      
		console.log( prop + ": " + d[prop] );  
	}    
	console.log("=====");    
	for (var prop in d) {    
		if (d.hasOwnProperty(prop)) {      
			console.log( prop + ": " + d[prop] );    
		}  
	}    
	// Output    
	// name: Bowser  
	// legs: 4  
	// speak: function () {          return "woof!";  // }  
	// =====  
	// name: Bowser

Sometimes, you’ll want to let the properties through, but filter out any methods. You can do that by using typeof:

	for (var prop in d) {    
		if (typeof d[prop] !== 'function') {      
			console.log( prop + ": " + d[prop] );    
		}  
	}

Either way, always be sure to clarify your for-in statements to avoid unwanted results.


Mistake 6 - You’re Using with or eval

Thankfully, most sources for learning JavaScript today don’t teach you about with or eval. But if you’re using some older material—or using a less-than-reputable source (because sometimes good material is hard to find on the web)—you might have found with and eval and given them a try. Terrible move, web developer.

Let’s start with with. Two main reasons not to use it:

  1. It really slows down the execution of your JavaScript.
  2. It’s not always clear what you’re doing.

Point one stands on its own, so let’s look at the second. Quickly, here’s how with works: You pass an object to a with statement; then, inside the with statement block, you can access properties of the object as variables:

	var person = { name: "Joe", age : 10 };    
	with (person) {    
		console.log(name); // Joe    
		console.log(age);  // 10  
	}

But, what if we have a variable with the same name as a property of the object we’re with-ing? Basically, if both a variable and a property with the same name exist, the variable will be used. The other gotcha is that you can’t add a property to the object inside a with statement: if no property or variable exists, it will be made a variable of the scope outside the with statement:

	var person = { name: "Joe", age : 10 },      
		name = "Billy";    
	with (person) {    
		console.log(name); // Billy    
		job = "Designer";  
	}     
	console.log(person.job); // undefined;  
	console.log(job); // Designer

So, how about eval? In a nutshell, you can pass a string of code to the function and it will execute the code.

eval( "Console.log('hello!');" );

Sounds harmless, even powerful, right? Actually, that’s the main problem: it’s too powerful. There’s obviously no reason to just hand it a hard string that you write directly into your code, because 1) why not just write the code? And 2) eval is slower, just like with. Therefore, the primary use of eval is to execute code that you don’t have at runtime. You could be getting this from the server, or taking code directly from the user. Do you really want to give your website users complete control of your code? I hope not. Also, it opens your site up to unnumbered hackers: using eval is basically a sign that says ”I’m away, and the key is under the mat.” If you love yourself or your users: don’t use it.


Mistake 7 - You’re Not Using a Radix When Using parseInt

JavaScript has a great little helper function called parseInt that allows you to convert a string that contains a number to a number:

	parseInt("200"); // 200  
	parseInt("043"); // 35

Um, what happened there? Shouldn’t that second example be 43? Actually, parseInt will work with more than just decimal values: so, when parseInt sees a string that starts with a 0, it assumes that it’s an octal number (base 8). That’s why it’s a mistake not to pass a radix; this tells parseInt what base the number is in (it always outputs a decimal number).

	parseInt("020", 10); // 20  
	parseInt("100", 2);  // 4

Mistake 8 - You’re Not Using Braces on if and while statements

One of the most obvious beauties of JavaScript is its flexibility. But sometimes, that can come back to fight you. That’s certainly the case with braces on if- and while-statement blocks. These braces are optional if you only have one line of code in the block:

	if (true)    
		console.log("inside the if statement");
	

This is great, because you can even put them on the same line:

	var arr = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"],      
	i   = arr.length - i;    
	while (i) 
		console.log( arr[i--] );

But this isn’t smart for a couple of reasons: firstly, it can become unclear:

	if (true)    
		console.log("inside the if-statement.");    
	console.log("outside the if-statement.");

See what I mean? That second line isn’t in the if-statement, but it sure looks like it. Braces would make that clear. Also, if you ever want to add a line to the block, you have to remember to add the braces as well. Just adding them in the first place is so much easier. Do it.


Mistake 9 - You’re Adding Elements to the DOM Individually

All right, all right: this isn’t really JavaScript itself. But, in 99 of 100 cases, JavaScript means using the DOM. While there’s a lot of mistakes you can make when working with the DOM, this is a big one.

I fondly remember the day when I inserted my first DOM element via JavaScript. It’s fun to do, and oh-so-useful, but it unfortunately is a strain on the page: inserting a DOM element forces the browser to completely repaint the page, so if you have a whole bunch of elements to add, adding them one by one is a bad idea:

	var list = document.getElementById("list"),      
		items = ["one", "two", "three", "four"],      
		el;    
	for (var i = 0; items[i]; i++) {    
		el = document.createElement("li");    
		el.appendChild( document.createTextNode(items[i]) );    
		list.appendChild(el); // slow, bad idea  
	}

Here’s what you should do instead: use document fragments. Document fragments are a container to hold DOM elements; then instead of inserting each element individually, you can insert them all at once. The document fragment isn’t a node in itself and there will be nothing to show for it in the DOM: it’s just an invisible net for holding DOM elements before you put them into the DOM. So, here’s how you do it:

	var list = document.getElementById("list"),      
		frag = document.createDocumentFragment(),      
		items = ["one", "two", "three", "four"],      
		el;    
		for (var i = 0; items[i]; i++) {    
			el = document.createElement("li");    
			el.appendChild( document.createTextNode(items[i]) );    
			frag.appendChild(el); // better!  
		}    
		list.appendChild(frag);

Faster, quicker, cleaner—what’s not to love?


Mistake 10 - You’re Not Learning JavaScript

Many people don’t take the time to learn JavaScript right.

JavaScript does not equal jQuery. Did I just shock your sock off? If you found yourself guilty of committing several of the mistakes listed above, you probably need to do some serious JavaScript studying. JavaScript is a language that you can use almost without learning it, which means that so many people don’t take the time to learn it right. Don’t be one of those people: there are so many awesome JavaScript tutorials out there that you have no excuse for not learning the language. If all you know is jQuery (or Mootools, or whatever), you’re really putting yourself in a bad spot.


Mistake 11 - You’re Following all the Rules

Rules are made to be broken.

The last and final mistake you’re making is that you’re following all the rules. Yes, even some of the rules I’ve listed here. As with anything, rules are made to be broken. If you’re relatively new to JavaScript, you should probably avoid with fervour all the mistakes I’ve outlined for you today. But the truth is that if you understand why it’s recommended not to do something, that thing becomes a tool that you might use in just the right circumstance. For example, eval is preached against loudly, but it’s the only tool you can use to parse JSON from a server. Of course, there are many security checks in place when you do it (you should probably use a library). But the point is that you shouldn’t be afraid to knowledgeably use the “bad practices” I’ve listed above if the need arises. It’s the same close-mindedness that causes you to make these mistakes in the first place is the same close-mindedness that keeps you from using them when they are the right tool.

Of course, never make mistake 10 -


Conclusion

If you’re new to JavaScript, hopefully you’re a better JavaScript developer now. If you consider yourself a JavaScript pro (then how are you even still reading this?), what have I missed? Let us all know in the comments!


Theo NETTUTS