View Single Post
Old 10-10-2012, 05:52 AM   PM User | #3
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,237
Thanks: 59
Thanked 3,998 Times in 3,967 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
Even if the array is *NOT* global, changes made in a function *WILL* affect its value in the caller. That's because in JavaScript *ALL* objects are passed by reference, and an array *IS* an object.

Here's a clear demo of that:
Code:
<script type="text/javascript">
function one( ary1 )
{
    ary1[0] = "banana pudding";
    ary1[3] = "zamboni";
}
function two( ary2 )
{
    alert( ary2.join("\n") );
}
function test() 
{
    var ary = [ 1, 2, 3 ];
    one( ary );
    two( ary );
}
test( );
</script>
As you can see, the array ary is *NOT* a global. Yet when we pass it to function one( ) it's first element is changed, as is proven when we then pass the same variable to function two( ).

And, as you can see, we can even add elements to the array and the added elements are carried back to the caller and then to the second callee.

THERE IS ONLY ONE ARRAY in all that code. The names ary, ary1 and ary2 are all actually referencing the same array.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote