Jimmy Jimmy - 1 month ago 6
HTML Question

I need properly increment a function in JavaScript loop

Please bear with me. I'm working on the following loop and I'm trying to figure out why foo.count is never incremented and displays 0. I would like to rewrite the example so that foo.count is properly incremented. I know I'm overlooking something. Any suggestions?
Thanks

function foo(num) {
console.log("foo: " + num);
this.count++;
}
foo.count = 0;

var i;
for (i = 0; i < 10; i++) {
if (i > 5) {
foo(i);
}
}
// foo: 6
// foo: 7
// foo: 8
// foo: 9
console.log(foo.count); // Still 0!

Answer

As mentioned by Jaromanda, you're utilizing this incorrectly. In this scenario, you need to be careful where you use it. Try replacing this.count++ with foo.count++

function foo(num) {
  console.log("foo: " + num);
  foo.count++;
}
foo.count = 0;

var i;
for (i = 0; i < 10; i++) {
  if (i > 5) {
    foo(i);
  }
}
// foo: 6 
// foo: 7 
// foo: 8 
// foo: 9 
console.log(foo.count); // Still 0!

Note that using this references the object it is contained within, not the function in is contained within, as it appears you mistakenly have taken it for.