0

I am using javascript to get the exchange rates of currencies. I have the following function set up to do so:

var latest;

function convert(from, to){
    var requestURL = 'https://api.exchangerate.host/convert?from='+ from.toUpperCase()+'&to='+to.toUpperCase();
    var request = new XMLHttpRequest();
    request.open('GET', requestURL);
    request.responseType = 'json';
    request.send();
        request.onload = function() {
        var response = request.response;
        console.log(response);
        response = JSON.parse(JSON.stringify(response));
        latest = response.result;
        console.log(latest);
        }
    console.log(latest);
}

The variable latest is assigned the conversion rate. However,I cannot then access it outside of the function to do anything with it, as it is "null" or undeclared outside the subfunction. I have declared latest outside of the function, as has been recommended on other similar topics I've found on here. I would appreciate any help!

Jan K
  • 1
  • You can store the results in an object like this `var latest = {};` `latest[from.toUpperCase()][to.toUpperCase()] = response.result; `, then you can always access the results without re-requesting them. I believe thats what you were attempting to do. – Hilton Siegert Oct 20 '22 at 06:53

0 Answers0