The Weird behavior of splice with variables

I’ve noticed that splice has a very odd behavior with variables which have been assigned the values of other variables and I don’t understand how this is, because it doesn’t happen with any other operations that I can think of.

When you take the value of a variable, and assign it as the value of another variable and then use splice on the second variable, it actually modifies the original variable too. This would not happen if you were to operate on the second variable in any other way(that I can think of right now).

Splice Example:

var stuff = [1,2,3];


var other = stuff;


var test = other.splice(1);

//outputs [1] showing that using splice on the 'other' variable modified 'stuff' as well. Why?
//outputs [1] as expected because splice modifies the original array while providing the removed elements to the variable 'test'
//outputs the removed elements as expected

it looks like other is not actually assigned the value of stuff, but in the case of split() is treated like a symbolic link to the variable ‘stuff’. Other points to stuff.

This seems inconsistent with how variables work normally, which can be demonstrated like so:

var numbers = 1;


var copyNumbers = numbers;


var testNumbers = copyNumbers+1;

//outputs 2 exactly as you would expect.
//outputs 1 exactly as you would expect, it's unaffected by any changes to the other vars. 
//outputs 1 exactly as you would expect, it's unaffected by any changes to the other vars.

It looks like I’m fundamentally misunderstanding how the assignment operator works. Why is the variable ‘stuff’ affected by operating on the variable ‘other’?

I understand that splice modifies the array it’s working on, so other SHOULD be changed, but it doesn’t make sense to me that ‘stuff’ is paired with other in any way.

Why does the number example treat assignment as copying the value of the first var into a new var, but with splice they behave as a linked pair?

What you’re seeing is because stuff is an array. With complex data types, a variable actually holds a memory location for the object. When you do var other = stuff, you are creating another variable that refers to the same memory address. It does not create a complete copy of the object. If you modify other, you are also modifying stuff.

Thanks, that makes sense. Primitives are copied to new variables, objects(of which arrays are) are treated as a reference to the same singular object in memory instead of being copied.

I also located a more in depth explanation of this just moments ago, if anyone else is still struggling.

you got it dude