Search code examples
javascriptarraysglobal-variables

Manipulate global variable as parameter in function


I'm currently learning JavaScript and have a question about following code.

var testArr = [1, 2, 3, 4, 5];

function nextInLine(arr, item) {
  arr.push(item);
  arr.shift();
}

console.log("Before: " + testArr);
nextInLine(testArr, 6);
console.log(" After: " + testArr);

The output is:

Before: 1,2,3,4,5

After: 2,3,4,5,6

I'm expecting no change in testArr and Before and After to be the exact same, because function-parameters are not global, as far as I know.

But the function actually manipulates the global variable testArr even though it's never mentioned in the function and just put in as a parameter.

I'd be very thankful if somebody could explain to me, why testArr is being manipulated in the function and how I could change that.


Solution

  • There is no such thing as passing a variable by value or by reference in JS as there is in other programming languages such as C++. The way you can deal with such things is to create a copy of the object you want to temporary modify. You can see the difference below

    function changeAgeImpure(person) {
        person.age = 25;
        return person;
    }
    var alex = {
        name: 'Alex',
        age: 30
    };
    var changedAlex = changeAgeImpure(alex);
    console.log(alex); // -> { name: 'Alex', age: 25 }
    console.log(changedAlex); // -> { name: 'Alex', age: 25 }

    alex is a global variable but as you can see it is changed by the function changeAgeImpure.

    The way you solve such things (in my example at least) is this way:

    function changeAgePure(person) {
        var newPersonObj = JSON.parse(JSON.stringify(person));
        newPersonObj.age = 25;
        return newPersonObj;
    }
    var alex = {
        name: 'Alex',
        age: 30
    };
    var alexChanged = changeAgePure(alex);
    console.log(alex); // -> { name: 'Alex', age: 30 }
    console.log(alexChanged); // -> { name: 'Alex', age: 25 }

    Now the alex variable will not be changed by the function as we have created an intermediate.