0

What doesn't the 2nd console.log below return 2? Is it because inside the function scope when I assign thing = thing + 1, the assignment of thing is just another variable? It's no longer referring to the original thing argument that was passed in?

function change(thing) {
  thing = thing + 1;
  return thing;
}

let a = 1

console.log(change(a)) //2
console.log(a)         //1
stackjlei
  • 9,485
  • 18
  • 65
  • 113

2 Answers2

1

That's because in javascript when you pass primitive types to a function like "string" or "number" only a copy is passed, if it were an object or an array then the value would change because those types are passed by reference, for example:

function change(thing) {
  thing.value = thing.value + 1;
  return thing;
}

let a = {value: 1};

console.log(change(a)) 
console.log(a) 
chinloyal
  • 1,023
  • 14
  • 42
  • **1.** Even if an object or array is passed to to `change`, the variable `a` won't be changed, at least not in the way OP is trying to change it. **2.** There is no such thing as pass by reference in javascript. Objects are passed around by a reference to them instead of their value, but the variables aren't passed by reference. – ibrahim mahrir Aug 19 '18 at 22:22
0

Javascript always pass by value so changing the value of the variable never changes the underlying primitive (String or number).

Pass by Reference happens only for objects. In Pass by Reference, Function is called by directly passing the reference/address of the variable as the argument. Changing the argument inside the function affect the variable passed from outside the function. In Javascript objects and arrays follows pass by reference.

function callByReference(varObj) { 
  console.log("Inside Call by Reference Method"); 
  varObj.a = 100; 
  console.log(varObj); 
} 
let varObj = {a:1};
console.log("Before Call by Reference Method"); 
console.log(varObj);
callByReference(varObj) 
console.log("After Call by Reference Method"); 
console.log(varObj);

Output will be :

Before Call by Reference Method

{a: 1}

Inside Call by Reference Method

{a: 100}

After Call by Reference Method

{a: 100}

Sab
  • 16
  • 1