简体   繁体   中英

How does javascript function scope work with arguments?

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

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) 

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM