+ 4
Ooh I like this question! I have learnt more about JS: your question is answered perfectly here https://stackoverflow.com/questions/37290747/pass-by-reference-javascript-objects (and I’d note a commenter says JS doesn’t pass by reference at all) What has happened is that within edit(obj), the method starts by passing the value of the object reference (so not the object itself, just a reference) and this reference is ‘obj’ obj.d = 3; —> great! obj is still a reference to an object passed as a parameter so I can still update property d here to 3 obj = {}; —> never mind, forget that reference before as I now want to make obj refer to a new object obj.d = 4; —> and this new object will have property d as 4. I’m no longer referencing the initial parameter object so console.log of property d here within this method will show me 4 Any passed parameter/object to edit(obj) will be edited the same way as obj does within the method before obj gets assigned to {} as it no longer will be caring about a passed reference Hope that helps
22nd Mar 2019, 5:32 PM
Jenine