0

In the following example, when I log to the console, I get ["c","b","a"] for all three arrays.

let x = Array.from("abc");
let y = x;
let z = y.reverse();
console.log({x:x, y:y, z:z})

y = ["c", "b", "a"] because Array.prototype.reverse() reverses the array in place

z = ["c", "b", "a"] because I reversed y and then assigned it to z

but why does x = ["c", "b", "a"]?

3
  • 2
    you do not assign a new array, but took the same object reference. Commented Oct 20, 2020 at 18:24
  • you need to do deep copy if you want to keep original Commented Oct 20, 2020 at 18:26
  • no, you don't need a deep copy - a shallow copy is enough Commented Oct 20, 2020 at 18:28

2 Answers 2

1

The script only ever creates a single array:

let x = Array.from("abc");

The Array.from creates the array and assigns it to x.

let y = x;

The above creates the y variable name and points it to the same array.

let z = y.reverse();

The above reverses the array in-place, and also creates the z variable name and points it to said array.

The array is never cloned, so x, y, and z are all referring to the same array in memory.

Sign up to request clarification or add additional context in comments.

2 Comments

I figured this is what was happening. Is there a way to check whether two variables point to the same object in memory?
Something like x === y
1

when you are assigning y = x you are passing reference of x. So copy x by spread operator.

let x = Array.from("abc");
let y = [...x];
let z = y.reverse();
console.log({x:x, y:y, z:z})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.