Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript variable definition: Commas vs. Semicolons

What are the differences and/or advantages, if any, of using commas when declaring a group of variables rather than semicolons.

For example:

var foo = 'bar', bar = 'foo'; 

versus

var foo = 'bar'; var bar = 'foo'; 

I know that if you specify the var keyword on the first variable in the first example it persists across all of the variables, so they both produce the same end result regarding scope. Is it just personal preference, or is there a performance benefit to doing it either way?

like image 454
Collin Klopfenstein Avatar asked Sep 23 '10 18:09

Collin Klopfenstein


People also ask

Is semicolon required for variable declaration?

So since the first function is essentially being assigned to a variable STATEMENT the semicolon is required.

Are commas necessary in Javascript?

A comma is not an option It is truly important where you put your comma. Defining an array and enumerate elements, you must separate them with a comma. What you actually can do is omitting values. If you want to have every second entry of an array, but keep the indexes of the array.


1 Answers

No performance benefit, just a matter of personal choice and style.

The first version is just more succinct.


Update:

In terms of the amount of data going over the wire, of course less is better, however you would need a hell of a lot of removed var declarations in order to see a real impact.

Minification has been mentioned as something that the first example will help with for better minification, however, as Daniel Vassallo points out in the comments, a good minifier will automatically do that for you anyways, so in that respect no impact whatsoever.

like image 138
Oded Avatar answered Oct 05 '22 14:10

Oded