0

I am trying to empty an array passed to a function within javascript:

var a = [1,2,3];

function emptyArrayNo(ar) {
    // the following does not empty the global array
    ar = [];
}

function emptyArrayYes(ar) {
    // any of the following 3 methods empties the global array
    ar.length = 0;
    //ar.splice(0, ar.length)
    //while(ar.length > 0) {ar.pop();} 
}

emptyArrayNo(a);
console.log(a); // returns [1,2,3]

emptyArrayYes(a); 
console.log(a); // returns []

All the three methods within emptyArrayYes() seem to work, which I think is due to the reference to the array passed not being modified within the function. However when we set the array to [] within the function, I believe the reference changes therefore causing issues i.e. not being seen at the global scope. Can someone please clarify what is going on here? Thanks.

owl7
  • 308
  • 1
  • 3
  • 9
  • 1
    Reassigning the parameter alone doesn't do anything, because that only affects further references to the parameter name lower in the function. Only way to do something like that would be to reassign the `a` variable name instead (`a = []`), but that isn't very flexible because it's not something you can pass. Another option would be to do `a = emptyArrayNo()` where `emptyArrayNo` returns `[]` – CertainPerformance Oct 05 '19 at 05:49
  • 1
    Check the second duplicate: [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000) – adiga Oct 05 '19 at 05:56
  • Thanks, the second duplicate gave a clear answer to this. I was trying to find an example of array reassignment within a function before posting, thinking that arrays were pass-by-reference and hence were treated differently to passing an Int (pass-by-value), when being reassigned. So here it's just pass-by-value with the reference being the value, and the value is clearly modified to a new reference i.e. []. Cheers. – owl7 Oct 05 '19 at 06:38

0 Answers0