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

Access variable outside of function

/*How can I access the variables getWeather, getTemp, getWind and getPrecip outside of this function. Right now they come back undefined. Thanks!*/

var request = new XMLHttpRequest();
request.open('GET', 'http://(my personal API key goes here)', true);

var getWeather, getTemp, getWind, getPrecip;

request.onload = function () {
    if (request.status >= 200 && request.status < 400) {
        // Success!
        var data = JSON.parse(request.responseText);

        getWeather = (data.current_observation.weather);
        var weather = document.querySelector('.weather');
        weather.innerText = getWeather;
        getTemp = (data.current_observation.temp_f);
        var temperature = document.querySelector('.temperature');
        temperature.innerText = getTemp + '° F';
        getWind = (data.current_observation.wind_mph);
        var wind = document.querySelector('.wind');
        wind.innerText = getWind + ' MPH Wind';
        getPrecip = (data.current_observation.precip_today_in);
        var precipitation = document.querySelector('.precipitation');
        precipitation.innerText = Math.ceil(getPrecip) + ' Inches of Rain     ';
    } else {
        console.log('We reached our target server, but it returned an error');
    }
};

request.onerror = function () {
    console.log('There was a connection error of some sort');
};

request.send();

console.log(getWeather); //This comes back undefined

1 Answer

Hi Rachel!

The reason that they appear undefined is because they are only visible and usable in the scope of the function in which they are defined. This means that, because they are declared within that function, they cannot be used elsewhere in the program and be expected to retain a value or even exist.

A way to counter-act this would be to declare those variables outside of the function and then just have the function in question modify them. This way you can access them wherever you please.

Another alternative way would be to pass them as parameters into another function that needs to use them but this might not be the best solution depending; it really depends on the situation.

I hope that I managed to help you out, if you need any more help then don't hesitate to ask.

-Luke