views:

1437

answers:

8

I find that what not to do is a harder lesson to learn than what should be done.

From my experience, what separates an expert from an intermediate is the ability to select from among various seemingly equivalent ways of doing the same thing.

So, when it comes to JavaScript what kinds of things should you not do and why?

I'm able to find lots of these for Java, but since JavaScript's typical context (in a browser) is very different from Java's I'm curious to see what comes out.

+6  A: 

A few things right on top of my head. I'll edit this list when I think of more.

  • Don't pollute global namespace. Organize things in classes instead;
  • Don't omit 'var' for variables. That pollutes global namespace and might get you in trouble with other such scripts.
Vilx-
Note that jslint (http://www.jslint.com/) will issue a warning for both of these, so it can be helpful in cases where you've forgotten 'var' and are creating a global variable by accident, for example.
thomasrutter
+33  A: 

Language:

  • Namespace polluting by creating a large footprint of variables in the global context.

  • Binding event handlers in the form 'foo.onclick = myFunc' (inextensible, should be using attachEvent/addEventListener).

  • Using eval in almost any non-JSON context

  • Almost every use of document.write (use the DOM methods like document.createElement)

  • Prototyping against the Object object (BOOM!)

  • A small one this, but doing large numbers of string concats with '+' (creating an array and joining it is much more efficient)

  • Referring to the non-existent undefined constant

Design/Deployment:

  • (Generally) not providing noscript support.

  • Not packaging your code into a single resource

  • Putting inline (i.e. body) scripts near the top of the body (they block loading)

Ajax specific:

  • not indicating the start, end, or error of a request to the user

  • polling

  • passing and parsing XML instead of JSON or HTML (where appropriate)

edit: I keep thinking of more!

annakata
On the last point in AJAX, the X stands for XML, If you aren't passing XML, you aren't even doing AJAX, you are doing AJAJSON, or maybe just AJAJ. I'm not sure what the difference is between passwing JSON and passing XML.
Kibbee
Yeah I know what the X stands for :) Alot of the time the A is false as well. It's just an unfortunate umbrella term for stuff a lot of us were doing ages ago. FYI the difference between JSON and XML is large, but critically JSON is lighter and is in a native format JS doesn't need to parse.
annakata
AJAX is now used as an umbrella term, like DHTML. Although strictly speaking you're correct. Anything that allows for Asynchronous communication with the server is AJAX in my book.
Allain Lalonde
@annakata: Why not post each of these as a separate answer. That way, you get more points and the best single answer floats to the top?
Allain Lalonde
Kibee, I think that is just a purely pedantic distinction. This is what everybody means by the term AJAX so I think it is just irrelevant. Just forget about AJAX as an acronym and think of it as the thing we all mean.
BobbyShaftoe
@Allain: karma is irrelevant compared to putting the answer in one easy to find place - besides I was under the impression this was the preferred approach on SO (confirm anyone?)
annakata
I agree mostly with this - except the last part about XML. I think that's a flavor choice. I like my data output to come in XML because then it's easily accessible to different kinds of applications. Using a library like jQuery also makes traversing XML as simple as accessing a JSON property.
Andy Baird
@andybaird - why can't you expose JSON and XML? My apps typically work with XML internally and XSLT to JSON where required. jQuery makes it easy, but JSON still performs better there.
annakata
@annakata - I don't see the need to do both when one works just fine for both. May perform better, but it's marginal enough that I'd rather save the development time.
Andy Baird
@andybaird - we'll call it personal choice then, but imho you'll gain mileage out of a write-once JSON serialiser and the dev overhead is minimal.
annakata
What sort of 'polling' are you referring to under 'Ajax specific'? A lot of JS frameworks like jQuery do their own polling of the DOM or the XMLHttpRequest object, for instance. jQuery for example has lots of "setTimeout" calls with comments like "continually check to see if the document is ready".
thomasrutter
+5  A: 

any reference to

document.all

in your code, unless it is within special code, just for IE to overcome an IE bug. (cough document.getElementById() cough)

scunliffe
+6  A: 
  • browser detection (instead of testing whether the specific methods/fields you want to use exist)
  • using alert() in most cases

see also Crockford's "Javascript: The Good Parts" for various other things to avoid. (edit: warning, he's a bit strict in some of his suggestions like the use of "===" over "==" so take them with whatever grain of salt works for you)

