Pass variables between functions in Javascript?

I have functions that perform distance calculation with Google Maps.

They work smoothly, returning me the requested values.

This function returns a first value

  function calcDistance(response) {

    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;


    for (var i = 0; i < origins.length; i++) {
     var results = response.rows[i].elements;

     for (var j = 0; j < results.length; j++) {
   
    distanzafissa = results[j].distance.value;
    distanzafissa = distanzafissa / 1000;
    
    distanzafissarr = Math.round(distanzafissa*100)/100;
    }
   }
  }

I would like the value of distanzafissarr to pass to another function so coded:

    function computeTotalDistance(result) {
      var total = 0;
      var myroute = result.routes[0];
      for (i = 0; i < myroute.legs.length; i++) {
        total += myroute.legs[i].distance.value;
      }
      total = total / 1000;
      
      
    var totalarr = Math.round(total*100)/100;
   }

I have tried to follow various answers on this site, but always getting errors.

19 thoughts on “Pass variables between functions in Javascript?”

Leave a Comment