-2

I found a good piece of code on SO that I only partially understand. If you could help me understand what is happening with myObj in the second loop of this recursive function when the function no longer points to myObj (instead it points to tmpObj yet it still adds onto it.

  var myObj = {};

function addProps(obj, arr, val) { // in the first run obj = myObj

    if (typeof arr == 'string')
        arr = arr.split(".");

    obj[arr[0]] = obj[arr[0]] || {};

    var tmpObj = obj[arr[0]];

    if (arr.length > 1) {
        arr.shift();
        addProps(tmpObj, arr, val); // whilst recursing, tmpObj becomes obj (as function parameter), so why myObj keeps being changed as well?
    }
    else
        obj[arr[0]] = val;

    return obj;

};

addProps(myObj, 'sub1.sub2.propA', 1);

Link to the original piece of code : https://stackoverflow.com/a/34205057

J. Doe
  • 37
  • 5
  • 2
    [What does your step debugger tell you?](http://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems). Your question can be answered very quickly and easily with your step-debugger. You should always try and solve your problems with a step debugger before coming to StackOverflow. –  Jun 10 '18 at 09:28
  • 1
    Possible duplicate of [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) –  Jun 10 '18 at 09:28
  • I have use the debugger, and it increases the myObj. I just want to know why as the new tmpObj is not pointing to myObj – J. Doe Jun 10 '18 at 09:55

1 Answers1

0

when you have a nested object and mutate the inner one, there is no copying involved... the outer one still points to the same (now mutated) inner object, e.g.:

const myObj = {a: {b: 'c'}}
const tmpObj = myObj.a
tmpObj.b = 'd'
console.log('original mutated after changing the inner object:', myObj)

const copyObj = Object.assign({}, myObj.a) // or {...myObj.a}
copyObj.b = 'e'
console.log('original NOT mutated after changing a copy:', myObj)
Aprillion
  • 21,510
  • 5
  • 55
  • 89