0

This happens to be from a Chrome extension, but I believe this is a pertinent general JS question. I have a working func like so to access local storage:

function loadItem(sName, callback){
    var get = {};
    get[sName] = {}; //blank obj by default.
    chrome.storage.local.get(get, function(data) {
        data[sName] && callback(data[sName]);
    });
};

When I invoke loadItem's callback in an asynchronously-called "outer" callback, I make use of loadItem's arg sName. Why is that defined in there? Shouldn't the asynchronous callback not recognise that var because loadItem has finished running and sName was not provided as one of the callback's own args?

tripRev
  • 830
  • 3
  • 12
  • 27

1 Answers1

1

This is what is called a closure. The callback you send to get captures the variables in the local scope of the original function (loadItem in this case) so that they can still be used in the callback even after the original function has finished executing. For more information see here

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357