0

I want to make a variable "city" global and use it in other function. I am requesting a JSON data and it seems to work in this function

var city;

function conditions(data) {
        var city = data.current_observation.display_location.full;
        var wcode = data.current_observation.icon;

        $('#city').append('<h2>' +'Weather forecast in ' + city + '</h2>');
        $('#city').addClass('headings-style');

    }

But whe I try to use variable city in other function I'm getting an undefined data:

function forecastDays(info) {
        var locationOne = info.forecast.simpleforecast.forecastday;
        locationOne.forEach(function (daysPlus) {

        var high = daysPlus.high.celsius;
        var low = daysPlus.low.celsius;
        var arr = ["day1", "day2", "day3", "day4"];
        jQuery.each(arr, function (i, val) {

            $("#temp_" + val).html('<p>' + city + 'High: ' + high + '&deg;C' + '<br>' + ' Low: ' + low + '&deg;C' + '</p>');

            });
        });

Please, help.

2
  • 2
    You re-declare city inside conditions. Do city = ... instead of var city = .... Commented Jul 20, 2017 at 19:54
  • A good question! It is a mistake that is often made and therefore it is good that attention is paid to this. Commented Jul 20, 2017 at 20:02

3 Answers 3

4

Instead of doing

var city = data.current_observation.display_location.full;

you should do

city = data.current_observation.display_location.full;

in order to set the value of the global city variable. Re-using var keyword will declare a new variable city in function scope, rather than global.

Sign up to request clarification or add additional context in comments.

Comments

1

Little, late, but here's an example. (@J. Chen provided the answer)

When you use var city = you're redefining the variable within the function scope, so it' no longer accessible from the global scope.

In the example below, the city variable is being used correctly in the global scope, where the town variable is being redefined in the function scope:

var city;
var town;

function foo() {
  city = "New York";
  var town = "Boston";
};

function bar() {
  console.log(city);
  console.log(town);
}

foo(); // assigns the variable a value
bar(); // console "New York" / undefined
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments

-1

delete var city in funtion conditions

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.