Search code examples
javascriptchaining

JS - Adding key to one variable adds it to all the variables created in chained assignment


I have created an object and assigned it to 3 variables like so

var barChartOptions, longChartOptions, scatterOptions;
barChartOptions = longChartOptions = scatterOptions = {
    legend: {
        display: false
    },
    scales: {
        ...
    }
};

also tried

var barChartOption = longChartOptions = scatterOptions = {
    legend: {
        display: false
    },
    scales: {
        ...
    }
};

Then I tried to add a key to one of the variables. This key is only specific to this one variable and rest of the object is same for all the variables.

longChartOptions.aspectRatio = 3;

Now, all three variables have the key aspectRatio. Why is this happening? I understand if I define the three variables seperately the problem will not occur but the object is quite long and I wanna keep the code DRY.


Solution

  • You can use the spread operator to copy an object to another variable.

    var barChartOption = {...longChartOptions} = {...scatterOptions} = {
        legend: {
            display: false
        },
        scales: {
          // ...
        }
    };
    

    Actually, when you use = sign to copy an object to a variable javascript copies the reference of the object to that variable. So when you change anything on any of the variable it also reflects the other one.

    To get rid of this you can use the spread operator or the process mentioned by @CertainPerformance.