1

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 $this = $(this),
    $body = $("body"),
    $main-wrap = $("body > section.wrapper");

OR

var $this = $(this);
var $body = $("body");
var $main-wrap = $("body > section.wrapper");

I always thought that the difference only lies in notation. The first example is shorter and possibly faster to execute. Recently I did some testing and now I am not sure anymore. Can anyone clear this up?

Is there a difference in execution speed, result, method?

Community
  • 1
  • 1
Bram Vanroy
  • 22,919
  • 16
  • 101
  • 195

2 Answers2

4

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

Community
  • 1
  • 1
Brad Christie
  • 96,086
  • 15
  • 143
  • 191
0

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

Community
  • 1
  • 1
Scrimothy
  • 2,453
  • 11
  • 23