I’ve noticed a JavaScript behavior that does not agree with my understanding of variable scope and was hoping that someone could clarify:
[CODE]function change(arr)
{
var tmp1 = arr[0];
var tmp2 = arr[1];
arr[0] = arr[2];
arr[1] = tmp1;
arr[2] = tmp2;
}
var arr = [‘cat’, ‘dog’, ‘parrot’];
change(arr);
alert(arr.join(‘,’)); //results in “parrot, dog, cat”
In the above code, the function accepts an array, puts the third item at the beginning, and moves the other two to the right. If you’ll notice, however, the function does [I]not[I]local
So how come the resulting alert is “parrot, dog, cat?” Even though the function operated only on the array it was given, it affected the original array.
Note that in this example the original array is [I]not
[CODE]function change(arr)
{
arr = [‘monkey’, ‘mouse’, ‘ferret’];
}
var arr = [‘cat’, ‘dog’, ‘parrot’];
change(arr);
alert(arr.join(‘,’)); //This time, alert is “cat, dog, parrot.”