Skip to content Skip to sidebar Skip to footer

Difference In Listing Variables In Javascript

Possible Duplicate: Declaring Multiple Variables in JavaScript I was wondering whether there is a difference in listing variables in JavaScript (and JS libraries). Example: var

Solution 1:

That's not jQuery that just plain-jane JavaScript variable declaration.

As far as a difference, there isn't one. The only speed increase you could acquire would be to stop spinning up multiple jQuery objects and re-reference existing ones for further processing. e.g.

var body = $('body'),
    wrapper = body.children('section.wrapper');

See also JavaScript variable definition: Commas vs. Semicolons

Solution 2:

I broke the habit of using multiple var statements when I started using jsLint. It always caught that and said that it was faster to separate by a comma.

Looking into this more, there seem to be many sources that agree with this.

From jsLint #scope

It is recommended that a single var statement be used per function.

From A List Apart:

The var statement defines one or more variables. Sometimes you’ll see code that looks like this:

var image = document.getElementById("myImage");
var div = document.getElementById("myDiv");

This code defines two variables, one right after the other. I often see this pattern for 10 or more variables in a row. Doing so artificially inflates the size of your code because multiple var statements can be combined into one using a comma operator:

var image = document.getElementById("myImage"),
div = document.getElementById("myDiv"); 

This code also defines two variables and provides the same initialization. However, you’ve saved the three bytes that another var would have cost. Three bytes might not seem like a big deal, but if you’re able to find dozens of places where there’s currently an extra var statement, the savings can really add up.

However,

here are two fairly compelling reasons to use multiple var statements from SO posters. and here

Post a Comment for "Difference In Listing Variables In Javascript"