Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a variable inside a function which is inside a function in javascript?

How can I access a variable inside a function which is inside a function in javascript ?

var a;
var surveyObjects = Parse.Object.extend(surveyObject);
var query= new Parse.Query(surveyObjects);
query.count({
    success: function(count){a = count;},
    error: function(error){}
});
alert("count of function "+a);

a is showing undefined value. I need to use the value of a outside.

like image 865
Syam Ps Avatar asked Dec 01 '22 12:12

Syam Ps


1 Answers

Because of how javascript, and most languages, scope variables, you can't access variables declared inside a function from outside a function. The variable belongs to the function's scope only, not the global scope.

Fortunately, functions inherit the scope of their caller. So the easiest way to make your variable accessible from outside the function is to first declare outside the function, then use it inside the function.

function one(){
   var a;

   function two(){
       a = 10;
       return a;
   }

   return a;
}

Note that you should be very careful about how you scope your variables. The whole point of functions is to encapsulate and isolate functionality.

In the case of promises, you can declare a variable outside the promise and then set its value on success.

var a;

Parse.doSomething().then(function(data) {
    a = data;
});

EDIT: Based on what you showed in the comments, you're having async issues. Promises are asynchronous meaning they don't run in sequence in your code. That's why the success and error callbacks exist, to be called once the promise resolves. Your alert(a) is outside the promise callback, so it runs immediately, without waiting for the Parse promise to resolve so a is still undefined. If you put the alert(a) inside the promise callback, a will have been set by that point.

var a;
query.count({
    success: function(count) {
        a = count;
        alert(a);
        return a;
    },
    error: function(err) {}
});
like image 194
Soviut Avatar answered Dec 04 '22 01:12

Soviut