When creating the function foo here, I reference a variable fromTheFuture the hasn’t been declared yet. This actually works as expected, but why? Is it considered dangerous or bad practice?
var foo = function(x) {
return fromTheFuture * x;
};
var fromTheFuture = 5;
console.log(foo(10));
I can see this being very convenient though, if you have several functions that wants use each other in a cycle fashion – without having to declare them all with var in the beginning of the method.
By the time
foois called,fromTheFutureis defined. More accurately, due to hoisting, your code is essentially:If you were to call
foo(10)beforefromTheFuture=5, you would getNaN.