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).
var stuff = [1,2,3]; console.log(stuff) var other = stuff; console.log(other) var test = other.splice(1); console.log(stuff); //outputs  showing that using splice on the 'other' variable modified 'stuff' as well. Why? console.log(other); //outputs  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?