0

While some people are saying that this question has been answered before, its only the answer that has been given before to a different question with much more specifics (ie. asking specifically about call-by-reference / call-by-value, whereas this question does not presuppose knowledge of eiither)

The following code appears to be very confusing. We can logically deduce that the reason why z.id updates after the function is because it is an object. But why? What particular trait or characteristic of javascript is doing this?

function changea(a) {
  a = 100; // does not change a
}  // no return

function changez(z) {
  z.id = 100;  // does change z
} // no return

var a = 0;  // a is zero

changea(a)  // a variable

alert('variable a is equal to ' + a); // why does this stay at zero?

var z = {id: 0};
changez(z);
alert('variable z.id is equal to ' + z.id); // why does this change to 100

see the demo here: http://jsfiddle.net/u0pysgjy/7/

docodemore
  • 1,074
  • 9
  • 19
  • 1
    See this question: http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language – LJᛃ Nov 07 '14 at 03:14

1 Answers1

0

In the first case a is passed by value to the changea function and in the second case z is an object and it is passed by reference to the changez function.Whenever a function gets a variable which is passed to it by value, even if you change the value it will not reflect outside of the function which is the case of a. And if a function gets its parameter which is passed to it by reference if you change the value of its property it will be reflected outside of the function also.

There is a nice explanation here

Community
  • 1
  • 1
R A Khan
  • 187
  • 4
  • 12
  • You basically restated my question: objects are changed, variables are not. this was not the answer I was looking for. I wanted to know the computer science behind it, and LJ_1102 answered it properly, and I learned new terms, pass-by-reference, pass-by-value. The real answer is in the explanation you linked to, and I posted that link to my answer as well before you did. Not sure why yours gets upvoted and mine gets downvoted. – docodemore Nov 07 '14 at 15:40
  • I did not restate your question.Actually I tried to answer your question in your flow so that you can understand.I mentioned in my answer the terms pass by value and pass by reference.For further explanation of these terms I shared a so question link so that you can understand more.Your question got downvote because it is a kind of duplicate question and the answer to your question is already in so. – R A Khan Nov 08 '14 at 06:03