title: Updating global variable locally in Javascript
body: <p>I started to learn Backbone.js library by implementing a simple project. After seeing a few tutorials, I produced the code which is show below. I am aware that it might not look perfect since I am new to javascript development.</p>
  
  <p>So the below, I am fetching the list of nationalities from the API and then getting the number of students from those specific countries. This seems clear for the time being but the problem is, I need to get the total students per nationality which is why there is a counter in the second collection fetch function. The problem I am facing is about Javascript. Basically, defining "total" globally and updating it locally is what I need to do. I have come across to many threads similar to this one but to be honest didn't understand well enough to reproduce my own solution. Once again, my question is how I can re-engineer this code so that I can update the value of the variable "total" locally and then use the updated result outside of the inner fetch function. I appreciate your answers and advice. Thanks in advance.</p>
  
  <pre><code>    $.ajaxSetup({
      crossDomain : true,
      cache : false,
      contentType : "application/json",
      dataType : "json"
  });
  
  var baseURL = "http://lucalongo.eu:80/courses/2014-2015/questionnaireDIT/app/index.php";
  
  
  var mModel = Backbone.Model.extend({});
  
  var cNationality = Backbone.Collection.extend({
      model: mModel,
      url: this.baseURL + "/nationalities"
  });
  
  var cStudent = Backbone.Collection.extend({
      model : mModel,
      initialize : function(models, options) {
          this.url = "http://lucalongo.eu:80/courses/2014-2015/questionnaireDIT/app/index.php/students/nationality/" + options.id;
      }   
  });
  
  var vView = Backbone.View.extend({
  
      render: function(){
      var total = 0;
      this.collection = new cNationality();
      this.collection.fetch({
          success: function(c){
              _.each(c.models, function(col) {
                 var nationalDesc = col.toJSON().description;
                 var nationalID = col.toJSON().id;
                 var studentNationality = new cStudent([], {id : nationalID});
                  studentNationality.fetch({
                    success: function(c){
                        //console.log(nationalDesc + ": " + c.length);
                         total = total + c.length;
                        console.log(total);
                    }
                 }); 
              });
  
          }
        });
          console.log("Total:" total); // still displays 0
      }
  });
  
  
  var v = new vView();
  v.render();
  Backbone.history.start({pushState: true});
  </code></pre>