This is the order of execution:
1 var request = require("request"); 2 var myMonzoBalance; 3 request({ uri: "https://api.monzo.com/balance?account_id=acc_XXXXXXXXX", method: "GET", headers: {'Authorization': 'Bearer XXXXXXX'} }, function(error, response, body) { 5 myMonzoBalance = JSON.parse(body).balance; 6 console.log(myMonzoBalance); }); 4 console.log(myMonzoBalance);
It is not the case that it is undefined outside of the function. It's just not defined yet when you run the final console.log().
Of course it's also possible that you don't get any response from the request (you cat test it by running console.log(body) instead of console.log(myMonzoBalance) in the callback function) but even if you get the response and it has a balance field then this line myMonzoBalance = JSON.parse(body).balance would still run after the value is printed in the last line of your code.
First step of fixing the problem would be to change the code to make sure that you get the right response:
var request = require("request"); var myMonzoBalance; request({ uri: "https://api.monzo.com/balance?account_id=acc_XXXXXXXXX", method: "GET", headers: {'Authorization': 'Bearer XXXXXXX'} }, function(error, response, body) { if (error) { console.log('ERROR:', error); } else { console.log('BODY:', body); console.log('BALANCE:', JSON.parse(body).balance); } });
and only if it prints what you need try to fix the timing issue.
To get a better understanding on the asynchronous nature of Node that is giving this execution order here, see those answers:
This is the most common thing in Node that people confuse and I've written a lot of answers about it which you may also find helpful.