I feel like I'm missing something fundamental about JavaScript. Any help would be appreciated.
In the below code, my function takes an array as an argument. It sets a new variable newArr
equal to the input
variable.
input = [1, 2, 3, 4, 1, 3, 4];
function test(input){
var newArr = input;
newArr.splice(0,1);
return input;
};
console.log(test(input));
Now I call the splice()
method on the new variable. I thought this would only affect the new variable, leaving the input
variable unchanged.
Yet, when I return the input
variable, it has been spliced in the same way as newArr
.
The same thing happens with the push()
method. Why is this? And how can you call these methods on one variable and not another?
Fiddle here
Many thanks in advance!