What anti-patterns are there for JavaScript?

I find that not doing is a difficult lesson to learn than what needs to be done.

In my experience, what separates the expert from the intermediate is the ability to choose from different, seemingly equivalent, ways to do the same thing.

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

I can find a lot of them for Java, but since the typical JavaScript context (in the browser) is very different from Java, I am curious to see what happens.

+47
javascript anti-patterns
Dec 18 '08 at 2:30 p.m.
source share
10 answers

Language:

  • A namespace that is polluting, creating a large footprint of variables in a global context.

  • Binding event handlers of the form "foo.onclick = myFunc" (irrational, attachEvent / addEventListener should be used).

  • Using eval in almost any context other than JSON

  • Almost all uses document.write (use DOM methods like document.createElement)

  • Prototyping an Object (BOOM!)

  • This is small, but the implementation of large quantities of string concat with "+" (creating an array and combining it is much more efficient)

  • Turning to a nonexistent constant undefined

Design / Deployment:

  • (usually) not supporting noscript support.

  • Do not pack your code into one resource

  • Entering inline (i.e. body) scripts at the top of the body (they block loading)

Ajax Specification:

  • without specifying the start, end or error of the request to the user

  • poll

  • XML submission and parsing instead of JSON or HTML (if necessary)

edit: I keep thinking more!

+46
Dec 18 '08 at 14:38
source share
— -

Besides the already mentioned ...

  • Using the for..in construct to iterate over arrays
    (iterating over array methods and indexes)

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

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

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

  • Relying on implicit statements without using semicolons
    (bad picking habit and may lead to unexpected behavior)

  • Using / * .. * / to lock lines of code
    (may interfere with regular expression literals, for example: /* /.*/ */ )

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

+19
Dec 18 '08 at 18:54
source share

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

  • Using the hierarchy of objects and creating very deep chains of inheritance. Small hierarchies work fine in most cases in JS.
  • Not understanding the orientation of objects based on prototypes and instead creating a huge number of forests to make JS behave like traditional OO languages.
  • Without the need to use OO paradigms when procedural / functional programming can be more concise and efficient.

Then there are those used at browser runtime:

  • Do not use good event patterns, such as event delegation or an observer pattern (pub / sub) to optimize event handling.
  • Perform frequent DOM updates (e.g. .appendChild in a loop) when DOM nodes can be in memory and added at a time. (HUGE increase in efficiency).
  • Using libraries to select nodes with complex selectors when you can use your own methods (getElementById, getElementByTagName, etc.). This is becoming a problem these days, but worth mentioning.
  • Extending DOM objects if you expect third-party scripts to be on the same page as yours (you will eventually burn each other).

And finally, deployment problems.

  • Do not shrink your files.
  • Web server configurations - not gzipping your files, not caching them wisely.

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

+10
Dec 19 '08 at 12:00
source share

A few things right on my head. I will edit this list when I think more.

  • Do not pollute the global namespace. Instead, organize things in objects;
  • Do not skip var. This pollutes the global namespace and can cause you problems with other such scenarios.
+8
Dec 18 '08 at 14:37
source share
  • browser detection (instead of checking if there are specific methods / fields that you want to use)
  • using alert () in most cases

see also Crockford "Javascript: The Good Parts" for other things to avoid. ( edit:) , it is a little strict in some of its sentences, such as using "===" over "==", so take them with something like salt salt for you)

+8
Dec 18 '08 at 14:50
source share

any use of 'with'

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

+6
Dec 18 '08 at 15:09
source share

any link to

 document.all 

in your code, unless it is in special code, only for IE to overcome IE error. (cough document.getElementById () cough)

+5
Dec 18 '08 at 14:44
source share

Do not use a community-based environment to perform repetitive tasks such as DOM manipulation, event handling, etc.

+4
Dec 18 '08 at 15:03
source share

Poor use of parenthesis positioning when creating statements

You should always put a bracket after the instruction because of the automatic insertion of a semicolon.

For example:

 function() { return { price: 10 } } 

very different from this:

 function(){ return{ price: 10 } } 

Becuase in the first example, javascript inserts a semicolon for you, actually leaving you with this:

 function() { return; // oh dear! { price: 10 } } 



Using setInterval for potentially lengthy tasks.

You should use setTimeout instead of setInterval for cases when you need to do something repeatedly.

If you use setInterval, but the function that runs in the timer is not complete by the time the next timer ends, this is bad. Use the following template instead using setTimeout

 function doThisManyTimes(){ alert("It happening again!"); } (function repeat(){ doThisManyTimes(); setTimeout(repeat, 500); })(); 

This is very well explained by Paul Irish on his 10 things I learned from the jQuery video source.

+3
Mar 31 '11 at 20:51
source share

Effective caching is rarely performed:

  • Do not store a copy of the library (jQuery, Prototype, Dojo) on the server if you can use a common API, for example, the Google library APIs to speed up page loading.
  • Combine and reduce all your scripts that you can add to one
  • Use mod_expires to give all your scripts an infinite cache lifetime (never load)
  • Return your javascript file names so that the new update is accepted by clients without the need to reboot / restart (i.e. myFile_r231.js or myFile.js? R = 231)
+1
Mar 31 '11 at 20:38
source share



All Articles