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.



Attractive things work better

That’s right. People prefer beautiful things. Clean, simple, pretty
things. It even goes so far, that we are more tolerant about a
product’s flaws (functional wise) when it’s aesthetically pleasing.
Just think about the iPhone.
The aesthetics of a product influences how we sense it. Or, to
rephrase it, how we feel about something (emotion) is tightly coupled
with how we perceive it (cognition). To find out more, check the
and read the article by Stephen Anderson.