Let's consider the following code:
let num = 1; // set the value of the variable
function func() {
console.log(num); // print it to the console
}
func(); // call the function
As I mentioned earlier, the variable value does not have to be before the function definition, the main thing is that it should be before the function call:
function func() {
console.log(num);
}
let num = 1;
func();
In fact, this is not entirely true. Our
function even before its call knows the
value of the variable num
:
let num = 1;
function func() {
console.log(num); // the function already knows that num = 1
}
Here's a more complicated example:
let num = 1; // the function at this point learns that num = 1
function func() {
console.log(num);
}
num = 2; // the function at this point learns that num = 2
Add function calls:
let num = 1; // the function at this point learns that num = 1
func(); // shows 1
function func() {
console.log(num);
}
func(); // shows 1
num = 2; // the function at this point learns that num = 2
func(); // shows 2
Once again: in fact, the function knows the values of external variables, even without being called.