-3

let arr1 = [1, 2, 3, 4, 5];
let arr2 = arr1;

console.log(arr1 === arr2);

arr1 = [1, 2];

console.log(arr1 === arr2);
console.log('array1 ', arr1);
console.log('array2 ', arr2);

if array is reference type, so arr2 value should be change

Andy
  • 61,948
  • 13
  • 68
  • 95
  • 2
    arr1 is being overwritten, while its referred object is still being referred by arr2. – IT goldman Sep 26 '22 at 19:43
  • 1
    arr2 contains a reference to "1,2,3,4,5", but never a reference to "arr1". – James Sep 26 '22 at 19:48
  • If you want to see how arrays are reference values, you'd need to mutate the array: `arr1.length = 2`. Not assign a different value to the variable. – Bergi Sep 26 '22 at 19:50
  • Related question: [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – Yogi Sep 26 '22 at 19:56
  • Does that mean we are creating a copy of a reference that points to an object or array? – Shubham Negi Sep 26 '22 at 20:25

1 Answers1

0

at arr1 = [1, 2] value of the array is reassigned and hence it creates a new reference.

you can read more about it here

Josal
  • 336
  • 1
  • 10