TechSelfLearner
TechSelfLearner

Reputation: 397

issues with redux payload in reducers

I have the following code for one of the CASES in reducers

case CHART_CHANGE: {
            const {method,copiedArray} = payload;

            let ref = copiedArray  
            
            let swapped = bubblesort(copiedArray) //<------here

            console.log(ref)
            console.log(swapped)
          }

      }

The question is this, as you can see here I assigned the variable ref before involving the bubblesort function. But when I run the program, ref variable has the same value with the swapped variable. Why is that?

Upvotes: 0

Views: 29

Answers (1)

marzelin
marzelin

Reputation: 11610

In javascript objects (arrays are objects) are assigned by reference, so copiedArray and ref are referring (pointing) to the same object. If you change the contents of the object (and your bubblesort function seems to sort in place - that is mutate/change the array internally), the changes are visible in all of the variables: copiedArray, ref and swapped.

const copiedArray = [3,2,1];
const ref = copiedArray;
const swapped = copiedArray.sort();

console.log(copiedArray);
console.log(ref);
console.log(swapped);

Upvotes: 2

Related Questions