I’ve been doing some maintenance work on a few sites (all originally developed by different people) and I have noticed a lot of JavaScript code like this:
function MM_findObj(n, d) { //v4.01
var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
if(!x && d.getElementById) x=d.getElementById(n); return x;
}
A few minutes of effort can improve the readability.
function MM_findObj(name)
{
var doc = document;
var x;
if((var p = name.indexOf("?")) > 0 && parent.frames.length != 0)
{
doc = parent.frames[name.substring(p + 1)].document;
name = name.substring(0, p);
}
if(!(x = doc[name]) && doc.all)
{
x = doc.all[name];
}
for (var i = 0; !x && i < doc.forms.length; i++)
{
x = doc.forms[i][name];
}
for(var i = 0; !x && doc.layers && i < doc.layers.length; i++)
{
x = MM_findObj(name, doc.layers[i].document);
}
if(!x && doc.getElementById)
{
x = doc.getElementById(name);
}
return x;
}
I am curious as to why JavaScript tends not to be written in a readable way? Of the sites that I have worked on – and have had nothing to do with the initial development – condensed, poorly formatted and unreadable JavaScript is definitely a trend I have noticed. Is it merely to reduce the amount of space that scripts take up on pages or is it just poor technique?
Edit: To add to this question, why does single character variable names also seem to be the norm?
P.S. By no means am I an expert, in fact I am barely proficient, with JavaScript so if anybody could also explain what the above code actually does then it’d be much appreciated.
There are very commonly-used tools that take JavaScript code and remove unneeded whitespace and shorten variable names, producing code like this, or worse. It saves network bandwidth, and keeps casual lookie-loos from reading your code (very poor security by obscurity.)
Normally the code doesn’t look like this when people are working on it; this is just done when the code is about to ship.