Declaring a variable with another variable. Strange behaviour

Hello forum!

I have encountered some behaviour that I can seem to understand. Please see code below:

function someFunction(arr) {
  const someArr = arr;
  someArr.push(1, 2, 3);
  console.log(arr);
//logs [arr, 1, 2, 3] but why?
  console.log(someArr);
//also logs [arr, 1, 2, 3] as expected.
}

My question is a follows:
Why does changing contents of the array someArr also changes the contents of the array arr ?
I have tried searching the forum and the web, but couldn’t find much (or couldn’t formulate my search query properly).

Any explanations or hints of where (or how) to look for an explanation are highly apreciated.

Thanks and stay heathly.

There are two types of variables in JavaScript

  • Primitive variables (numbers, boolean values, etc)

  • Object variables (to include arrays)

The thing is, a variable can only hold one piece of data. So for more complex data, such as objects and arrays, the data that is stored in the variable is the location in your computer’s memory where the full object or array is stored.

In this case, arr holds the location of an array. The line const someArr = arr (not the most descriptive name) creates a new variable that hold the contents of arr, which is the same location in memory.

This means that you have two variables ‘pointing’ at the same place in your computer’s memory, and using either variable results in changes at the same memory location.

You want to instead copy your array and make someArr (or whatever you want to call it) point instead at this copy of the array.

1 Like

If you want to look ahead to where this is covered in the freeCodeCamp curriculum, it’s in the Functional Programming section.

2 Likes

Thank you very much.
You response filled a gap in my my knowledge and saved me some confusion further down the road (and yes, I will also pay more attention to having descriptive names for my variables).
Edit: I have been directed to the fCC section where this is described.:+1:

1 Like