The following program executes in an unexpected way. Why is this exactly? I have some vague understanding based on the fact that the closure returns the reference to i and not the value of i. And since the value of i at the end is 3, then it will apply those values all across.
function idCreator (peopleList) {
var i;
var uniqueID = 100;
for (i = 0; i < peopleList.length; i++) {
peopleList[i]["id"] = function () {
return uniqueID + i;
}
}
return peopleList;
}
var myFriends = [{name:"ABC", id:0}, {name:"PQR", id:0}, {name:"XYZ", id:0}];
var createIdForMyFriends = idCreator (myFriends);
var abcID = myFriends [0];
console.log(abcID.id()); // 103