0

I might be getting things wrong, but I know at least that I don't want this behaviour.

I have a while loop in JS, inside a function. Global vars are passed into the function.

Yet when the loop runs, the global variables are changed, alongside the ones inside the function.

Example

var arr = [0, 1, 2, 3, 4, 5];
var i = 0;

function test(myArr)
{
    while(i < 2)
    {
        myArr.pop();
        i++
    }

    console.log(arr);
    console.log(myArr);
}

test(arr);

The console spits out

[ 0, 1, 2, 3 ]
[ 0, 1, 2, 3 ]

Why is the global being affected?

Mr Pablo
  • 4,109
  • 8
  • 51
  • 104

0 Answers0