Why the two scripts behave differently? I want the to use the first script, but in the second drawData()
call it changes data
; it's weird and not what I want to happen. The second script does not have this problem. Why is it like that, and how can I fix the first script?
First script does not change data
:
var data = ["right"];
function drawData(arrs, type) {
if (type == "percentage") {
arrs[0] = "omg";
}
console.log(data[0]); // Changed!?
}
drawData(data);
drawData(data, "percentage");
Second script:
var data = "right";
function drawData(arrs, type) {
if (type == "percentage") {
arrs = "omg";
}
console.log(data); // OK, not changed.
}
drawData(data);
drawData(data, "percentage");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With