0

I'm needing to compare the previous state of an array length with a later state (not referring to state syntax). I thought the task was as simple as assigning the variable to a new variable at the point in time you want to capture, then just use that variable to compare with the main variable later, i.e;

let x = [1, 2];
const y = x;
function test() {
    x.push(3, 4);
    console.log(x.length > y.length);
}
test();

But for some reason this returns

false

I only have this issue when using push(). As soon as x.push(3, 4) is executed for some reason y is updated to have the same values as x after pushing in more data. This confuses me because they're in different scopes and executed at different times? Is there something magical I don't understand about push()?

srb633
  • 793
  • 3
  • 8
  • 16
  • 1
    Basically, `y` is a reference to `x`, not a copy. Use `slice()` or `const y = [...x];` to make a copy. – Heretic Monkey May 22 '20 at 13:58
  • Interesting, so the state of an array is almost like a scopeless object (reference). I'm a little loose with my understanding of the spread operator, how does it function to make the array a copy exactly? – srb633 May 22 '20 at 14:01
  • If you want to compare just a previous length, then store just the previous length: let `prevLength = x.length;`. Arrays are objects in Javascript and objects are assigned by pointer. So, when you do `const y = x`, you now have a pointer to the same object in both variables `y` and `x`. They literally point at the same object so, of course, when you change that object, both variables are looking at the same object so they see the change. This has nothing to do with scope. The array's length, is a number which is a primitive in Javascript so when you assign it, you get a separate static copy. – jfriend00 May 22 '20 at 14:01
  • This is great thank you, `const y = [...x];` was certainly the most helpful solution. Should post it as a response. – srb633 May 22 '20 at 14:09

0 Answers0