In JavaScript (most often not in other languages), variables defined outside of a function will be visible inside that function. Such variables are called global. Let's look at an example:
let num = 1; // variable outside the function
function func() {
console.log(num); // the num variable is visible inside the function
}
func(); // shows 1
In fact, the variable need to be defined not before the definition of the function, but before calling it:
function func() {
console.log(num);
}
let num = 1; // variable outside the function
func(); // shows 1
If you change the value of the variable and then call the function each time, the alert will give different results each time:
function func() {
console.log(num);
}
let num; // declare a variable
num = 1; // set the value 1
func(); // shows 1
num = 2; // set the value 2
func(); // shows 2
If we have several functions, then the global variable will be available in each of these functions:
function func1() {
console.log(num);
}
function func2() {
console.log(num);
}
let num = 1;
func1(); // shows 1
func2(); // shows 1
If changes occur with a global variable in one function, then this variable will change in all functions using this variable:
function func1() {
console.log(num);
num++; // change global variable
}
function func2() {
console.log(num);
}
let num = 1;
func1(); // shows 1
func2(); // shows 2
Since any of the functions can easily change the global variable, their use is a breeding ground for subtle errors. For this reason, the use of global variables in a script should be kept to a minimum. It is desirable that they do not exist at all or that there is a minimal amount.
Determine what will be output to the console without running the code:
let num = 1;
function func() {
console.log(num);
}
func();
Determine what will be output to the console without running the code:
let num = 1;
function func() {
console.log(num);
}
num = 2;
func();
Determine what will be output to the console without running the code:
function func() {
console.log(num);
}
let num;
num = 1;
func();
num = 2;
func();