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

Variable issue.. with a switch statement

Hi guys.. i'm making a schoolproject and i'am stuck with something. i made a d3 visualization and when certain year is chosen the background needs to change. To achieve this i made this piece of code:

$("#year_options").change(function(){
    selectedYear = "";
    currentValue = "";
    lastValue = "";
    selectedYear = $("#year_options").val();
    currentValue = selectedYear;

    switch(currentValue){ 
        case '2006' :
          if(filterCity == true){
            draw2006();
            lastValue = currentValue;
            console.log(lastValue);
          }else{
            drawCity2006();
          }
          break;

        case '2007' :
          if(filterCity == true){
            console.log(lastValue);
                $('#map').css('background-image','url(img/' + lastValue + '_oud.svg)');
            draw2007(); 
          }else{
            drawCity2007();
          }      

The problem is that the variable: lastValue works fine in case 2006.. but when i select option 2007 after i've chosen option 2006 it returns empty.

What i'm trying to achieve is storing the last chosen year and when a new year is clicked it changes te background of the previous year..

What am i doing wrong? I declared the variables as global variables i think?

1 Answer

lastValue isn't set for case 2007 i believe, im guessing you declared your last value outside like this

var lastValue = "";

then inside the change function you set it to nothing again

lastValue = "";

so for case 2006 you set lastValue to be currentValue which is why you got something returned, then you break, which kicks you out the switch, and when the change is called again lastValue is cleared to

lastValue = "";

but for case 2007 you never set lastValue. so basicaly lastValue was only set for the scope of 2006

check out this article on hoisting http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

i hope this helped, comment back if that was the issue =]