1

If I declare two variables to be equal to each other and then I edit one of them, will both variables still be equal? For example, if I do this:

let arr1 = [2, 3, 4, 5];
let arr2 = arr1;
var c = arr1.pop()
console.log(arr1); // prints [ 2, 3, 4 ]
console.log(arr2); // prints [ 2, 3, 4 ]

Both variables are still equal even though I have not stated arr2 = arr1 after the pop function. However, if I redeclare the array:

let arr3 = [2, 3, 4, 5];
let arr4 = arr3;
arr3 = [1];
console.log(arr3); // prints [ 1 ]
console.log(arr4); // prints [ 2, 3, 4, 5 ]

arr4 maintains its value.

Could someone explain to me why this is so? Thank you!

Ashley
  • 13
  • 3
  • in your first example you reference the arr2 to arr1. That means that the `arr2` is pointing to the adress in the memory of `arr1` and that means that `arr1` and `arr2` pointing to the same adress in the memory and if you change in `arr1` some value then ofcorse `arr2` will change too because they point at the same adress. in your second example you assigned `arr3` to an value. – bill.gates Mar 18 '20 at 06:58
  • How is assigning arr3 to a value different? – Ashley Mar 18 '20 at 07:13
  • when u write `arr4 = arr3` that means that `arr4` is pointing on the same adress in the memory like `arr3`. Then you did `arr3 = [0];` That means that `arr3` is no longer pointing to the adress of `[2, 3, 4, 5]` its now pointing to the adress of `[1]`. Now `arr3` is pointing to `[1]` and `arr4` is still pointing on his adress with the value `[2, 3, 4, 5]` – bill.gates Mar 18 '20 at 07:37
  • Ohh ok, thank you!! – Ashley Mar 18 '20 at 08:03

0 Answers0