I'm having difficulty understanding variable shadowing in JavaScript based on scopes. Consider this small code fragment:
var k = {
prop1: 'test',
prop2: 'anotherTest'
}
for(var k = 0; k < 10; k++) {
console.log(k);
}
//prints number
console.log(typeof k);
//prints 10
console.log(k);
//undefined
console.log(k.prop1);
This is fine, because owing to the immediate function scope, the loop counter variable k shadows the json variable k we declated earlier. Hence the json variable k becomes inaccessible so to speak.
Question:
- In terms of memory allocation, now that there is no way to access
the original json var k, is it eligible for garbage collection? Will
the allocated memory be freed? Or the 'reference-orphaned' variable
still live on? If yes, why and for how long?
- Is there a way of accessing the original json var k WITHOUT writing any code before the for loop?
Now consider another slightly modified code fragment:
var k = {
prop1: 'test',
prop2: 'anotherTest'
}
var m = {
prop1: k
}
for(var k = 0; k < 11; k++) {
console.log(k);
}
//prints number
console.log(typeof k);
//prints 10
console.log(k);
//undefined
console.log(k.prop1);
//reference altered? No, this reference points to the original json k
//firebug dumps object to console
console.log(m.prop1);
Question:
- This time, we hold a reference to the original k before hand, in another json object. And surely, the memory will not be de-allocated. But, wouldn't evaluating m.prop1 resolve to an updated integer k, with a value of 10? Why isn't this resolution leading to the loop counter with value 10?