Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing array in JavaScript function changes array outside of function?

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");
like image 236
Tom Tom Avatar asked Nov 14 '22 04:11

Tom Tom


1 Answers

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.

like image 151
trincot Avatar answered Nov 16 '22 04:11

trincot