Declare multiple variables in JavaScript

No, your second statement will create four references to the same array. You want:

var src_arr     = [],
    caption_arr = [],
    fav_arr     = [],
    hidden_arr  = [];

Yes, it is if you want them all to point to the same object in memory, but most likely you want them to be individual arrays so that if one mutates, the others are not affected.

If you do not want them all to point to the same object, do

var one = [], two = [];

The [] is a shorthand literal for creating an array.

Here's a console log which indicates the difference:

>> one = two = [];
[]
>> one.push(1)
1
>> one
[1]
>> two
[1]
>> one = [], two = [];
[]
>> one.push(1)
1
>> one
[1]
>> two
[]

In the first portion, I defined one and two to point to the same object/array in memory. If I use the .push method it pushes 1 to the array, and so both one and two have 1 inside. In the second since I defined unique arrays per variable so when I pushed to one, two was unaffected.


Please stay away from that assignment pattern, even if you wanted to have all variables pointing to the same object.

In fact, only the first one will be a variable declaration, the rest are just assignments to possibly undeclared identifiers!

Assigning a value to an undeclared identifier (aka undeclared assignment) is strongly discouraged because, if the identifier is not found on the scope chain, a GLOBAL variable will be created. For example:

function test() {
    // We intend these to be local variables of 'test'.
    var foo = bar = baz = xxx = 5;
    typeof foo; // "number", while inside 'test'.
}
test();

// Testing in the global scope. test's variables no longer exist.
typeof foo; // "undefined", As desired, but,
typeof bar; // "number", BAD!, leaked to the global scope.
typeof baz; // "number"
typeof xxx; // "number"

Moreover, the ECMAScript 5th Strict Mode, disallows this kind of assignments. Under strict mode an assignment made to a non-declared identifier will cause a TypeError exception, to prevent implied globals.

By contrast, here is what we see if written correctly:

function test() {
    // We correctly declare these to be local variables inside 'test'.
    var foo, bar, baz, xxx;
    foo = bar = baz = xxx = 5;
}
test();

// Testing in the global scope. test's variables no longer exist.
typeof foo; // "undefined"
typeof bar; // "undefined"
typeof baz; // "undefined"
typeof xxx; // "undefined"