0

I'm not understanding why, in a file where I define a React class, a variable assigned to an import and one that is never mutated still changes.

import statuses from '../statuses'; // array of 6 items

class MyComponent extends React.Component {

  constructor(props) {
    super(props);
    this.statuses = statuses;
  }

  render() {
    const statusOptions = this.statuses;
    if (statuses.length === statusOptions.length) statusOptions.push(obj);
    console.log(statuses.length); // 7 (?!?!)
  }
}

I have no idea why statuses would be updated at all, and why it would get mutated as if it were statusOptions here. (To be clear, I also logged statuses itself, and sure enough, obj had been pushed to the array.

Koushik Chatterjee
  • 4,106
  • 3
  • 18
  • 32
zahabba
  • 2,921
  • 5
  • 20
  • 33

2 Answers2

3

statuses, this.statuses and statusOptions are all references to the same object.

Push to one, and it'll appear in all three.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • 1
    See something like [this question](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) to better understand how javascript deals with variables. – fetherolfjd Jul 26 '17 at 21:22
1

All three variable are the same, share same reference. You can use:

this.statuses =JSON.parse(JSON.stringify(statuses))

var a=[1,2,3]
var b=a;
c=JSON.parse(JSON.stringify(a));
a.push(4);

console.log(b);
console.log(c);

This is like this.statuses=statuses , but changing one variable does not affect another one.

Vlado Pandžić
  • 4,879
  • 8
  • 44
  • 75