1

I am encountering an issue with javascript scope.

function myFunc(){

    var tmpTab = []; // I have an issue with this variable

    for (var i=0; i > 72; i++){

        fs.readFile(filename, 'utf8', function(err, data) {
            // Here I'm doing some basic manipulations with my tmpTab

            console.log(tmpTab); // -> it works
        });
        console.log(tmpTab); // -> it works
    }
    return tmpTab;
    console.log(tmpTab); // -> it does not work. It doesn't return the content of my tmpTab
}

I tried different ways (with var, without, with this) but none worked. So how am I supposed to correctly get the content of my tmpTab that was modified inside the readFile function ?

Nicolás
  • 11
  • 3
  • Could you define "does not work"? And include what you're doing to `tmpTab`? – Igor Dec 04 '15 at 14:44
  • 1
    A `return` statement halts execution of a function when it is met. So simply put the function exits or `returns` before it gets to your last `console.log`, assuming that is what you mean by 'get' `tmpTab` unless you mean its not returning it then thats a different story. – ste2425 Dec 04 '15 at 14:44
  • The `fs.readFile()` function is **asynchronous**. You're trying to return a value that is fetched asynchronously, and that makes no sense. There are hundreds and hundreds of questions on that topic here. – Pointy Dec 04 '15 at 14:50

3 Answers3

2
return tmpTab;
console.log(tmpTab); 

you can't call code after returning from function. reverse the statements

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
2

Try readFileSync, which is synchronous. Otherwise tmpTab in the last console will be [].

If you use readFile, the content is only available in the callback. readFileSync will "feel" slower, but the content is synchronously available throughout the block.

var tmpTab = fs.readFileSync(filename, 'utf8')
console.log(tmpTab);

Edit : And of course, like the previous answers have rightly included, any statement which occurs after the return statement will not execute, so that is the other change you should make. Swapping the two statements will do.

Bhargav Ponnapalli
  • 9,224
  • 7
  • 36
  • 45
  • Very good point. I, like the others assumed he meant because return was called before the last log. `readFile` is async meaning its callback is called after the calling function exits. So our solutions of swapping the return and log may still not work. – ste2425 Dec 04 '15 at 14:46
1

Code after return statements will not run. (Some modern browsers warn you about this in the console.) Put it before the return:

console.log(tmpTab); 
return tmpTab;
Mitya
  • 33,629
  • 9
  • 60
  • 107