-4

A JavaScript code:

var age = 27;
var obj = {
  name: 'Jona',
  city: 'Lisbon'
};

function change(a, b) {
  a = 30;
  b.city = 'San Francisco';
}
change(age, obj);
console.log('age:', age);
console.log('obj.city:', obj.city);

The result in console is 27, San Francisco respectively. I am confused with that why the value of age is 27 instead of 30. In my opinion, the value of variable age will be changed to 30 after calling function change. Can someone answer it?

Phil
  • 157,677
  • 23
  • 242
  • 245
Harrymissu
  • 450
  • 2
  • 8
  • 18
  • 3
    hint: put `b = {city: "San Francisco"}` instead of `b.city=` - see how obj doesn't change = what can you infer from that? – Jaromanda X Sep 13 '18 at 04:06
  • or try this `change({age}, obj);` and `a.age = 30` – Jaromanda X Sep 13 '18 at 04:08
  • Some great answers relating to this here ~ https://stackoverflow.com/questions/51583906/assignment-by-reference-confusion – Phil Sep 13 '18 at 04:10
  • Since `age` is in the global scope and you didn't do anything to change the value of `age` in this scope. In the `change` function, you actually pass `age` as a parameter, but instead of using this parameter, you declare a new variable `a` inside `change`, but it's nothing to do with the variable `age` outside of the function `change`. – Wayne Li Sep 13 '18 at 04:20

1 Answers1

0

it is about "pass by value" and "pass by reference"

On javascript, that will be "pass by value" when pass primitive to function and "pass by reference" if you pass a object/array to function. the changing of the object passed inside the function is change the object itself.

Atk
  • 149
  • 7
  • `changing of the object passed inside the function is change the object itself` so, if I change the object to `{}`, what happens? i.e. your explanation seems not quite there – Jaromanda X Sep 13 '18 at 04:13
  • if we replace the b.city = 'San Francisco' to b = {}, javascript would not change the original passed b, becoz that assigned a new object to it with new reference? – Atk Sep 13 '18 at 04:19