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

Loop not counting up.

So I am working on a dice counter, and my function is not counting up, it can return 1 and the number of sides on each die correctly but not count up on click like I want it too. Do I need a different type of loop, or a different starting variable?

function counterDice(side) {
    this.side = side;
    start = 1;
}

var d4counter = new counterDice(4);



counterDice.prototype.countUp = function() {
        for(i=start; i< this.side +1; i++){
            console.log(this.side);
            console.log(i);
            return i;
        }
    };




//count up (left click)
$("#d4c, #d4count").click(function() {
    document.getElementById('d4count').innerHTML = d4counter.countUp();
});

example just using the d4.

4 Answers

You have a "return" inside your loop. Return stops the loop.

Thanks I forgot about that.

Sorry, when you posted the first time I saw the return and pretty much stopped looking at your code for the most part.

I am not sure exactly what you are trying to display in your HTML, but here is what I see with the code.

Your loop is based on "start" assigned as 1 and the sides in this case as 4. Nothing in your loop changes those values, so each time you click the mouse, you are starting the loop over at 1 and 4. You are not changing anything to 2, 3, etc.

If you remove the return statement, each time you click the console should be 4,1,4,2,4,3,4,4. If you leave the return in it is 4,1,1.

If you want it to countUp, you effectively need to add to the start variable each time you click. So somehow in the function you need to ++start and then display start in your HTML tag.

Does that make sense?

So your loop is working, but you are resetting to the beginning each time you click.

yes that makes sense- thanks!

Your welcome.

still not functioning correctly, not sure what is happening.