0

I have a global variable say :

var series,hours;
var loadData = function(){
series = [[]];
hours = [];
d3.json("data/radar.json", function(error, data) {

    data.QualitySummaryObject.forEach(function(d,i) {
        series[i] = d.extractPercentage;
        hours[i] = d.extractorName;
  });


});  
console.log(hours);
};

Now if I am trying to access this console.log its working fine, but.

var print = function(){
    console.log(hours); //here its not working no value in hours why ... ?
}
2
  • 2
    where are you calling print? Commented Jan 28, 2013 at 12:07
  • 1
    use hours = [] instead of var hours. remove var from declaration and hours will become global Commented Jan 28, 2013 at 12:08

2 Answers 2

2

Ensure that you hours is global:

window.hours = [];

Then anywhere you can log it:

console.log(window.hours);

Using directly var without declaration will avoid context problems.

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

Comments

0

If you are running the above code in a function, the variable hours is not a global variable because you previously declared it with var.

If you want to declare a variable as a global variable, instead of this:

var hours = [];

Do this:

hours = [];

To declare a global variable, all you have to do is give it a name.

5 Comments

no i am not running in any function... var hours is declared outside of every function....
@SaurabhSinha either way, you should not need to declare a global variable with var outside of all the functions.
@starbeamrainbowlabs: Why not? Even global variables can (and should) be declared.
@Bergi Didn't know that! I thought that global variables in javascript were declared without var.
@starbeamrainbowlabs: It's just that everything without a var and no declaration is considered to be global.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.