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();
You can declare multiple variables in a single line. However, there are more efficient ways to define numerous variables in JavaScript. First, define the variables' names and values separated by commas using just one variable keyword from var , let or const.
If your variables are the same type, you can define multiple variables in one declaration statement. For example: int age, reach; In this example, two variables called age and reach would be defined as integers.
To define multiple variables on a single line with JavaScript, we can use the array destructuring syntax. const [a, b, c, d] = [0, 1, 2, 3]; to assign a to 0, b to 1 , c to 2, and d` to 3 with the array destructuring syntax.
Do not declare more than one variable per declaration. Every declaration should be for a single variable, on its own line, with an explanatory comment about the role of the variable. Declaring multiple variables in a single declaration can cause confusion regarding the types of the variables and their initial values.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With