1

What is the purpose of separating code using commas instead of moving to the next line?

For example, I found this code:

var fm = $.NSFileManager.defaultManager,
oURL = $.NSURL.fileURLWithPathIsDirectory(strPath, true),
lstFiles = ObjC.unwrap(
    fm.contentsOfDirectoryAtURLIncludingPropertiesForKeysOptionsError(
        oURL, [], 1 << 2, null
    )
),
lstHarvest = [];

I don't see it often but it feels like a run on sentence.

Update:
I think I see what is going on but I rarely ever see this. Is it ES5, ES6 thing?

1.21 gigawatts
  • 16,517
  • 32
  • 123
  • 231

4 Answers4

4

This is the syntax for var :

var varname1 [= value1] [, varname2 [= value2] ... [, varnameN [= valueN]]];

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var

note that the presence of initializations (=) is irrelevant.

Why use this syntax ?

  • to avoid repeating var. Compare :

    var a, b, c, d, e
    

    or

    var a,
        b,
        c,
        d,
        e
    

    versus

     var a
     var b
     var c
     var d 
     var e
    
  • sometimes a matter of style and preference

  • in some places you must use this syntax to declare several variables because you can't use several lines, (e.g. in a for loop header : for (var a = 0, b = 3; ... ; ...))


Note that this is not the same thing as having new lines ! (the other lines after first would not be var variable declarations, see What is the purpose of the var keyword and when to use it (or omit it)? for the differences).

Your example would however be equivalent without commas at the end and with var at beginning of each others.


Is it ES5, ES6 thing?

It is the syntax since ECMAScript 1st edition (1997)

https://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%201st%20edition,%20June%201997.pdf

(page 63 / 110 of the pdf file, section 12.2, variable statement)

Pac0
  • 21,465
  • 8
  • 65
  • 74
2

There is just one var used for initializing multiple Variables. You can also do this (I think this is much better and more readable):

var fm = $.NSFileManager.defaultManager;
var oURL = $.NSURL.fileURLWithPathIsDirectory(strPath, true);
var lstFiles = ObjC.unwrap(
    fm.contentsOfDirectoryAtURLIncludingPropertiesForKeysOptionsError(
    oURL, [], 1 << 2, null));
var lstHarvest = [];
fawee
  • 395
  • 3
  • 13
2

Like most other languages like c,c++ we can declare

int a,b,c;
char x='1',y='2'; 

like this javascript also allow us to this . Simple :)

RaM PrabU
  • 415
  • 4
  • 16
1

Using the comma allows the programmer to omit var at the beginning of each declaration/definition. It's up to your preferred style to decide which form is used but be consistent.

Brandon H. Gomes
  • 808
  • 2
  • 9
  • 24