I want to declare multiple variables in a function:
function foo() {
var src_arr = new Array();
var caption_arr = new Array();
var fav_arr =
For all intents and purposes the literal []
notation syntax should be used. Since the Array constructor is ambiguous in how it deals with its parameters.
From the docs:
If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with its length property set to that number. And that implies
Array
of passed length of empty slots withundefined
values.
new Array(1, 2, 3); // Result: [1, 2, 3]
new Array(3); // Result: [empty × 3] with undefined at indexes
new Array('3') // Result: ['3']
//this was ambiguous
let x = new Array(5); // Result: [empty × 5]
x.push("Hello"); //expected x as ["Hello", empty, empty, empty, empty]
//Actual x: [empty × 5, "Hello"]
Destructuring syntax:
Another neater way to declare multiple variables is using destructuring assignment which enables unpacking values from arrays, or properties from objects, into distinct variables.
function foo() {
//destructuring assignment syntax
let [src_arr, caption_arr, fav_arr, hidden_arr] = [[], [], [], []];
console.info("Variables::", fav_arr, hidden_arr, caption_arr, src_arr);
fav_arr.push("fav");
hidden_arr.push("hidden");
//After adding some values to couple of arrays
console.info("Variables::", fav_arr, hidden_arr, caption_arr, src_arr);
}
foo();