TKEz TKEz - 3 months ago 13
jQuery Question

jQuery - commas vs. semicolons

I'm working on some jQuery code that a previous developer wrote. I am trying to understand when/why a person would use commas to separate statements as opposed to semicolons.

In the below example, is it safe to say that there is no benefit to using a comma to separate the statements? If yes...why, if no... is there a situation in which it would make sense to use commas?

FYI: This questions is about chaining statements and whether or not there is a benefit. Not about what the comma does in the statements.

var $some_field_1, $some_child_field, $some_field_2, $some_child_field_2;

function a() {

$some_field_1 = jQuery(".field_class"), $some_child_field = $some_field_1.find("input"), RunSomeFunction(), $some_field_2 = jQuery(".field_class_2"), $some_child_field_2 = $some_field_2.find("input");

}


VS.

var $some_field_1, $some_child_field, $some_field_2, $some_child_field_2;

function a() {

$some_field_1 = jQuery(".field_class");

$some_child_field = $some_field_1.find("input");

RunSomeFunction();

$some_field_2 = jQuery(".field_class_2");

$some_child_field_2 = $some_field_2.find("input");

}


I hope this makes sense. Thanks all!

Answer

Normally commas are used to separate out variable declarations, but the version you have shown is using them to separate out expressions. While this is nuanced, it is still significant.

Note that all of the expressions are assigning variable names to the global scope (technically the Lexical Environment in the case of your example, it is possible those variables are defined in a more local scope than the global one).

A better example would have been

var one = 1, two = 2, sum = function(a,b){ return a+b; };

Note that if you tried to call a function in the variable declaration here it would have caused an Uncaught SyntaxError: Unexpected token (.

As all of the declarations are inherently prefaced by the var and are therefore local variables (in the Variable Environment).

Contrast the example with

one = 1, two = 2, sum = function(a,b){ return a+b; }, sum(one,two);

which is essentially your example in the question, and the difference is mostly the scope of the variables and also that as each is simply an expression, the function call is allowed.

More on the Comma operatorMDN

Comments