1

I'm having a difficult time understanding how return and scopes work.

I have this code and what I need is be able to use the "obj" variable and its content in the global scope, or a separate function from the one where it is declared.

input.addEventListener('change', function(e){
    const reader = new FileReader()
    reader.onload = function(){
        var obj = JSON.parse(reader.result);
    }
    reader.readAsText(input.files[0]);
}), false;

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Andra
  • 61
  • 1
  • 9
  • Declare your obj variable outside of the listener and then just assign a result to this variable. – demkovych Feb 26 '20 at 09:34
  • 2
    This has nothing to do with scope, but with ***timing***. `var obj = JSON.parse(reader.result)` is executed when the file reader is done loading, after it has been triggered by the input's `change` event. That is ***sometime later***, after you have run this `input.addEventListener` code. The value simply will not be available right after you have executed `addEventListener`. Put the code that needs `obj` into the `onload` callback function, which will be executed *if and when* the loading has succeeded and the data is available. – deceze Feb 26 '20 at 09:37
  • Actually deceze is correct. Follow his advice. – natsuozawa Feb 26 '20 at 09:45
  • This actually makes sense and I understand what you're saying, but.. My "obj" contains a bunch of paths (strings) to some local images. I want to create an array with these and then assign them whenever I need to load a new picture, if this makes sense. I'd rather not have to write my entire code inside the onload function. Isn't there any other way to do this? Thanks! – Andra Feb 26 '20 at 09:46
  • 2
    You could create a separate function and call within the onload function. – natsuozawa Feb 26 '20 at 09:48
  • 1
    I will try this, thank you – Andra Feb 26 '20 at 09:51
  • 1
    My apologies about the previous answer. You can generally write to a global variable inside an event listener. However I have not tested this against FileReader. – natsuozawa Feb 26 '20 at 09:54
  • @natsuozawa Most uses of callback functions are because the result will be available *sometime later*. Sure, you can write that result into a global variable. But other code won't know *when* that data will be available in that global variable, so doing that is mostly pointless. Here you even have *two* such "sometime later" callbacks. So, generally, writing to a global variable from a callback is mostly not useful. – deceze Feb 26 '20 at 10:00
  • I agree. I initially read this question as asking about updating a global state inside an event listener, not processing the response of an asynchronous request. – natsuozawa Feb 26 '20 at 10:02

0 Answers0