So I am looking at some code on this question, and I have no idea how this double assignment in one line actually works:
var deepAssign = function( base, names, value ) {
// If a value is given, remove the last name and keep it for later:
var lastName = arguments.length === 3 ? names.pop() : false;
// Walk the hierarchy, creating new objects where needed.
// If the lastName was removed, then the last object is not set yet:
for( var i = 0; i < names.length; i++ ) {
base = base[ names[i] ] = base[ names[i] ] || {}; /* this line wtf? */
}
// If a value was given, set it to the last name:
if( lastName ) base = base[ lastName ] = value;
// Return the last object in the hierarchy:
return base;
};
var x = {}
deepAssign(x, ['a', 'b', 'c'])
console.log(x) /* wtf, how? => { a: { b: { c: {} } } } */
I would assume that the original 'base' object would be destroyed in the for loop and that 'base' would then just be the inner object only, but somehow the original passed in object is preserved. Can someone give a detailed explanation of what is going on inside that for loop? It really bothers me to have something that I don't understand inside my code.