gzbuaapzroyn gzbuaapzroyn - 1 year ago 84
Javascript Question

Using closure for storing and retrieving data

I am trying to use closure for storing and retrieving variable at the same time.

I am using

and callback to the function



function geoIPInfo(newGeoData) {
var geoInfo;
if (newGeoData) {
geoInfo = newGeoData;
var provideGeoData = function () {
return geoInfo;

return provideGeoData();

I want firstly to store data and than retrieve last saved data from the closure using simple call like that


If argument provided it will set new info otherwise it will return existing one.

But in my case data is set successfully, but when I try to get set data I get

$("#super_button").click(function (e) {

What is wrong with my closure understanding ?
Please explain.

Thank you.

Answer Source

This will work. The idea here is we create a function that returns a function with that accepts a parameter and we store geoInfo in a closure to keep it value. Idk if that makes sense, if you need a better explanation I can give it another try :)

var geoIPInfo  = function() {
    var geoInfo;
    var provideGeoData = function (newGeoData) {
        if (newGeoData) {
            geoInfo = newGeoData;
        return geoInfo;
    return provideGeoData;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download