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

Review and question on small JS app

I have this small little app that I built but I was wondering if there was a way to make this code more condensed/easier

var i = -1;
$( "#next, #back, #remove"  ).click(function () {
    var filters = [ "aden", "reyes", "perpetua", "inkwell", 
    "toaster", "walden", "hudson", 
    "gingham", "mayfair", "lofi", 
    "xpro2", "1977", "brooklyn"]

    function changefilter(){
      $('figure').removeClass().addClass(filters[i]);
      $('h1').text(filters[i]);
      console.log(filters[i]);
    }

if (this.id == 'next' && i < filters.length) {
     i++;
     changefilter();
    } else if (this.id == 'back' && i > -1 && i !== undefined) {
        i--;
        changefilter();} else if (this.id == 'remove'){
        i = -1;
        changefilter();
    }
});

basically the app has 3 buttons which will cycle the class on the figure element.

I am still really new to javascript and I know this would have to do something with the scope but why is it that if I put the "i" variable at the very top (inside) of my function

var i = -1;
$( "#next, #back, #remove"  ).click(function () {
    var filters = [ "aden", "reyes", "perpetua", "inkwell", 
    "toaster", "walden", "hudson", 
    "gingham", "mayfair", "lofi", 
    "xpro2", "1977", "brooklyn"]

the counter does not move? Also, i put initiated "i" to be -1 because i didnt want to have a class applied until the button was hit. Is this a good way to do this?

Is there a way to have a variable that all functions within a function are able to see without making it global? Is there even a point to doing that? Am I even making sense anymore?

If you want to see this working i have a pen at http://codepen.io/Oreilly617/pen/KdrOom