function generateUniqueCelebrityIDs(celebrities) {
var i;
var uniqueID = 100;
for (i = 0; i < celebrities.length; i++) {
celebrities[i]["id"] = function () {
return uniqueID + i;
};
};
return celebrities;
}
var actionCelebs = [
{ name: "Stallone", id: 0 },
{ name: "Cruise", id: 0 },
{ name: "Willis", id: 0 }
];
var updateActionCelebIDs = generateUniqueCelebrityIDs(actionCelebs);
var stalloneID = updateActionCelebIDs[0];
console.log(stalloneID.id()); // 103
In the above example, due to the timing of when the anonymous functions are executed, all celebrity IDs end up as 103 instead of being distinct values starting from 100. This issue arises from how the loop increments and affects the closure around the variable 'i'.
I've researched the concept of callback functions but still struggle to understand why we consistently get ID=103 in this scenario. Seeking clarity and insight on this topic. Thank you.