0

There's a JavaScript function, lets call it "primary", it contains another function inside, name it "secondary".

The logic is that primary gets an object, passes the object to secondary then secondary adds another key/value into given object, finally primary returns the object.

function primary(objA) {
    function secondary(obj, key, value) {
        obj[key] = value;
    }
    let key = 'newkey';
    let value = 'newvalue';
    secondary(objA, key, value);
    return objA;
}

Surprisingly, objA is changed.

{
    key: "value",
    newkey: "newvalue"
}

My question is, how is the secondary function changing obj without returning the modified object!?

Is it because secondary is in the scope of primary? I need a complete explanation please.

Sagar V
  • 12,158
  • 7
  • 41
  • 68
Brian Salehi
  • 414
  • 2
  • 10
  • 19
  • 2
    Isn't it because the object is passed by reference? So the "JSON" is changed when `secondary` is called. – evolutionxbox Jul 21 '17 at 10:10
  • 4
    *"Surprisingly, obj is changed."* Why would it surprise you that if you pass in object A and then change it, that after that object A is changed? – Tomalak Jul 21 '17 at 10:11
  • Mutating an object will be visible to any part of the code that uses that object. The objects are not copied when you pass them along. – trincot Jul 21 '17 at 10:12
  • @Tomalak well, I'm not that much into JavaScript, I'm a C guy :D so basically it's like passing a pointer and waiting for object to be changed!? that was easier than I expected – Brian Salehi Jul 21 '17 at 10:13
  • 3
    Additionally, there is no JSON in this question. I've removed all references to it. JSON always is a string and you are not dealing with strings here. – Tomalak Jul 21 '17 at 10:13
  • @BrianSP try debugging your function in browser. You'll better understand why it is being changed – Karthik Chintala Jul 21 '17 at 10:14
  • 1
    @BrianSP Yes, all parameter passing in JS happens by reference, except for primitive types (number, string, boolean), those are passed by value. – Tomalak Jul 21 '17 at 10:16
  • @Tomalak thanks, that helped a lot, sorry for duplication. – Brian Salehi Jul 21 '17 at 10:17
  • 1
    Watch out, dates are not primitive types in JS, this can bite you if you are not careful. – Tomalak Jul 21 '17 at 10:19
  • @Tomalak noted. – Brian Salehi Jul 21 '17 at 10:22

0 Answers0