Search code examples
javascriptscopeclause

Javascript variable in function changes global variable


i have a huge problem figuring out scopes and clauses. I want to have a tmp variable, that i remove one element from. But the global variable should stay intact. This is what iv´e come up with. This;

var test = ['test', 'huhu'];

function foo(bar) {

    var tmpTest = test;
    var index = tmpTest.indexOf(bar);

    if (index > -1) {
        tmpTest.splice(index, 1);
    }
    console.log(tmpTest);
}

foo('huhu');
console.log(test);

Should produce this;

test
test, huhu

But produces this;

test
test

I also tried to make var tmpTest = new Array(test); But this stops the splicing from working. I guess what´s happening is that when i set tmpTest = test, tmpTest just becomes a reference to the original test variable? How can i come around this?


Solution

  • Arrays are objects. Objects in JavaScript are manipulated by references. Assigning a reference does not involve making a copy of the object; it's merely a copy of the reference. Thus, your tmpTest variable is just another reference to the same object.

    There's a simple way to make a copy of an array:

      var tmpTest = test.slice(0);
    

    That constructs a new array with all the same values as the original.

    The Array() constructor can be invoked with one or more arguments, but the arguments are not interpreted as being an array to make a copy of. If it's invoked with one number argument, that's interpreted as an initial .length value for the array. More than one argument creates a new array with those values.