In Stefanov's JS Design Patterns book, he writes "you use one var statement and declare multiple variables delimited by commas", and then gives an example of the "single var" pattern as follows:
function func() {
var a = 1,
b = 2,
sum = a + b,
myobject = {},
i,
j;
Stefanov additionally writes:
- "It’s a good practice to also initialize the variable with an initial value at the time you declare it."
- "You can also do some actual work at the time of the declaration, like the case with sum = a + b in the preceding code."
Now I have some code as follows, declaring the same number of variables with the single var pattern, but doing quite a bit more "actual work at the time of the declaration":
var html = '{purchaseQty}<br>FR: {fromLoc}'
,tpl = new Ext.XTemplate(html)
,srcReqLoc = record.get('SRC_REQUEST_LOC').trim()
,srcSupLoc = record.get('SRC_SUP_LOC').trim()
,fromLoc = srcReqLoc ? srcReqLoc : srcSupLoc
,tplCfg = {
purchaseQty: purchaseQty
,fromLoc: fromLoc
};
What are the disadvantages of doing too much "actual work at the time of the declaration"? BTW I don't consider this an exact duplicate of Javascript single var pattern. Am I overloading it? because I am asking about general disadvantages, rather than what might be wrong with just my code.
I think I can see that a general disadvantage would be inability to check errors, for instance where in my example I call trim() on strings expected back from record.get, but if undefined is returned instead, the "can't call method on undefined object" (or whatever it is ;) will be thrown. Can anybody think of anything else?
trim()
you can always write your own trim function that checks if what's passed to it is a string or not.(record.get('SRC_SUP_LOC')||"").trim()
(assuming, as per the question, that.get()
returns either a string or undefined/null).