1

I thought this is how you make a variable inside a if/else block global (Case 3).

connection.query(sql, function (err,rows){

    //Handle Errors
    if(err){
        //Log The Error & Die
    }

    //If Successful - Log Results For Now (Change To Export Results)
    else {
        //console.log(rows);
        foo = rows;

    }

});

console.log(foo); // Out: undefined

Why can't I access the variable outside of the function?

SOLUTION

Well, the problem here was one of understanding what asynchronicity really is. After chatting with @AmmarCSE and looking at this great question here on SO I understood that I structured my question (and my code, obviously) incorrectly.

I was trying to access a variable that is not defined until the function finishes to run (an SQL query to a remote DB obviously takes longer to finish then running a local script). If I structure my code asynchronically, however, the variable only gets called once the function finishes.

This, as it turns out - is not a problem of variable scope, really, but of variable defining time (not sure if that's the correct terminology for the time in the script where the variables get defined - CS majors, feel free to edit in the correct term).

Anyway, Here is the new code:

runSQL(function(result){

//Do Whatever you want with the results - they're defined!!
console.log(result);
)};

function runSQL(callback){

connection.query(sql, function (err,rows){

        //Handle Errors
        if(err){
            //Log The Error & Die
        }

        //If Successful - Log Results For Now (Change To Export Results)
        else {
            callback(rows);            
        }

    });

}
13
  • possible duplicate of What is the scope of variables in JavaScript? Commented Jun 13, 2015 at 9:34
  • You can, but callbacks don't execute when you think they do. Commented Jun 13, 2015 at 9:35
  • I KInda Pointed That As My Reference. Commented Jun 13, 2015 at 9:36
  • @DaveNewton How So? What Am I Missing Here? Commented Jun 13, 2015 at 9:36
  • I know I answered, but actually, I have a question. Shouldnt foo above still work because it is a global variable because it was defined without var? Commented Jun 13, 2015 at 9:40

3 Answers 3

1

When you are in the error callback, it has its own scope defined. Therefore, foo is only visible to that closure and any nested closures. For case 3 you have mentioned in the link

var a = 1;

function four() {
  if (true) {
    var a = 4;
  }

  alert(a); // alerts '4', not the global value of '1'
}

they alert the variable within the correct closure, function four(), even if that variable was defined in the if block, it is visible to its parent function.

However, you are making foo global by not prefixing with var. Yet, logging after the callback results in undefined because at that point, foo was not yet defined. If you log within the error callback it will work but I advise you restructure your code to work with the asynchronous nature of callbacks

connection.query(sql, function (err,rows){

    //Handle Errors
    if(err){
        //Log The Error & Die
     }

    //If Successful - Log Results For Now (Change To Export Results)
    else{
        //console.log(rows);
        foo = rows;

    }
    console.log(foo);
    });
Sign up to request clarification or add additional context in comments.

1 Comment

OK! But - I Need To Eventually Export That Variable Into A Different Module, And I Can't Do That From Within The Block. How Can I Make Sure foo Is Defined Outside Of function & connection.query?
0

if you put a var foo = "something" in somewhere it'd would equal "something". I suppose it didn't go into the else otherwise it'd equal rows... Also is it possible rows is undefined?

Also without using a var foo = anywhere it becomes a global variable if the foo = bit is executed, which is probably not desirable...

Comments

0
var result= connection.query(sql, function (err,rows){

    //Handle Errors
    if(err){
        //Log The Error & Die
     }

    //If Successful - Log Results For Now (Change To Export Results)
    else{
        //console.log(rows);
        document.foo = rows;

    }

    });

result.on('result', function(){
    console.log(document.foo);
}

5 Comments

It Throws Back That window is not defined.
sorry window is not used in nodejs, use document instead
First, this is node. Second, this isn't the issue.
@DaveNewton sorry i dont see from the Q where globals are not the issue? Nodejs is only tagged below and i've updated to use document instead and a callback...
Scope isn't the issue, asynchronicity is. You edited after my comment; obviously if you change the answer's content a comment made prior to the edit won't necessarily make sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.