1

Listening to udemy, we find that arrays and objects are references, and assigning an already declared array to a new variable (e.g. arr2) itself copies the pointer of an existing array, not a value.

However, if you reallocate the existing array arr itself declared as let at all, why does arr2 output a value before the reallocation rather than the reallocated arr1 value?

let arr1 = [0, 1, 2, 3];
let arr2 = arr1;

arr1.shift();
console.log(arr2); // [ 1, 2, 3]

arr1[0] = 3;
console.log(arr2); // [ 3, 2, 3]

why [0, 1, 2, 3] print?

let arr = [0, 1, 2, 3]
let arr2 = arr

arr = [3, 2, 1, 0]

console.log(arr2) // [0, 1, 2, 3]

solution

'ar2' refers to the memory address of the array '[0, 1, 2, 3]' that 'ar' refers to.

'ar' simply refers to the memory address of the new array '[3, 2, 1, 0]

If 'ar' points to a new array, 'ar2' still points to the memory address of array '[0, 1, 2, 3]'!

So the value was the same.

최석규
  • 46
  • 5
  • There's no such thing as reallocation or pointers in javascript. – Ouroborus Nov 22 '22 at 06:28
  • See also questions linked to the referenced Q&A, e.g. [reassigning javascript objects](/q/58551188/4642212), [Why this code references different result](/q/58103131/4642212), etc. – Sebastian Simon Nov 22 '22 at 06:31
  • You already have the concept of pointers vs actual. So let's call `[0,1,2,3]` as `x` and `[3,2,1,0]` as `y`. arr1 = x ; arr1 points to x. arr2 = arr1 ; **arr2 points to x (it doesn't point to arr1, it points to x**. Both have the same *value* `x`, so change one and the other changes (your first snippet). Now, in your 2nd snippet: arr1 = y ; arr1 now points to y, **arr2 still points to x**, because arr2 pointed to x, not to arr1 – freedomn-m Nov 22 '22 at 06:40
  • Thank you freedomn-m ! Thanks to your comment, I found a clue :) – 최석규 Nov 22 '22 at 16:36

0 Answers0