here you can see there is a anonymous function inside of loop which executes only once at the end. if i use function declaration it calls 3 times(which is the length of array).
function celebrityIDCreator(theCelebrities) {
var i;
var uniqueID = 100;
for (i = 0; i < theCelebrities.length; i++) {
console.log(i) //which return 1,2,3
theCelebrities[i]["id"] = function () {
console.log(i) //which returns 3
return uniqueID + i;
}
}
return theCelebrities;
}
var actionCelebs = [{
name: "Stallone",
id: 0
}, {
name: "Cruise",
id: 0
}, {
name: "Willis",
id: 0
}];
var createIdForActionCelebs = celebrityIDCreator(actionCelebs);
var stalloneID = createIdForActionCelebs [0];
console.log(stalloneID.id()); // 103