I am new to javascript (new to programming overall, really). And I encountered this behavior of for/in loop that I don't quite understand. The following pieces of code were run with $node command in console.
code_0:
var result = {};
var list = ['A', 'B', 'C'];
for(var index in list){
var id = list[index];
result[id] = {};
result[id]['name'] = id;
}
console.log(result);
result_0:
{ A: { name: 'A' }, B: { name: 'B' }, C: { name: 'C' } }
code_1:
var result = {};
var list = ['A', 'B', 'C'];
var INIT = {'a': 0, 'b': 0, 'c': 0,}
for(var index in list){
var id = list[index];
result[id] = INIT;
result[id]['name'] = id;
}
console.log(result);
result_1:
{ A: { a: 0, b: 0, c: 0, name: 'C' },
B: { a: 0, b: 0, c: 0, name: 'C' },
C: { a: 0, b: 0, c: 0, name: 'C' } }
I can understand why code_0 would give result_0. But result_1 is what I don't understand. I expected result_1 to be:
{ A: { a: 0, b: 0, c: 0, name: 'A' },
B: { a: 0, b: 0, c: 0, name: 'B' },
C: { a: 0, b: 0, c: 0, name: 'C' } }
What's the difference between code_0 and code_1? Why would code_1 give result_1?
EDIT: * Add tags related to the question. * Change title. (Title used to be about for/in loops)
A,BandC, so naturally they'll show the same data.