0

I am learning javascript and I read that in javascript array and objects are by default passed as a reference. So when I do this:-

var a = [2, 3, 4]

function pushEl(a, num) {
  a.push(num)
}

pushEl(a, 5)

console.log(a)

The output is as expected which is

[2,3,4,5]

But what I am not able to understand is that when I assign value to an array or an object inside the function the original array/object is not changed.

var a = [2, 1, 3]

function change(a) {
  a = [1, 2]
}

change(a)

console.log(a)

I expect the output to be [1,2] but the output is [2,1,3].

If the array is passed by reference then the changes should have been reflected in the original array too.

Can anybody tell me what concept I'm missing here?

Andy
  • 61,948
  • 13
  • 68
  • 95
Tan_R
  • 27
  • 8
  • Take a look at the [scope of variables](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) it might help you understand this behaviour – Reyno Nov 22 '21 at 07:59
  • 1
    Globally defined array `a` and the function parameter `a` are two _different_ variables. When you call the `change` function, passing in the `a` array as a parameter, function parameter `a` holds a reference to the same globally defined array BUT when you re-assign the function parameter `a`, it now holds a reference to a different array (globally defined `a` variable is unaffected). – Yousaf Nov 22 '21 at 08:02
  • I think you have a misunderstanding with the argument name... check it with this name: `function change(arg) { arg = [1, 2] }` actually you are editing the argument and not that `var a` – Mohammad Esmaeilzadeh Nov 22 '21 at 08:02

0 Answers0