0

What is the scope of an array in javascript?

How can I resolve this situation?

var parseXlsx = require('excel');
var arrayURLToSearch = [];
parseXlsx('foo.xlsx', function(err, data) {
  if(err) throw err;
    for(var i=1; i<2; i++){
        arrayURLToSearch[i] = data[i][0];
    }
});
console.log(arrayURLToSearch[0]); -> undefined

How can I print the arrayURLToSearch outside the function?

OiRc
  • 1,530
  • 4
  • 18
  • 51
  • What do you mean outside the function? what is your exact scenario that you want to acheive? If you have no specific scenario, just put console.log(arrayURLToSearch[0]); after the "for" loop – Sharjeel Ahmed Mar 20 '17 at 13:03

2 Answers2

1

You cannot. The callback happens at some point in the future that you cannot predict. Try this instead:

var arrayURLToSearch = [];
parseXlsx('foo.xlsx', function(err, data) {
  if(err) throw err;
    for(var i=1; i<2; i++){
        arrayURLToSearch[i] = data[i][0];
    }

console.log(arrayURLToSearch[0]);
});
Paul
  • 32,974
  • 9
  • 79
  • 112
0

Your method is asyncronous, so console.log(arrayURLToSearch[0]); line will be executed before parseXlsx method.

One solution is to use a callback function.

function execute(callback){
   var parseXlsx = require('excel');
   var arrayURLToSearch = [];
   parseXlsx('foo.xlsx', function(err, data) {
     if(err) throw err;
     for(var i=1; i<2; i++){
         arrayURLToSearch[i] = data[i][0];
     }
     callback(arrayURLToSearch);
   });
}
execute(function(arrayURLToSearch){
     console.log(arrayURLToSearch[0]);
});
Mihai Alexandru-Ionut
  • 41,021
  • 10
  • 77
  • 103