How to make push, unshift, pop and move to work only with the local array in javascript?

advertisements

I have a function to describe my problem:

function testingFunc(value) {
  var temp = value;
  console.log("temp before:    " + JSON.stringify(temp));
  console.log("arrayTest before:    " + JSON.stringify(arrayTest));
  temp.unshift(123);
  console.log("temp after unshift:    " + JSON.stringify(temp));
  console.log("arrayTest after unshift:    " + JSON.stringify(arrayTest));
  temp.push(456);
  console.log("temp after push:    " + JSON.stringify(temp));
  console.log("arrayTest after push:    " + JSON.stringify(arrayTest));
  temp.shift();
  console.log("temp after shift:    " + JSON.stringify(temp));
  console.log("arrayTest after shift:    " + JSON.stringify(arrayTest));
  temp.pop();
  console.log("temp after pop:    " + JSON.stringify(temp));
  console.log("arrayTest after pop:    " + JSON.stringify(arrayTest));
  return temp;
}

var arrayTest = [1,2,3,4,5];
var arrayTestTwo;

arrayTestTwo = testingFunc(arrayTest);
console.log("arrayTest after testingFunc:    " + JSON.stringify(arrayTest));
console.log("arrayTestTwo:    " + JSON.stringify(arrayTestTwo));

As you can see, arrayTest will change too if temp change by using push, unshift, pop and shift to edit it's data.

But I want those function to work ONLY with temp and ignore arrayTest.

Is it possible? Also is it possible to work with object contains functions?

And why is this happen?


When you assign an array to a variable (or passing it as an argument to a function), you are only storing a reference to that array. If two or more variables are referencing the same array, making changes to one will affect all the others as well:

var original = [];
var modified = original;
console.log(original, modified); // [] []

modified.push(1, 2, 3);
console.log(original, modified); // [1,2,3] [1,2,3]

The way to solve this is to make a copy of the array. To make a copy of an array, you just call array.slice():

var original = [];
var modified = original.slice();
console.log(original, modified); // [] []

modified.push(1, 2, 3);
console.log(original, modified); // [] [1,2,3]