Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

brandonlind2
brandonlind2
7,823 Points

why isnt this counter method working?

let obj={
            num:0,
            count: function(max){
                for(let i=0; i<max; i++){
                    let num=this.num;
                    num++
                    console.log(num);
                }
            }
        }

obj.count(100);
Ashraf Suleiman
Ashraf Suleiman
Courses Plus Student 5,008 Points

is this what are you looking for ?

let obj = {
        num: 0,
        count: function(max) {
            for (let i = 0; i < max; i++) {
                (function() {
                    var a = i;
                    let num = this.num;
                    num++;
                    console.log(a);
                }())
            }
        }
    }

    obj.count(100);
'''

1 Answer

Sean T. Unwin
Sean T. Unwin
28,690 Points

Move let num=this.num; to before the for loop; after the function declaration.

Using let inside the for loop resets to 0 every time since num: 0, which is, of course, this.num and inside the loop only num (the variable inside the loop) is getting incremented.

Another thing to keep in mind is let will not allow you to re-declare the same variable in the same scope. So if you were to use this script inside Firefox's Scratchpad and run (clicking the Run button) it more than once an error will occur because obj was already declared with let. In that case, it would be better to use var instead of let as the code stands now, unless it were enclosed within a function or IIFE. However, that's not really a realistic situation so if it's just a one off declaration, like pasting this into a browser console or NodeJS CLI and calling obj.count() numerous times, it's fine to use let.

The code I expressed above would be:

let obj = {
  num:0,
  count: function(cmax) {
    let num = this.num;
    for(let i = 0; i < max; i++) {
        num++;
        console.log(num);
    }
  }
};
obj.count(100);