0

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!

ibhhvc
  • 255
  • 2
  • 12

3 Answers3

2

It looks like I was missing the fact that I need to clone the array, not just assign it to a new variable.

It seems like there are many ways to do this, one of which looks like this:

input = [1, 2, 3, 4, 1, 3, 4];

function test(input){
  var newArr = input.slice(0); // clones array
  newArr.splice(0,1);
  return input;
};

console.log(test(input));
ibhhvc
  • 255
  • 2
  • 12
1

In javascript a var that receive an object from another var isn't a copy, but a reference.

http://snook.ca/archives/javascript/javascript_pass

Ian Ramos
  • 414
  • 7
  • 16
1

Array assignment does not copy the array. Both newArr and input point to the same object.

Patrick Fournier
  • 600
  • 6
  • 19