11 JavaScript Mistakes Should Avoid

In the previous JavaScript tutorials, jsB@nk provided many useful JavaScript skills, helpful JavaScript tips and tricks and awesome JavaScript solutions:
- 10 Small Javascript Tricks You Should Master
- 6 Advanced JavaScript Techniques You Should Use
- A Few Common JavaScript Mistakes

However, these JavaScript tutorial article still can not cover all JavaScript problems we're encountering because the JavaScript applications become more and more complicated; hence, today in this JavaScript tutorial, I would like to provide more 11 JavaScript mistakes/errors we should avoid to make our JavaScript web-based applications better.

Some mistakes you can know obviously such as: using JavaScript global variables in wrong manners, forgot the semicolons, assign wrong variable/object types, etc. Please go to the inner post page for details with full JavaScript source codes and JavaScript demos.


Sampled by © JavaScriptBank.com

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!

Language
Translate this page to English Translate this page to French Translate this page to Vietnamese

Recent articles
The Possible Working Methods of Python Ideology
JavaScript Research Paper: 6 Writing Tips to Craft a Masterpiece
Learning How to Make Use of New Marketing Trends
5 Important Elements of an E-commerce Website
How To Create A Successful Prototype For Your PCB
WordPress Landing Page Conversion Essentials to Convert More
4 Development Hacks To Make Your Website Launch A Success
Why Data Recovery Software and Services are Important
Why Engineers Specializing in DevOps Are the Wave of the Future
The Ultimate Checklist for HTTP to HTTPS Migration


Top view articles
65 Free JavaScript Photo Gallery Solutions
Top 10 Beautiful Christmas Countdown Timers
Best Free Linux Web Programming Editors
Top 50 Most Addictive and Popular Facebook mini games
Top 10 Free Web Chat box Plug-ins and Add-ons
50+ Beautiful Resources of HTML Form using CSS and JavaScript
Top 10 Best JavaScript eBooks that Beginners should Learn
The Ultimate JavaScript Tutorial in Web Design
HTML5 Web Workers Multithreading in JavaScript
Learn more about JavaScript Inheritance with Tiny JavaScript Example Codes


Free JavaScript Tutorials & Articles
at www.JavaScriptBank.com