0

I've recently learned about pass-by-reference. So I expected the behaviour of arr2, but have trouble understanding why arr1 is not changed outside of the function. Someone please enlighten me?

let arr1 = ([1, 2, 3, 4])
let arr2;
let a = 1
let b = 3
filterRange(arr1, a, b);

function filterRange(arr1, a, b) {
  arr2 = arr1.filter(item => {
     return ((item >= a) && (item <= b)) ? item : "";
  });
  arr1 = arr1.filter(item => {
     return ((item >= a) && (item <= b)) ? item : "";
  });
  return
}

console.log(arr1) // [1, 2, 3, 4]
console.log(arr2) // [1, 2, 3]
Lorenz Mueller
  • 140
  • 3
  • 11
  • 1
    You've created a variable `arr1` inside the function. This is [variable shadowing](https://stackoverflow.com/questions/5373278/what-is-the-correct-term-for-variable-shadowing-in-javascript) – evolutionxbox Jul 26 '21 at 14:11
  • *"why arr1 is not changed outside of the function"* Because \JavaScript doesn't use pass-by-reference, it uses pass-by-value, so you would never get the behavior you expect. – Felix Kling Jul 26 '21 at 14:18
  • @evolutionxbox: That's not relevant in this case. OP expects that assigning to a parameter changes the outer variable. The name of the parameter doesn't matter. – Felix Kling Jul 26 '21 at 14:22
  • @FelixKling sure. I still think it's worth noting. Even if in this case it's not the primary issue. – evolutionxbox Jul 26 '21 at 14:24
  • Thanks for your answer, it's all clear to me now! – Lorenz Mueller Jul 27 '21 at 09:36

0 Answers0