0

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
SameerShaik
  • 488
  • 2
  • 10
  • 22
  • The functions shouldn't be executed at all since you are not doing anything with `createIdForActionCelebs`. – Felix Kling Jul 07 '15 at 15:33
  • yeah i'm not doing anything but im trying to changes the value of `id` in arrays by `celebrityIDCreator` function. `createIdForActionCelebs` results array so i guess no need to this function. – SameerShaik Jul 07 '15 at 15:38

0 Answers0