jquery/javascript: best practices (concerning structure and readability)

Status
Not open for further replies.

uviathon

Ars Scholae Palatinae
1,333
For years my focus has been server-side stuff, but I'm now being tasked with client-side. If anyone knows of some recognized best-practices guides, I'd love to read them. In addition, I'd appreciate hearing some comments on the following items I'm dealing with while trying to edit code written by someone else:

1. The javascript file I'm currently working with starts with the following. I'm only including the top for sake of size, and because this isn't a troubleshooting question (I'm adding functionality, not fixing problems), and because this region relates to my question, specifically:

Code:
var _defaultSettings = {
            iSelAllIndex: 0,
            iDocTypeIndex: 2,
            iUploadedByIndex: 4,
            iIsNewDataIndex: 5,
            iIsCompanyOnlyDataIndex: 6,
            iFilesDataIndex: 8,
            iHighlightDataIndex: 10,
            oSettings: this,
            newEntryImgHTML: "<img src=\"/images/New_icons_41.gif\" ></img>",
            entryDownloadedImgHTML: "<img src=\"/images/checkmark.png\" ></img>",
            downloadButtonImgHTML: "<img src=\"/images/download.gif\" ></img>",
            CompanyOnlyHTML: "<img src=\"/images/Padlock.png\"  ></img>",
            "sGetEntryListService": "/Services/Secure/EntriesList.asmx/GetEntryListForJQueryDataTable",
            "sGetDocTypesWithFilesUploadedService": "/Services/Secure/EntriesList.asmx/GetDocTypesWithFilesUploaded",
            "sGetUploadedByUsersService": "/Services/Secure/EntriesList.asmx/GetUploadedByUsers",
            "sPageSizeService": "/Services/Secure/EntriesList.asmx/GetOrSetEntryListSize",

            "aoColumns": [{ sTitle: "Date", sName: "EntryDate", sWidth: "110px", bUseRendered: false,
                fnRender: function (oObj) {
                    var str = oObj.aData[oObj.iDataColumn];
                    var isNew = oObj.aData[oSettings.iIsNewDataIndex];
                    var dateTime = new Date(parseInt(str.substr(6)));
                    var dateHtml = $.datepicker.formatDate("mm/dd/yy", dateTime);
                    
                    if (isNew)
                        dateHtml = dateHtml + oSettings.newEntryImgHTML;
                    return "<span title=\"" + dateTime.toString() + "\">" + dateHtml + "</span>";
                }
            },
                { sTitle: "EntryType", sName: "EntryType", sWidth: "240px", bUseRendered: false,
                    fnRender: function (oObj) {
                        
             -----------------------------

So, if I'm reading this correctly, it starts by defining a variable, which is set to the value of a JSON object, whose 17th or so key:value pair is an array, each element of which is a JSON objcet, each of which contains at least one function. The array has at least 20 elements (I gave up counting after that), and there are more pairs after the array.

On this, I'm asking if this is the generally accepted way to write it? I find it nauseating to read. When I'm down to the 20th element of the array, the curly braces for functions and JSON data start to kind of run together. If nothing else, I guess it seems to negatively affect readability to write everything "inline." But, if this is just the way these things are done, I'll force myself to get used to it.


2. Is it common/recommended/accepted practice to preface the type before the variable name in camel case (ie. sTitle)? I never saw the c# devs I worked with do this, and I never do it. I usually only saw it this when editing other people's VB6 and VB.NET code.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
2. Is it common/recommended/accepted practice to preface the type before the variable name in camel case (ie. sTitle)?

nope, this is Hungarian Notation and it is widely viewed as a bad idea in the modern age.

In dynamic languages some might argue it helps, I have no significant experience on anything that wasn't so small as to be trivially understandable in this area so can't give a personal opinion but certainly strongly consider adding "s" to the variable "title" should be utterly redundant...
 

Faramir

Ars Legatus Legionis
36,356
Subscriptor
Hungarian notion applied religiously with the variable type is obnoxious. As I understand it though, the original idea behind the scheme was that you would use it like typedef (or obsessive typing in e.g. java).

So if you have an int that represents the difference between two quantities you prepend the variable name with d. Then when you see a line that says "int dFoo = foo1 - foo2" it will look right, but if you see a line that says "int dFoo = foo1 * foo2" you will rightly be brought up short.

Frankly this seems like it would be even more important in a dynamic language since there are no types at all. That said, I haven't read enough in-the-wild javascript to say what is or isn't idiomatic.
 

Dracorat

Ars Tribunus Militum
2,798
As far as best practices go, I've taken to placing all the onLoad page events in to separate functions.

It just feels easier to manage.

Example:

Code:
$(document).ready(function(){
  $('#AbandonMessageId').change(ChangeAbandon());
  $('#SubscriptionMessageId').change(ChangeSubscription());
});

function ChangeAbandon()
{
  // Work here;
}

function ChangeSubscription()
{
  // Work here;
}

Rather than using the inline functions the examples use repeatedly.

I used to use the inline functions, but then management took longer than I liked. Having discrete broken-out functions lets me wrap up the code I need in to neat packages without it all being onelongrunonpieceofcode...

At least, it feels that way - to me. I know it's not a huge difference - code is code is code no matter where it's at. But there's just something about it.

So there you have it. My one best practice that I wanted to share.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
Then when you see a line that says "int dFoo = foo1 - foo2" it will look right, but if you see a line that says "int dFoo = foo1 * foo2" you will rightly be brought up short.

It would astonish me that someone could say with a straight face they would want something like this but use a dynamic language (except when forced into it, a la javascript[1]). They're basically crying out for *really* strong typing.

1. of course you could write in something far higher level and 'compile' to javascript...
 

Faramir

Ars Legatus Legionis
36,356
Subscriptor
ShuggyCoUk":26qf01di said:
Then when you see a line that says "int dFoo = foo1 - foo2" it will look right, but if you see a line that says "int dFoo = foo1 * foo2" you will rightly be brought up short.

It would astonish me that someone could say with a straight face they would want something like this but use a dynamic language (except when forced into it, a la javascript[1]). They're basically crying out for *really* strong typing.

1. of course you could write in something far higher level and 'compile' to javascript...

Personally I can't stand dynamically typed languages, but as you say one can't entirely avoid javascript these days. I use cross-compilers, but there are dragons there as well.
 

grahamb

Ars Praefectus
3,900
Subscriptor
So, if I'm reading this correctly, it starts by defining a variable, which is set to the value of a JSON object, whose 17th or so key:value pair is an array, each element of which is a JSON objcet, each of which contains at least one function. The array has at least 20 elements (I gave up counting after that), and there are more pairs after the array.

Nitpick: the variable _defaultSettings contains an Object literal, not a "JSON Object". JSON (JavaScript Object Notation) is a data interchange format that happens to look like an object literal. That object literal isn't valid JSON: not all the keys are quoted, functions aren't a valid type in JSON, etc.
 
Status
Not open for further replies.