I am a beginner in JS and I have difficulty understanding why the output of my var is "Undefined." My JS runs a GET to download a JSON file and with a function, I am trying to read the file and return the first line:
invest.stock('APPLE', function (err, data) {
if (err) { console.log('ERROR', err); return; }
var APPLE_price = data.order[0]['price'];
console.log(APPLE_price); //until here works fine
});
console.log(APPLE_price); //output "Undefined" var
I tried declare the var previously, I created a statement to wait the var (because was a async function) but nothing works.
-
3Look at javascript variable scope.Matt Greenberg– Matt Greenberg2018年03月28日 00:49:48 +00:00Commented Mar 28, 2018 at 0:49
-
@Felipe, I added answer, Hope it will help you to understand the function level scope of the variable in javascript.Rohìt Jíndal– Rohìt Jíndal2018年03月28日 07:05:03 +00:00Commented Mar 28, 2018 at 7:05
4 Answers 4
Declare the variable outside of the function first:
var APPLE_price;
invest.stock('APPLE', function (err, data) {
if (err) { console.log('ERROR', err); return; }
APPLE_price = data.order[0].price;
console.log(APPLE_price); //until here works fine
});
setTimeout(() => console.log(APPLE_price), 2000);
But it would be far more elegant to use a callback or a Promise:
function getApplePrice() {
return new Promise((resolve, reject) => {
invest.stock('APPLE', function(err, data) {
if (err) {
reject(err);
return;
}
resolve(data.order[0].price);
});
});
}
getApplePrice().then(applePrice => {
console.log('applePrice is ' + applePrice);
})
Comments
your problem here is the variable scoop it's called the local scoop, you can't use
var APPLE_price outside the function
you can find a reference here for javascript scoops JavaScript Scopes for that.In this situation, you can declare the variable outside the function
var Name = " john";
function myFunction() {
// code here can use Name
}
// code here can use Name
Comments
The issue here is scope.
Since the scope of APPLE_PRICE is limited to the function it is in you cannot access it outside the function. But best to read some tutorials on variable scoping in JavaScript.
Comments
var APPLE_price = data.order[0]['price'];
Here, APPLE_price is a Local variable (Function-level scope). As it is declared within a function. Hence, only accessible within that function or by functions inside that function.
If you want access APPLE_price outside of a function you need to declare it outside the function.
var APPLE_price;
invest.stock('APPLE', function (err, data) {
if (err) { console.log('ERROR', err); return; }
APPLE_price = data.order[0]['price'];
console.log(APPLE_price); // value of data.order[0]['price']
});
console.log(APPLE_price); // value of APPLE_price under invest.stock function.