The 11 JavaScript Mistakes you’re Making
Tutorial Details
- Topic - JavaScript Mistakes
- Difficulty - Intermediate
Download Source Files
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 avalueOfmethod 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:
- It really slows down the execution of your JavaScript.
- 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!

Andrew, can you give more info about ‘hasOwnProperties’?
Did you mean to say ‘hasOwnProperty’?
And most cases it is faster to clone a node instead of creating new ones, if you have the ability to do that, then that is a bit faster.
be aware that clone will not success in every browser as expected, so creating new node is better way
Yes, sorry about that; it’s a typo: I meant
hasOwnProperty.Well Mistake 10 is all that matters most to me ! I started using jQuery without knowing Javascript untill at one point I was more than frustrated ! So I went back and read JS from scratch ! Great article
Very good hints! If I could have read this when I started coding in Javascript I’d have saved a lot of time!
Recommended tutorial !
(not sure of my english grammar !!)
coding always comes with stupid mistakes.
Very helpful post. Slowly but surely getting better at this JavaScript thing.
I’d like to add “You’re not using a Javascript framework”. I’d advise any webdev to use jQuery or Prototype..
If you have enough experience, you don’t need a public framework.
A public framework (like: jQuery, Prototype) is good for developers that doesn’t know how or doesn’t have the time to write their own framework.
Not using a framework is NOT a mistake.
I’m no Resig or Crockford, but I’m pretty good at JavaScript. I’ve written numerous libraries and even some large scale libraries for huge websites as API wrappers and such. I’ve written all kinds of jQuery plugins as well. jQuery wasn’t written so any numbskull developer can make something fade in and out, it was made to make working with the DOM easier, cross browser, and so any other random developer who takes on your project has a central place to learn your library.
Having to learn a new library for every site you ever work on would be ridiculous. Knowing when I see a site that it’s jQuery I know, for one, it’s working in IE. I also know I can just jump right in and start working on things. Finally, if you use a cache like Google’s CDN the end user has the site loaded even faster. Having to load some random personal library due to NIH syndrome slows everything down.
It’s a bad, bad idea to create your own library for every. single. project. There’s a reason, Barry, sites as large as Google use jQuery and it’s for these reasons. Talk about a beginner’s mistake. Keep things DRY and copy and paste the jQuery CDN link.
If it’s a huge project, with lots of users and it’s heavy in JavaScript you might want to optimize and make your own library which makes sense. An example of this is Facebook. However, I know Twitter, Yammer, Google, and all kinds of huge companies use jQuery, so why do you think it’s a bad idea?
I think you are missing the point, please read the messages again and review.
I never said one single time that you should avoid a public library, if you have the knowledge and the time it’s perfectly to write your own, and not for every project, whats the idea behind that?
Writing your own is: Fun. Learning process. Instructive.
I am writing JS for 10+ years, i know what i do, i know what i want, and i know how fun and how instructive it can be. And i never have said that i haven’t used a public library before.
Not using a framework is most definitely a mistake. The only time it is not a mistake is you have mastery level so high you can write your own framework.
To use JS without leveraging a framework is like using Ruby without rails, ASP.NET without MVC (or even webforms) etc. Yes there may be times you’re better off going bare metal but that requires architect level knowledge and capacity.
@Chris,
“Not using a framework is most definitely a mistake. The only time it is not a mistake is you have mastery level so high you can write your own framework.”
Actually, you are completely ignoring the added cost of loading and processing a framework. For simple javascript projects, it is often the best course to not use any framework at all (including a self-rolled on) for the added speed. Yes, you have to do multi-browser testing when you do this, but sometimes it’s worth it. I’ve been doing JS development for several years, and while I usually use jQuery (for general purpose JS; there are other pre-packaged frameworks that work better for specific tasks), there are plenty of smaller simple tasks where plain javascript makes more sense for the best user experience.
“To use JS without leveraging a framework is like using Ruby without rails”
I am a full-time ruby developer, and I very frequently use Ruby with Rails. For web apps, I’ve used Rails a few times, but Sinatra is more often the way to go because Rails is way too bloated for many web apps. Granted, Sinatra is also a framework.
But for non web-app purposes (i.e. general purpose scripting), I use Ruby all the time without any framework.
“frequently use Ruby with Rails” was supposed to say “frequently use Ruby without Rails”
Framework or not Framework?
I recommend any new to JS, to do your own framework (and then see if you want to keep expanding it)
After that… start using a framework ( I love jQuery)
and then you can make a decision with all the information
the best of it, is that at the end, you will know how the framework makes the magic happens
I’m not sure I agree with #8. I think omitting braces in situations where you only have one line help to keep your code clean and organized. Besides, if you are keeping your code clean, you shouldn’t have any issues with confusion based on situation like in your example above.
Also, there are many developers (both those that know Javascript and those that only know jQuery) that disagree with #10. jQuery (and other libraries like it), make learning and using Javascript extremely easy, and, for the most part, you can accomplish just about everything you need with jQuery.
I personally learned both. But once you learn Javascript, you would be crazy not to use a library. They exist for a reason.
Andrew is not trying to discourage the use of jQuery or any other library. He is saying that, even if you do use a library, you should learn how to code with raw javascript.
You’re right: it’s possible to keep your code organized and not have any problems with omitting braces. But if you’re sharing your code with others, they might not realize what’s going on, and add another line without adding the braces. And even the pros will have mental lapses occasionally. The point of including them is to require as little thinking as possible for the person reading / modifying the code, and to allows as little room for error as possible.
About learning JavaScript vs. jQuery: The thing here is that jQuery is just JavaScript. You need to understand something about JavaScript to use jQuery properly. I don’t think someone can say they know jQuery well without knowing JavaScript.
Of course, I’m not for a second saying that you shouldn’t use a framework. I’m saying that every framework—barring things like Objective-J and CoffeeScript—is just JavaScript, and you’ll never use a framework to its fullest extent without knowing some JavaScript.
If I’m sharing my code with others then those others are competent programmers too. If they don’t spot that if (predicate()) consequence(); is different from if (predicate()) { doThis(); andThat() } then someones definition of ‘competent’ is out of whack.
I just use coffeescript and postfix if.
Well, In my personal opinion I think using braces all the time makes everything consistent and, well, less confusing.
However, the reason why I always use braces in the “if-statement” regarding the number of lines beneath it is that if you run it against js-lint, it would return an error. Here is the reason why:
Taken from: http://www.jslint.com/lint.html
Required Blocks
JSLint expects that if, while, do and for statements will be made with blocks {that is, with statements enclosed in braces}.
JavaScript allows an if to be written like this:
if (condition)
statement;
That form is known to contribute to mistakes in projects where many programmers are working on the same code. That is why JSLint expects the use of a block:
if (condition) {
statements;
}
Experience shows that this form is more resilient.
I will never put braces around a one-line if/for/while block. EVER. I hate that Perl makes me do so, and regardless of whether or not it’s better for consistency, you just can’t make me. :)
Pray I never debug your code :P
haha, me too!
(typeof bla !== ‘undefined’) ? alert(‘true’) : alert(‘false’); /* shorthand / single line if */
I agree with you here. I don’t code single line code blocks for C#, I won’t do it for JS either.
The only time I consider doing it is if the 1 liner is so convoluted that it’s hard to retain scope currently visually, then I’ll make it a block.
Totally agree that braces on one-liners often make no sense. It’s adds unnecessary syntax to your code such that braces can actually make your code *more* difficult to read and understand.
I’m not saying never use braces on one-liners — sometimes there is a real chance of confusion, and you should add braces then. But it’s just bad advice to say always add braces.
The other 10 rules were all spot on though.
How is
if ( something === true ) {
do this;
} else {
do that;
}
more confusing?
Braces keep code organized.
just as tab’s do.
The only mistake I seem to have committed is the Mistake 10 or maybe sometime Mistake #1. Thankfully none others I have ever committed. But its a good read so one knows about these mistakes and can avoid them in future.
Surely you have made a mistake in point 11 where you said eval is the only way? JSON.parse() shields against any problems you might encounter
http://www.json.org/js.html
“To convert a JSON text into an object, you can use the eval() function. eval() invokes the JavaScript compiler. [...] The text must be wrapped in parens to avoid tripping on an ambiguity in JavaScript’s syntax.
var myObject = eval(‘(‘ + myJSONtext + ‘)’);
[...] It is much safer to use a JSON parser. In web applications over XMLHttpRequest, communication is permitted only to the same origin that provide that page, so it is trusted. But it might not be competent. If the server is not rigorous in its JSON encoding, or if it does not scrupulously validate all of its inputs, then it could deliver invalid JSON text that could be carrying dangerous script. The eval function would execute the script, unleashing its malice.
To defend against this, a JSON parser should be used.”
“For example, eval is preached against loudly, but it’s the only tool you can use to parse JSON from a server.”
you can use new Function( “return ” + data ) to parse JSON like jQuery do.
lame. can you write something that has not been written on 1500 another blogs already?
LOL @timi yeah just what I was thinking JS 101 from 6+ years ago
So what? It’s a well-written, succinct article that is sparking good discussion here. I personally don’t think these kinds of lists ever get old…No matter how long I develop, I’ll always need something like this to prevent me from getting complacent.
Great article, Andrew. Keep it up!
@timi Obviously the 1500 other blog posts have had pretty much zero effect given as baseline the atrocious JavaScript being paraded about in questions on StackOverflow.
Which of course means I doubt @AndrewBurgess’ will make much of a difference either…
Spot on!
What you said in #11 about eval being your only tool for parsing JSON isn’t true at all. In fact, if you *must* parse it as code (instead of using a proper parser like json2.js) using the function constructor would be better.
But I’m just nitpicking :p Good post!
Other mistakes:
You think your own output and skillset matches the tens of thousands of man-hours that have gone into the debugging and enforcing cross-platform compliance in frameworks like jQuery, prototype, underscore or backbone, so you don’t use them.
You don’t use QUnit, Zombie, Vows, or some other testing harness to ensure your code does, in fact, work on any browser you can get your hands on.
You don’t have Firebug or the Chrome equivalent installed.
You don’t “get” what’s so big about node.js
You don’t “get” what’s so big about coffeescript.
“You want to install some Firebug Extension to the Browser(Chrome) with the by far best Dev Tools built in.” ;)
“You think your own output and skillset matches the tens of thousands of man-hours that have gone into the debugging and enforcing cross-platform compliance in frameworks like jQuery, prototype, underscore or backbone, so you don’t use them.”
^this
People talking about
evaland JSON: You are all correct. However, the function constructor is just another form ofeval; they both do the same thing. Both should be avoided (apart from JSON). Same goes for passing strings of code tosetTimeoutandsetInterval. Of course, if the browser supportsJSON.parse, use that; I was referring to legacy browsers.Thanks for all the comments!
Andrew, you do not need to, and should not use eval on legacy browsers. You should use a JSON parser: http://www.json.org/js.html
The parser does not evaluate the code. It builds the JavaScript object by parsing the JSON as a string. This may be a bit slower than evaluating the string, but it is much safer.
Except it’s defending against a case where you’re already screwed. If you’re fetching malicious JSON then the page you’re fetching it from has already been compromised, which means the page has been compromised by arbitrary javascript already. Evalling the JSON’s not going to kill you, it’s just going to make jslint whine.
This is such an excellent set of suggestions. Very well written! Thank you so much.
Good stuff, these are all good practices I have found on books like (Eloquent JS, The Good parts)
And I agree on using braces on single lines, it’s way more readable for other developers.
All the other “javascript education tutorials” are for semi-pro’s and a beginner would get lost immediately.
Good stuff. I come from a programming background so I port over most of my good practices to Javascript anyway except using Type Wrapper Objects.
I learnt a few things tonight though, the Radix for one thing. I’ll keep that in mind in the future. Also, the Document Fragment containers is new to me but that might be because I use jQuery for all my DOM manipulation. Raw javascript is great to use performance wise for the DOM until you run into a browser specfic bug that has you reaching for palmfulls of your precious hair.
Nice tutorials there’s never enough JavaScript Tutorials cuz it’s the most complicated scripting language but thanks to framework its more sane,also is it me.i kinda noticed 90% developers here are Jquery users i guess i represent 10% using Dojo.Nice Article
Hard to find tutorials that bridge the gap between beginner, intermediate and advanced?
Thanks for some good tips. I think using double-equals is not a mistake. Both double and triple equals have their own usage; otherwise the double-equals is obsolete and should have been dropped from the language.
I’m surprised to see no mention of JSLint, given that many of this article’s recommendations came straight from it.
JSLint is a (free) tool that checks your javascript for several “bad practice” mistakes. “Bad practice” here means, “whatever Doug Crockford thinks is bad practice”.
I recommend it.
http://www.jslint.com/
JSLint is excellent. So so useful.
I’d also recommend JSHint, which is a fork of JSLint which seems to be more regularly developed and enhanced. Well worth a look.
http://jshint.org/
the == vs === applies in other programming languages as well,
I use == often, but I know what to expect, and if the case requires === than that is what I will use.
also don’t forget that if(x==true) can be written as if(x)
Amazing tips.. Just bookmarking this.. Worth the time spent reading this post
I must admit that I made some of these mistakes.
This is a good stuff material for beginner developers.
This is a great article on what not to do. I like to learn from my mistakes and I don’t plan on making them often. I guess I won’t be using wrapper objects again.
Great article. I do not use Javascript very often on websites I design because I believe that visitors do not trust server side scripting too much. None the less, it is a great language to master!
My version of the one liner looks like:
if(true) { console.log(“hello”); }
Your final example for == is incorrect (at least in IE and FF)
’0′ == ” is false
http://jsbin.com/ehuva3/2
*Mistake 3, that is.
mistake 12
————————————————–
u’re not using coffeescript & underscore
On mistake 3, using == instead of ===. You’re example is actually the exact reason I (as needed) use == instead of ===.
Often in our project I receive numbers in the form of strings (from the server, JSON). And they actually need to be compared to numbers (as numbers) in my Javascript. So while I agree, often == is actually what you might need. As long as one understands the difference between the two.
Your example of “with” is mistaken. The object passed into a “with” statement is placed at the front of the scope chain and identifier resolution starts with that object, so in the case of your example
var person = { name: “Joe”, age : 10 },
name = “Billy”;
with (person) {
console.log(name);
}
… “Joe” is sent to the console log, not “Billy”.
I learned all this rules using JSLint :)
Mistake 11 FTW
ahh… The Good Parts.
Nice tutorial, keep up the good job ;)
There are a couple problems w/ #9. First, there is no tag in (X)HTML 4 or 5. The second problem is your examples don’t accurately reflect the point that #9 is trying to make because the repaint will not occur until the “list” element has been added to the DOM. So in the example you’ve given the first snippet is no slower than the second because the “list” element is not attached to the DOM when list.appendChild(li) is called on line 8. In order for the point #9 to be meaningful you must have attached the “list” element to the DOM prior to the calling list.append(li).
Since I’ve interpreted this post as being about good vs bad JavaScript habits I must admonish your for loop construct where the boolean test is to probe the array because it causes an unnecessary array probe, which means if the array is implemented as a linkedlist it will have to be traversed twice. Thus your loop may exhibit O(n*2) behavior. A more efficient approach is the following:
var list = document.getElementById(“list”),
frag = document.createDocumentFragment(),
items = ["four", "three", "two", "one"],
el;
for (var i = items.length; i–) {
…
}
There are a couple problems w/ #9. First, there is no <list> tag in (X)HTML 4 or 5. The second problem is your examples don’t accurately reflect the point that #9 is trying to make because the repaint will not occur until the “list” element has been added to the DOM. So in the example you’ve given the first snippet is no slower than the second because the “list” element is not attached to the DOM when list.appendChild(li) is called on line 8. In order for the point #9 to be meaningful you must have attached the “list” element to the DOM prior to the calling list.append(li).
Since I’ve interpreted this post as being about good vs bad JavaScript habits I must admonish your for loop construct where the boolean test is to probe the array because it causes an unnecessary array probe, which means if the array is implemented as a linkedlist it will have to be traversed twice. Thus your loop may exhibit O(n*2) behavior. A more efficient approach is the following:
var list = document.getElementById(“list”),
frag = document.createDocumentFragment(),
items = ["four", "three", "two", "one"],
el;
for (var i = items.length; i–) {
…
}
There are a couple problems w/ #9. First, there is no <list> tag in (X)HTML 4 or 5. The second problem is your examples don’t accurately reflect the point that #9 is trying to make because the repaint will not occur until the “list” element has been added to the DOM. So in the example you’ve given the first snippet is no slower than the second because the “list” element is not attached to the DOM when list.appendChild(li) is called on line 8. In order for the point #9 to be meaningful you must have attached the “list” element to the DOM prior to the calling list.append(li).
Since I’ve interpreted this post as being about good vs bad JavaScript habits I must admonish your for loop construct where the boolean test is to probe the array because it causes an unnecessary array probe, which means if the array is implemented as a linkedlist it will have to be traversed twice. Thus your loop may exhibit O(n*2) behavior. A more efficient approach is the following:
var list = document.getElementById(“list”),
frag = document.createDocumentFragment(),
items = ["four", "three", "two", "one"],
el;
for (var i = items.length; i–;) {
…
}
P.S. Please forgive the previous revisions of this post but your comment system doesn’t allow previewing or editing.
If you would delete the earlier revisions of my comment I would appreciate it.
Thanks.
In Mistake #1, in the module pattern sample, there’s a small typo which possibly demonstrates another pitfall:
Defining multiple variables in one line/with only one var statement:
var cartTotaler = (function () {
var total = 0; tax = 0.05;
That would make “tax” global. Even in a self-invoking, anonymous function. The semikolon following “total” should be a comma, of course.
>> but it’s the only tool you can use to parse JSON.
I don’t think,
Here is the another way,
var func = new Function(“return {‘a’ : ‘b’}” );
var json = func();
These problems are some of the reasons which justify the usage of GWT in large projects or teams.
Let the IDE and the compiler to deal with all of these low level issues and spend your time producing and testing your business code.
Interesting list. I recognize alot of points from the list Javascript Garden: http://bonsaiden.github.com/JavaScript-Garden/
That is a really cool documentation on good practise with JS.
Excellent article dude, cant bear to avoid the suggestions.:)
Thanks.
Thanx for Sharing the points where we create problems. Some of the notations are very useful to improve the code.
Can anyone recommend a javascript book(s) for a beginner? I’ve read the jQuery cookbook and Learning jQuery 1.3 so I have what I would say is a basic – intermediate understanding and my html and css skills are solid, but I really want to be able to confidently write javascript without relying on one of the libraries.
Very good tutorial!
I have learned a couple of tips i did not know before.
Thank you for this.
Using eval is not as dangerous as you might think. If you use Firebug, you can inject any code to the current page code. So if someone wants to hack your site, he doesn’t need your evals. As a replacement for eval I propose “new function”.
I’m interested about #9 in using jQuery specifically.
Just curious to whom ever out there has a word on it … is there some sort of equivalent approach or common miss-practice ( w/ jQuery ) ?
! not to be misinterpreted, I completely appreciate the inclinations to learn core JS , OOP etc, but I’m jQuery for life.
Wow .. that is awesome .. Thanks for such a nice article :)
learned some of them but very useful.