Mihir Patel Mihir Patel - 1 month ago 6
AngularJS Question

Javascript Scope - can't access value outside of scope

I would like to access 'key' which happens to be a global variable after being returned from this.dorequest(). I get the key inside the if block but can't access it anywhere outside. Can somebody please assist? Pretty sure it is scope/hoisting issue. Thanks in advance!

var key;
jira.addNewIssue = function(issue) {
var options = {
uri: this.makeUri('/issue'),
method: 'POST',
followAllRedirects: true,
json: true,
body: issue
};

this.doRequest(options, function(error, response, body) {
**var key;** (removed this but still an error)
if (error) {
console.log('Error1')
return;
}
else {
key = response.body.key;
console.log("THIS IS RESPONSE BODY KEY:", key); //no errors 123
return key;
}
});
};

console.log("hello key", key); //undefined

Answer

You are using

var key;

inside the block which means you redefine it in the block scope which makes it a different variable within that scope. Just remove the var statement.

Plus you assign the key variable in an asynchronous call which might not have finished before you arrive at your console.log statement. Move your console.log statement into the callback function OR Create an event to trigger the console.log statement when callback has finished.

Probably not a good idea to use globals inside asynchronous callbacks. I am not sure whether your return statement does anything (depends on the API of the library you are using) but it would certainly not assign the key variable.

Comments