Javascript tips I.

Today I stumbled on two articles about Javascript dos and don’ts. Most
of it is common sense and practiques you develop naturally if you mean
it seriously with Javascript. However there were a couple of tricks
that caught my attention.
1. Smart looping through an array of elements:

var rows = document.getElementsByTagName('tr'); for( var i = 0, row; row = rows[i]; i++ ) {   // do stuff with rows here }

2. Reduce reflow.
3. Cache complex objects:

var cached = (function () {   var privateObj = {    option1: 500,    option2: 1000   };   return function (arg) {    // foo();   }; })();

Now you can do


which will have access to the variables defined in the privateObj. This object is created only once, hence the speed-up.



Share your thoughts

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s