At times, using a temporary array in a loop to store data becomes necessary. This is especially useful when dealing with 2-dimensional arrays. However, the question arises - is it considered bad practice to create a new array in a loop, especially if this action needs to be repeated frequently, like in animations?
for (let i = 0; i < 10000; i++) {
const temp = [];
for (let j = 0; j < 10; j++) {
temp.push(j);
}
arr.push(temp);
}
If the use of a variable is intended, one could opt for employing a global variable and assigning values to it repeatedly. Attempting to clear the array by setting temp.length = 0
may lead to unexpected outcomes since the array's reference is stored, causing all data to become the last pushed values. Another attempt was made using a global const temp = new Set()
; however, pushing the temp
set into the arr
array required arr.push([...temp])
. Therefore, is creating a new array in such situations unavoidable?