0

I feel like I'm almost grasping it... like it intuitively makes sense but I don't know the details of why. Can someone explain:

Why here, global arr is NOT affected outside the function

arr = [1,2,3]
function test(arr, a, b) { 
  arr = arr.filter(item => (a < item  && item < b)) 
  console.log(arr) // [2]
}

test(1, 3)
console.log(arr) // [1,2,3]

Why here, global arr IS affected outside the function

arr = [1,2,3]
function test(a, b) { 
  arr = arr.filter(item => (a < item  && item < b)) 
  console.log(arr) // [2]
}

test(1, 3)
console.log(arr) // [2]

EDIT another example. Why here global arr IS affected outside the function EVEN THOUGH once again arr is passed as a parameter

arr = [1,2,3]
function test(arr, a, b) {
  for (let i = 0; i < arr.length; i++) {
    let val = arr[i];
    if (a >= val || val >= b) {
      arr.splice(i, 1);
      i--;
    }
  }
  console.log(arr) // [2]
}
console.log(arr) // [2]
james
  • 3,989
  • 8
  • 47
  • 102
  • Possible duplicate: [What is the scope of variables in JavaScript?](https://stackoverflow.com/q/500431/8173752) – Endenite Oct 04 '17 at 19:27
  • You need to rewrite your question because your code wouldn't work at all. You're trying to use the filter method on a number. – zfrisch Oct 04 '17 at 19:34

1 Answers1

0

The first function declares arr as a parameter.

Inside the function, arr refers to the parameter, not the global variable.

This is called a scope.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • THAT was super helpful, but it led to me a third scenario where `arr` is declared as a parameter but the global variable is still affected... can you take a quick look? – james Oct 04 '17 at 19:36
  • @james: Now you're mutating the object, not setting a variable. – SLaks Oct 04 '17 at 20:05
  • well i guess the confusion is that, i don't have an `arr =` in the function anymore, so it's true that i'm not setting a variable, but per the previous logic, it'd seem that i'm mutating the parameter passed, versus the global variable? is that not right? – james Oct 04 '17 at 20:09