Trace Trace - 3 months ago 15
jQuery Question

What are the benefits of commas compared to semicolons in jQuery?


Possible Duplicate:

Declaring Multiple Variables in JavaScript




I was setting some variables in jQuery and someone suggested I do it this way:

var $wrapper = that.parents(".wrapper"),
$prettyCheckBox0 = $wrapper.find(".prettyCheckbox small:eq(0)"),
$prettyCheckBox1 = $wrapper.find(".prettyCheckbox small:eq(1)"),
$prettyCheckBox2 = $wrapper.find(".prettyCheckbox small:eq(2)"),
standard = $prettyCheckBox0.parents("span").parents("label").prev("input").val(),
professional = $prettyCheckBox1.parents("span").parents("label").prev("input").val(),
premium = $prettyCheckBox2.parents("span").parents("label").prev("input").val();


Though this works, I was wondering if anyone has a reason on why to pick commas over semicolons. How does it work? It seems like it would cause syntax errors. Also, why is there one one
var
?

Answer

The end of your question contains the answer to the beginning: var can be used for defining multiple variables in the same statement, like this:

var a = 1, b = "foo", bar = xyzzy(), baz = $('#something');

This is what happens in your snippet, and it's equivalent to

var a = 1;
var b = "foo";
var bar = xyzzy();
var baz = $('#something');

There isn't an objective benefit from picking one over the other, it is a matter of coding style/convention.

Comments