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
3
  • The function doesn't change the value of a. So a is still 1. Commented Aug 19, 2018 at 22:10
  • Basically than answer is yes... Commented Aug 19, 2018 at 22:10
  • stackoverflow.com/questions/518000/… Commented Aug 19, 2018 at 22:17

2 Answers 2

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) 

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.