Q:

Read a text file to a variable in JavaScript

I have a file that I want to read into a variable in JS to use it later
var states;
$.get('states.json', function(data) {
        states=data;
        alert(data);
        alert(states);
    }, "text");

 alert(states);

In the above code, value of states is that of the file inside the function, but it is null outside.

A:

That's because the alert at the end runs before the file is received. Ajax is asynchronous by default.

