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();
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
The
[]is a shorthand literal for creating an array.Here’s a console log which indicates the difference:
In the first portion, I defined
oneandtwoto point to the same object/array in memory. If I use the.pushmethod it pushes 1 to the array, and so bothoneandtwohave1inside. In the second since I defined unique arrays per variable so when I pushed to one, two was unaffected.