0

Imagine two situations below: We have an array which is a global variable and it will be updated after a function. On the other hand as you can see in commented code my other global variable doesn't updated after a function?

I learnt about pass by reference and value, but i am wondering how come array has been passes by reference to the function but "a" variable has been passes as value?

var a=[1,2,3,4,5];

function adder(arrey, item) {
    arrey.push(item);
    return arrey.shift();
}


console.log(a);
console.log(adder(a,6));
console.log(a);

var a =10

function adder (num) {
    num+=1;
    return num;
}

console.log(a);
adder(a);
console.log(a)
amin aoka
  • 1
  • 2
  • 3
    `num` is not `a` – Cid Jul 22 '21 at 11:17
  • 1
    1. You cannot update primitives. JS is not pass-by-reference. 2. You probably shouldn't rely on global variables anyway. – VLAZ Jul 22 '21 at 11:18
  • 1
    `adder(a);` --> `a = adder(a);` – Yousaf Jul 22 '21 at 11:19
  • @Yousaf many thanks. I learnt about pass by reference and value, but i am wondering how come array has been passes by reference to the function but "a" variable has been passes as value? – amin aoka Jul 22 '21 at 12:01
  • 1
    Everything in Javascript is _pass by value_. In the case of an array (or objects in general), value is a _reference_ to that object. So, if you pass an array to a function, you are passing a reference to that array. Any changes made to that array using its reference will modify the same array because in memory, there is only one array. – Yousaf Jul 22 '21 at 12:24

0 Answers0