The background image in the local weather app is not changing

When i write the following code:
document.body.style.backgroundImage =
“url(‘https://images.pexels.com/photos/412462/pexels-photo-412462.jpeg?w=940&h=650&auto=compress&cs=tinysrgb’)”;

the above code does run properly and it displays the background image.However when I place a condition like:
if(ftemp>=0){
document.body.style.backgroundImage =
“url(‘https://images.pexels.com/photos/412462/pexels-photo-412462.jpeg?w=940&h=650&auto=compress&cs=tinysrgb’)”;
}

the code fails to run.I am not able to understand the reason for it.
Here is my pen:

The AJAX request by nature is asynchronous, and therefore any code after this will run while it’s fetching the data. Since ftemp doesn’t receive a value until the request is complete, it will be undefined in that if statement.

So how to deal with this problem?Can you also explain the exact meaning of this statement “the ajax request is a synchronous in nature”.Thanks for the reply :slight_smile:

Sorry for the late reply, AJAX stands for “Asynchronous Javascript and XML”. The jQuery methods like .get, .getJSON, .ajax, are all asynchronous so when the javascript engine reaches this, it won’t stop and wait for these methods to finish executing, it will continue running the code after it.
Taking your code as an example, you have a get request that only fills the ftemp variable when all the data is fetched from the API. Keeping in mind that javascript doesn’t wait until it’s finished, it will look at the code after this and run it.

So this code: if (ftemp >= 0) {} will run before that get request is finished, meaning it still won’t have a value. Remember that undefined is falsy so the content of the if block won’t run.
What you can do is put the if statement inside of the request.

Thanks man.You helped a lot :smile: