11 lỗi JavaScript cơ bản nên tránh Trong các bài viết trước, jsB@nk đã cung cấp cho bạn rất nhiều các thủ thuật JavaScript hữu ích:
- 10 thủ thuật JavaScript đơn giản nên nắm vững
- 6 kĩ thuật JavaScript nâng cao bạn nên dùng

Và một vài lỗi JavaScript phổ biến mà chúng ta hay phạm phải Một vài lỗi JavaScript phổ biến.

Tuy nhiên những lỗi này hơi ít và lập trình JavaScript ngày càng phát sinh thêm nhiều vấn đề khác nên hôm nay jsB@nk quyết định cung cấp cho bạn thêm 11 lỗi JavaScript phổ biến khác: thường thiếu dấu chấm phẩy ; để ngắt các dòng lệnh, dùng sai kiểu dữ liệu, ... vui lòng vào bài viết chi tiết để xem thêm các ví dụ và mã nguồn JavaScript đầy đủ.

Miễn phí web hosting 1 năm đầu tại iPage

Nếu bạn vẫn còn đang tìm kiếm một nhà cung cấp hosting đáng tin cậy, tại sao không dành chút thời gian để thử với iPage, chỉ với không quá 40.000 VNĐ/tháng, nhưng bạn sẽ được khuyến mãi kèm với quà tặng trị giá trên 10.000.0000 VNĐ nếu thanh toán cho 24 tháng ~ 900.000 VNĐ?

Có trên 1 triệu khách hàng hiện tại của iPage đã & đang hài lòng với dịch vụ, tuyệt đối chắc chắn bạn cũng sẽ hài lòng giống họ! Quan trọng hơn, khi đăng ký sử dụng web hosting tại iPage thông qua sự giới thiệu của chúng tôi, bạn sẽ được hoàn trả lại toàn bộ số tiền bạn đã sử dụng để mua web hosting tại iPage. Wow, thật tuyệt vời! Bạn không phải tốn bất kì chi phí nào mà vẫn có thể sử dụng miễn phí web hosting chất lượng cao tại iPage trong 12 tháng đầu tiên. Chỉ cần nói chúng tôi biết tài khoản của bạn sau khi đăng ký.

Nếu muốn tìm hiểu thêm về ưu / nhược điểm của iPage, bạn hãy đọc đánh giá của ChọnHostViệ nhé!
Thử iPage miễn phí cho năm đầu tiên NGAY

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

Mistake 1 - Youre Using Global Variables

If youre just getting started with JavaScript, you probably think its a great thing that all variables are global. Actually, if youre 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, doesnt it? Any variable you might every want to change is always accessible.

Actually, no.

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

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

Now, lets say that youre 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


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

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

So whats 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 its 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 dont 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 its not declared with the var keyword. Watch out for this.

Mistake 2 - Youre Not Using Semicolons

Every statement in JavaScript must end with a semicolon. Its that simple. The issue here is that is you dont 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, its absolutely necessary; for example, you must put semicolons between the statements in a for-loops condition, or youll get a syntax error. But what about at the end of lines?

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

For example, look at this simple function:

function returnPerson (name) {
        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

Im going to go with diligently insert semicolons; honestly, it becomes habit pretty quickly. Also, as a web developer, youll probably use other languages (like PHP) where semicolons are required. Why switch back and forth when you dont have to?

Editors Note- Another way to look at it: unless youre aware of every single situation where they can successfully be omitted, dont risk it.

Mistake 3 - Youre 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. Whats this mean?

Try this:

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

Youd expect that to work, right? Well, now try this:

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

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

The solution here is to use ===; this doesnt 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, heres a few of the incredible inconsistencies that youll get if you use double-equals:

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

Mistake 4 - Youre 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:

["one", "two", "three"];

But, wait, theres more: these two things arent exactly equal. Heres 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"), youll get objectnot what you want. Plus, using wrapper objects can cause behaviour that youre not expecting if youre used to primitive values.

So why does JavaScript provide these objects? Its because theyre used internally. Primitive values dont actually have methods (because they arent 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: Im not saying you shouldnt use constructor functions and new (although some do recommend that). This advice specifically applies to primitive value typesnumbers, strings, and booleansarrays, and blank objects.

Mistake 5 - Youre not Property-Checking when Using For-In

Were all familiar with iterating over arrays; however, youll 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 youve done this before, youve 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 wont want to see these when enumerating properties. You should be using the hasOwnProperties to filter out properties that arent actually on the object:

Function Dog (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] );


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, youll 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 - Youre Using with or eval

Thankfully, most sources for learning JavaScript today dont teach you about with or eval. But if youre using some older materialor 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.

Lets start with with. Two main reasons not to use it:

  1. It really slows down the execution of your JavaScript.
  2. Its not always clear what youre doing.

Point one stands on its own, so lets look at the second. Quickly, heres 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 were 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 cant 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, thats the main problem: its too powerful. Theres 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 dont 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 Im away, and the key is under the mat. If you love yourself or your users: dont use it.

Mistake 7 - Youre 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? Shouldnt 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 its an octal number (base 8). Thats why its 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 - Youre 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. Thats 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 isnt 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 isnt 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 - Youre Adding Elements to the DOM Individually

All right, all right: this isnt really JavaScript itself. But, in 99 of 100 cases, JavaScript means using the DOM. While theres 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. Its 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"],

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

Heres 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 isnt a node in itself and there will be nothing to show for it in the DOM: its just an invisible net for holding DOM elements before you put them into the DOM. So, heres how you do it:

var list = document.getElementById("list"),
    frag = document.createDocumentFragment(),
    items = ["one", "two", "three", "four"],

for (var i = 0; items[i]; i++) {
  el = document.createElement("li");
  el.appendChild( document.createTextNode(items[i]) );
  frag.appendChild(el); // better!


Faster, quicker, cleanerwhats not to love?

Mistake 10 - Youre Not Learning JavaScript

Many people dont 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 dont take the time to learn it right. Dont 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), youre really putting yourself in a bad spot.

Mistake 11 - Youre Following all the Rules

Rules are made to be broken.

The last and final mistake youre making is that youre following all the rules. Yes, even some of the rules Ive listed here. As with anything, rules are made to be broken. If youre relatively new to JavaScript, you should probably avoid with fervour all the mistakes Ive outlined for you today. But the truth is that if you understand why its 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 its 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 shouldnt be afraid to knowledgeably use the bad practices Ive listed above if the need arises. Its 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 -


If youre new to JavaScript, hopefully youre 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!

JavaScript theo ngày

Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web