I see a lot of 'interesting' JavaScript working with CRM installations that have been in operation for more than a couple of years.

Last week, I found the ultimate example of not knowing how to utilize the CRM object model.  CRM 4.0 in this case:

for (var i = 0; i < crmForm.all.length; i++)
{
    var crmField = crmForm.all[i];
    if (crmField.title != null && crmField.title != 'undefined'
            && crmField.id != null && crmField.id != 'undefined'
                && crmField.id != '')
    {
        var fieldName = crmForm.all[i].id;
        var eventType = crmForm.all.new_eventType.DataValue;

        if (crmField.id.indexOf('new_name') == 0)
        {
            if (fieldName == 'new_name')
            {
                switch (eventType)
                {
                }
            }
        }
    }
}

What is this code doing?

The idea here, and I am making an assumption, is to find the 'new_name' field then perform some action.

The first thing you will notice is that we are looping through all of the objects found in the CRM form.  I checked and there were 2,607 objects in crmForm.all.  That is a lot of looping.

Also, as you can see, there are lots and lots of checks to make sure we have the correct field.  Once we have the correct field, we perform some specific actions.

A better way?

This code is totally unnecessary and it actually delayed the loading of the form.

Here is all that was needed:

if (crmForm.all.new_name != null &&
    crmForm.all.new_name.DataValue != null)
{
}

As you can see, this is much less code, it is easier to understand, and is much quicker.

Lessons Learned

First and foremost, know and understand your tools.  When in doubt, perform a search for the specific thing you are looking to do.  By now, there should be plenty of JavaScript samples that cover a variety of topics so finding something that is close to what you wish to do, should not be that hard.

If that fails, I would suggest visiting the Dynamics CRM Community Forums where the experts hang out.