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];

console.log(stuff)

var other = stuff;

console.log(other)

var test = other.splice(1);

console.log(stuff);
//outputs [1] showing that using splice on the 'other' variable modified 'stuff' as well. Why?
console.log(other);
//outputs [1] as expected because splice modifies the original array while providing the removed elements to the variable 'test'
console.log(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;

console.log(numbers);

var copyNumbers = numbers;

console.log(copyNumbers);

var testNumbers = copyNumbers+1;

console.log(testNumbers);
//outputs 2 exactly as you would expect.
console.log(copyNumbers);
//outputs 1 exactly as you would expect, it's unaffected by any changes to the other vars. 
console.log(numbers);
//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

3 Likes