tags:

views:

148

answers:

7

Reading Crockfords The Elements of JavaScript Style I notice he prefers defining variables like this:

var first='foo', second='bar', third='...';

What, if any benefit does that method provide over this:

var first='foo';
var second='bar';
var third='...';

Obviously the latter requires more typing but aside from aesthetics I'm wondering if there is a performance benefit gained by defining with the former style.

+5  A: 

Since JavaScript is generally downloaded to the client browser, brevity is actually quite a valuable attribute. The more bytes you have to download, the slower it gets. So yes, there is a reason apart from aesthetics, if not a massive one.

Similarly, you'll see people preferring shorter variable names to longer.

Personally, I don't bother minimising whitespace, as there are minimisers that can do this sort of thing for you (for example in YUI), and lack of indentation and spacing leads to less maintainable code.

David M
-1: You should minify your JavaScript if you are serving it yourself. Not optimize it for faster downloads, shortening variable names and declaring variables in one line.
roosteronacid
Yes, agreed. My point is that I prefer to maintain non-minified code in source control, and then minify it prior to deployment. I think we're talking at cross purposes.
David M
So you are worried about performance when developing on your local machine or using an internal server for pre-deployment testing?
roosteronacid
Don't fully understand your question. When I deploy a CSS file to any non-local environment, I make sure that it will always be served in a minified form. When I open it in my IDE I make sure that it will always be in a less minified form as it is easier to maintain that way. Does that make more sense?
David M
+1  A: 

I believe that what he is going for is declaring all variables as abosultely the first statement in a function (You'll notice that JSLint complains about this if you use it and don't declare them on the first line). This is because of JavaScript's scope declaration limitations (or quirks). Crockford emphasizes this as good practice for maintainable JavaScript code. The second example declares them at the top, but not in the first execution statement. Personally, I see no reason as why to prefer the first over the second, but following the first does enforce that all variables are declared before doing anything else in the function.

David is right that the larger the script the more time it will take to down load, but in this case the difference between the two is minimal and can be handled by using YUI compress etc.

Kevin
+1  A: 

It's a personal programming style choice.

On the one hand there is readability, wherein placing each variable declaration on a separate line makes it more obvious what's going on.

On the other hand, there is brevity, wherein you're eliminating transmitting a few extra bytes over the network. It's generally not enough to worry about, unless you're dealing with slow networks or limited memory on the client browser side.

Brevity is also known as laziness on the part of the programmer, which is one reason that many purists avoid it.

Loadmaster
Laziness, of course, is a virtue. But being lazy about typing or transmitting the code, as opposed to reading and debugging it, is *false laziness*, a terrible vice.
Jason Orendorff
+3  A: 

No difference in semantics and no measurable difference in performance. Write whichever is clearest.

For simple examples like:

var first= 'foo', second= 'bar', third= 'bof';

the concise single-statement construct is probably a win for readability. On the other hand you can take this much too far and start writing half your program inside a single var statement. Here's a random example plucked from the jQuery source:

var name = match[1],
    result = Expr.attrHandle[ name ] ?
        Expr.attrHandle[ name ]( elem ) :
        elem[ name ] != null ?
            elem[ name ] :
            elem.getAttribute( name ),
    value = result + "",
    type = match[2],
    check = match[4];

I find this (by no means the worst example) a bit distasteful. Longer examples can get quite hard to read upwards (wait, I was in a var statement?) and you can end up counting the brackets to try to work out what's a multi-line expression and what's just an extended var block.

bobince
I don't exactly disagree; but the jQuery guys have an especially strong and unusual reason to be terse. If they can scrimp and save a few hundred bytes, that means *they get to add another feature to the library* while staying under their self-imposed size limit (jQuery is about 19KB on the wire, minified and gzipped).
Jason Orendorff
+2  A: 

Aside of aesthetics, and download footprint, another reason could be that the var statement is subject to hoisting. This means that regardless of where a variable is placed within a function, it is moved to the top of the scope in which it is defined.

E.g:

var outside_scope = "outside scope";
function f1() {
    alert(outside_scope) ;
    var outside_scope = "inside scope";
}
f1();

Gets interpreted into:

var outside_scope = "outside scope";
function f1() {
    var outside_scope; // is undefined
    alert(outside_scope) ;
    outside_scope = "inside scope";
}
f1();

Because of that, and the function-scope only that JavaScript has, is why Crockford recommends to declare all the variables at the top of the function in a single var statement, to resemble what will really happen when the code is actually executed.

CMS
This is one of the places I strongly disagree with Crockford's Strictures. It's more work to keep shifting variable declarations up to the top every time you change anything inside a function, and it's easy to make a mistake that leaves you with the dreaded unintentional global. Especially with longer functions that might have multiple independent uses of one named variable (typically `i`).
bobince
+1  A: 

It all comes down to personal taste or a set of style-guides, your development team follows. If you are serving JavaScript yourself, you usually compress or minify your script(s) into one long string in one single file. So the whole you-are-saving-bytes-and-your-scripts-download-faster argument is, well, not an argument :)

I usually declare my variables like this: (a style you didn't mention)

var something,
    somethingElse,
    evenMoreSomething,
    andAnotherThing;
roosteronacid
+1  A: 

A statement like "var" is not minified/compressed.
Every time you place a var, instead of a coma you loose 4 chars if I count right.

Mic
It's not minified, but it's certainly affected by gzip/deflate. You'll still save a tiny amount, but it's not anything really worth worrying about.
bobince