3 ms·
no - I believe the parent comment is right it's passed by the value of a reference as seen here from the console var changeref = function(ref) { ref = {}} var
by bryanrasmussen 7y ago
no - I believe the parent comment is right it's passed by the value of a reference as seen here from the console
var changeref = function(ref) { ref = {}}
var changeable = {prop: "something"}
changeref(changeable);
changeable;
Object { prop: "something" }
var changeprop = function(ref) {ref.prop = "anything"}
changeprop(changeable);
changeable;
Object { prop: "anything" }
the use of changeref does not turn ref into an empty object, because you passed the value of the reference, but the use of changeprop did change the property of the object because you are changing the prop on the reference.
at least this is my understanding of how it works. Interestingly enough I totally blew a simple programming test on the phone recently because I forgot about this (well my whole mind went blank and I couldn't do anything so even if I had remembered this it wouldn't have been enough - it was lucky I remembered my name)
on edit: console used, Firefox developer.
- filleduchaos 7y agoYes, precisely. In a language that supported call by reference, your `changeref` function would actually cause `changeable` to point to an empty object/map (assuming, of course, it had been passed by reference).
- gbuk2013 7y agoThis is what I am talking about: > function mutate (o) { o.foo = 'bar'; } > const o = { foo: 'foo' }; > o { foo: 'foo' } > mutate(o); > o { foo: 'bar' } I am probably not using terminology correctly, but it is not important as far as Javascript is concerned, since the language does not allow for anything else. What is important is that you can mutate objects you pass into functions and this is useful and dangerous at the same time.
- bryanrasmussen 7y agoyes, essentially that is the same as my changeprop function so I do understand that - however what the parent comment was arguing about was the actual terminology and wondering why no one ever uses it correctly. As I noted in another comment I don't think people use the terminology correctly because explaining to people the difference makes explaining an already complicated thing more complicated, and also it makes communication less elegant if more precise. I certainly never say Objects are passed by value of a reference, I just say they are passed by reference and if someone wants to take the time to correct me I would probably say "yes, sorry I was imprecise"
- gbuk2013 7y agoOK, after a bit more reading I now understand the difference, thank you for your patience. But it remains true that in Javascript you can not pass an object by value, because the language does not permit creating copies of objects. You can only ever pass a reference to an object (which is indeed only ever done by value) so the usefulness of arguing about the distinction is questionable at best.