Javascript Quick Tips - a truly new array
You have probably noticed the following, perhaps surprising, behavior of Array objects:
var a = [1, 2, 3];
var b = a;
b = b.reverse();
alert(b); // returns "3, 2, 1"
alert(a); // returns "3, 2, 1" too !
This is because var b = a; does not create a new Array object, rather, it makes the variable b point to (or reference) the previously defined array. So any changes made to this array by either variable a or b will be reflected by both variables.
Usually, this behavior is pretty transparent and does not interfere with the expected outcome of your code (it actually often comes in handy). It is also much less resource intensive. Sometimes, however, it can be a drag when, for example, you need to keep a copy of the original array.
Luckily there is a simple solution to this issue, it is rather hackish, but only takes one line:
var a = [1, 2, 3];
var b = [].concat(a);
b = b.reverse();
alert(b); // returns "3, 2, 1"
alert(a); // returns "1, 2, 3"
The key to it lies in the second line (var b = [].concat(a)), which could be re-written as such:
var b = []; // creates a new array
b = b.concat(a); // add each element of the array "a" to the array "b"
If you run into this issue often and do not want to clutter your code with concat() all over the place, one possible solution would be to create a small global function to cleanly implement the above hack.
function newArray(arr) {
return [].concat(arr);
}
var a = [1, 2, 3];
var b = newArray(a);
b = b.reverse();
alert(b); // returns "3, 2, 1"
alert(a); // returns "1, 2, 3"
Please note that I do absolutely not recommend you to use the newArray() function (or any similar implementation you would have made) instead of the built-in constructor (whether you choose to go with the new Array() or [] syntax). You should use the above only when you need to keep an untouched original of the array you are working on. In other words, do not unnecessarily eat resources up!