Search code examples
javascriptjsond3.jsglobal-variables

variable scope in d3 javascript


I want to get data in global variable by using the following code:

var data;
d3.json ( "file.json" , function(json) {
  data = json;
  console.log(data); //defined
});
console.log(data); //undefined

But the problem is that i just have data variable defined in d3.json function but out it is undefined. how can I solve this issue?

Thanks


Solution

  • Because d3 requests (like d3.json) are asynchronous, it's best practice to wrap all of the code dependent on your external request within the request callback, ensuring that this code has access to the data before executing. From the D3 docs: "When loading data asynchronously, code that depends on the loaded data should generally exist within the callback function."

    So one option is to put all of your code within the callback function. If you'd like to separate the code into parts, you can also pass the response from your request to a separate function, something like this:

    function myFunc(data) {
        console.log(data);
    }
    
    d3.json('file.json', function (data) {
        var json = data;
        myFunc(json);
    });