Changing Array In Javascript Function Changes Array Outside Of Function?
Solution 1:
This is the difference between assignment to a local variable and mutation of the given object.
In both pieces of code arrs
is a local variable, distinct from data
. But the elements and other properties of arrs
are exactly the same as those of data
. Making changes to those property values (which is commonly called mutation of the object/array) will be visible whether you access them via arrs
or via data
. And this is exactly what the first script does.
The second script however, does not change a property value of arrs
, but assigns an entirely new value to arrs
, so that now it does not share any properties any more with data
. This is even more apparent, because both data
and arrs
are primitive values which cannot mutate like explained in the previous paragraph. But even if they were objects or arrays, and you would do the following assignment:
arrs = [1234];
It would not affect data
. data
would only be affected if you would assign to a property/index of arrs
without assigning to arrs
directly.
Solution 2:
First variant modifies object passed as parameter to function (which happens to be array) - so this change is seen outside function. Second variant assigns new value to function parameter (which happens to be reference to array) but does not change array itself.
Post a Comment for "Changing Array In Javascript Function Changes Array Outside Of Function?"