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