Jason S
yeah alert is pretty ugly :)
annakata
also I take issue with some of the things Crockford says (e.g his stance on with and continue)
annakata
the exception on browser detection is if the browser reports that it supports a method or property, but you know that the implementation is wrong/flawed. IE supports elem.setAttribute(name,value) but it certainly doesn't support it correctly.
scunliffe
@annakata: good point, i do too
Jason S
+3  A: 

Not using a community based framework to do repetitive tasks like DOM manipulation, event handling, etc.

Allain Lalonde
My personal choice would be jQuery, but the actual framework matters little. As long as it's not home grown.
Allain Lalonde
I sort of disagree with this - Sometimes a special solution is better than a general one and I have quite a lot of my own JS which I believe superior to jQueries equivalent. Possible I should give this stuff to jQuery actually, but the point is the masses aren't always right.
annakata
then we'll agree to disagree. :) Even if your personal framework is a better match, the testing you'd have to do, you get for "free" by using a community based approach.
Allain Lalonde
well not really, I've been dragging this chunk of code with me for 5 years now :)
annakata
Dragging is an apt metaphor. :)
Allain Lalonde
I kinda feel that the big frameworks are a bit bulky, when you want to use a small subset of things. Probably YUI has the right idea in this regard in that you can just load the modules you need, though it is very verbose for what it does. But if you chop down jQuery to size you get into a situation where it's like maintaining your own jQuery fork. I don't know what the answer is
thomasrutter
+5  A: 

any use of 'with'

with (document.forms["mainForm"].elements) {
input1.value = "junk";
input2.value = "junk"; }

Greg Dean
I wonder if this will stop being an issue when we get better code analysis tools for Javascript
Allain Lalonde
strongly disagree with this, Crockford is wrong here
annakata
See here: http://stackoverflow.com/questions/61552/are-there-legitimate-uses-for-javascripts-with-statement for a discussion of "with"; IMHO, there's at least one valid use for it, probably more... but as a means of scope control, not a convenience for modifying object members.
Shog9
+8  A: 

Besides those already mentioned...

  • Using the for..in construct to iterate over arrays
    (iterates over array methods AND indices)

  • Using Javascript inline like <body onload="doThis();">
    (inflexible and prevents multiple event listeners)

  • Using the 'Function()' constructor
    (bad for the same reasons eval() is bad)

  • Passing strings instead of functions to setTimeout or setInterval
    (also uses eval() internally)

  • Relying on implicit statements by not using semicolons
    (bad habit to pick up, and can lead to unexpected behavior)

  • Using /* .. */ to block out lines of code
    (can interfere with regex literals, e.g.: /* /.*/ */)

    <evangelism> And of course, not using Prototype ;) </evangelism>

Triptych
Anyone know why i was marked down? I'm new and am not sure if I broke some sort of rule...
Triptych
I don't know. I've voted you up. I like most of your answers.
Allain Lalonde
Probably because you use Prototype instead of jQuery... it seems like the SO crowd is very jQuery biased?
Chris MacDonald
@Chris. That would be ridiculous. I added a wink!
Triptych
Doesn't mean it isn't so ;) - personally I'd upvote you if you'd written "prototype" though :)
annakata
@annakata You mean I shouldn't have capitalized?
Triptych
<3 Prototype. And prototypes. And prototyping, for that matter.
Matt Kantor
+4  A: 

The biggest for me is not understanding the JavaScript programming language itself.

  • Overusing object hierarchies and building very deep inheritance chains. Shallow hierarchies work fine in most cases in JS.
  • Not understanding prototype based object orientation, and instead building huge amounts of scaffolding to make JS behave like traditional OO languages.
  • Unnecessarily using OO paradigms when procedural / functional programming could be more concise and efficient.

Then there are those for the browser runtime:

  • Not using good established event patterns like event delegation or the observer pattern (pub/sub) to optimize event handling.
  • Making frequent DOM updates (like .appendChild in a loop), when the DOM nodes can be in memory and appended in one go. (HUGE performance benefit).
  • Overusing libraries for selecting nodes with complex selectors when native methods can be used (getElementById, getElementByTagName, etc.). This is becoming lesser of an issue these days, but it's worth mentioning.
  • Extending DOM objects when you expect third-party scripts to be on the same page as yours (you will end up clobbering each other's code).

And finally the deployment issues.

  • Not minifying your files.
  • Web-server configs - not gzipping your files, not caching them sensibly.

<plug> I've got some client-side optimization tips which cover some of the things I've mentioned above, and more, on my blog.</plug>

Rakesh Pai