# Use Caution When Reinitializing Variables Inside a Loop[suggestions/opinions]

Tell us what’s happening:
This may be rather an off topic, but I was wondering what if I were to create 2-D array of any given numbers of rows and columns, which of the following function is more preferable?

My function

``````function zeroArray(m,n){
let array=[];
for(let i=0;i<m;i++){
array[i]=[];
for(let j=0;j<n;j++){
array[i].push(0);
}
}
return array;
}
``````

Most of the common solutions found in this forum

``````function zeroarray(m,n){
let newArray = [];
let row = [];
for(let i=0;i<n;i++){
row.push(0);
}
for(let i=0;i<m;i++){
newArray.push(row);
}
return newArray;
}
``````

User Agent is: `Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36`.

The first has an embedded loop with j iterations for each value of i, and you get 3 x 2 = 6 iterations total. The second splits up the loops and has 3 + 2 = 5 iterations total so will be faster than the first: not much of a difference,

But if i = 10 and j = 10, then the first gives you 100 iterations, and the second will give you 20 iterations.

So the larger the values of i and j, the second approach will be faster.

function zeroArray(m,n){
var ray = new Array(m);
for(var i = 0; i < ray.length; i++){
ray[i] = new Array(n);
}
return ray;
}
var test = zeroArray(3, 3); // Will result a 3 x 3 array (or whatever the dimensions you wish)
console.log(test.length); // 3
console.log(test[0].length); // 3

1 Like