Declare multiple variables in JavaScript

FFish picture FFish · Nov 2, 2010 · Viewed 37.1k times · Source

I want to declare multiple variables in a function:

function foo() {
    var src_arr     = new Array();
    var caption_arr = new Array();
    var fav_arr     = new Array();
    var hidden_arr  = new Array();
}

Is this the correct way to do this?

var src_arr = caption_arr = fav_arr = hidden_arr = new Array();

Answer

meder omuraliev picture meder omuraliev · Nov 2, 2010

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.