Combing two objects with multiple nodes - why does this code work?
<p>I have an object that is being used for storage of multiple values/objects and I want to be able to add on values/nodes only if the current node doesn't exist in the storage object (I don't want "i" values to ever overwrite data set in "data.pageData" - value1, value2, and value3 in the example). I don't know how deep the nodes I want to add on will be so the code has to handle an unlimited number of object levels. This is what I wrote, and it works like I need it to but I'm not sure why.</p>

<p>I don't understand why the final return to data.pageData is getting the two-level or three-level deep objects returned. I thought encapsulation would prevent the values from being returned.</p>

<pre><code>var data = {
    pageData: {
        value1: true,
        value2: 'not an empty string',
        other: {
            value3: false
        }
    }
};

var i = {
    value1: false,
    value2: '',
    other: {
        value3: true,
        value4: {
            value5: true
        },
        value6: 100
    }
};

init('pageData', i);
console.log(JSON.stringify(data));

function init(name, input) {
    if (typeof input !== 'object') {
        console.error('expected input as an object.');
        return;
    }

    var transverseObj = function(i, d) {
        for (var prop in i) {
            if (i.hasOwnProperty(prop)) {
                if (typeof i[prop] === 'object' &amp;&amp; typeof d[prop] !== 'undefined') transverseObj.call(transverseObj(i[prop], d[prop]));
                if (typeof d[prop] === 'undefined') d[prop] = i[prop];
            }
        }
        return d;
    };

    //// Check if the storage object is undefined, otherwise run through the object(s)
    data[name] = typeof data[name] === 'undefined' ? input : transverseObj(i, data[name]);
}
</code></pre>