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

52,368

Solution 1

Thanks. I declared the variable as global and inserted value inside the inner function and then made a function call inside the function to trigger another function which call the value.

var a=0;
var surveyObjects = Parse.Object.extend(surveyObject);
var query= new Parse.Query(surveyObjects);
query.count({
    success: function(count) {a =count; total();},
    error:function(error){}
});

function total(){alert (a);}

Solution 2

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) {}
});

Solution 3

You can do this by using implicit global variable behaviour.

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

one();
console.log(a);

If you don't declare a variable in javascript I.E not using the var keyword it becomes a global variable.

for further reading:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/var#Implicit_globals_and_outer_function_scope

Solution 4

//  You can simply do it by 
function test()
{
    this.name='xyz';
}
var obj = new test();

console.log(obj.name);

Solution 5

use return statement to access variables globally.

function(){
var k=1;//local
return k;//global
}
result=k+10;//sample
Share:
52,368
Syam Ps
Author by

Syam Ps

Updated on January 03, 2020

Comments

  • Syam Ps
    Syam Ps over 4 years

    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.

    • GolezTrol
      GolezTrol over 7 years
      You can't, unless you modify the code.
    • Alexander O'Mara
      Alexander O'Mara over 7 years
      That code you have is nonsensical.
    • Kishore Barik
      Kishore Barik over 7 years
      declare the variable in outer scope / global scope
  • VLAZ
    VLAZ over 7 years
    This is not really related to hoisting. The hoisting mechanism only ensures that your declarations are processed first so if you have var a on line 10 in your application you will be able to use it on line 4 without getting ReferenceError. However, hoisting does not make a variable move scopes.
  • Syam Ps
    Syam Ps over 7 years
    thanks guys .but the problem is i am using parse and using promises so it would be function one (){ query.count({ success: function(count) {c =count;}, error :function(error){} }); } alert(c); i need to get value of c here .
  • Sami Ahmed Siddiqui
    Sami Ahmed Siddiqui over 7 years
    You should have made that clear in your question that you're using Parse. You can access variables inside a promise handler function the same way described in my answer. Also, the Parse service is deprecated and being shut down in a few months.
  • Syam Ps
    Syam Ps over 7 years
    thanks guys .but the problem is i am using parse and using promises so it would be function one (){ query.count({ success: function(count) {c =count;}, error :function(error){} }); } alert(c); i need to get value of c here .
  • Syam Ps
    Syam Ps over 7 years
    yes we use parse open source server . so is there any way to get the value outside from the success function ?
  • Sami Ahmed Siddiqui
    Sami Ahmed Siddiqui over 7 years
    I've updated my answer to include a contrived example of setting variables outside promises. You should REALLY update your question with an example that's closer to your actual issue.
  • Syam Ps
    Syam Ps over 7 years
    but its still showing undefined . var a ; query.count({ success:function(count){ a=count; return a;},error: function(err){} }); alert(a);
  • Sami Ahmed Siddiqui
    Sami Ahmed Siddiqui over 7 years
    Please put that code in your original question so I can answer it properly. You're running into async issues is why this is happening.