Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 720
I3i0 Avatar asked Jun 25 '13 10:06

I3i0


People also ask

What is variable scope in JavaScript?

Variable Scope. Scope in JavaScript refers to the current context of code, which determines the accessibility of variables to JavaScript. The two types of scope are local and global: Global variables are those declared outside of a block. Local variables are those declared inside of a block.

What is variable scope example?

Variables have a global or local "scope". For example, variables declared within either the setup() or draw() functions may be only used in these functions. Global variables, variables declared outside of setup() and draw(), may be used anywhere within the program.

What is variable scope?

In simple terms, scope of a variable is its lifetime in the program. This means that the scope of a variable is the block of code in the entire program where the variable is declared, used, and can be modified. In the next section, you'll learn about local scope of variables.

What is the use of variable scope?

In programming also the scope of a variable is defined as the extent of the program code within which the variable can be accessed or declared or worked with.


1 Answers

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);
});
like image 148
nsonnad Avatar answered Oct 11 '22 06:10

nsonnad