Same variables name in JavaScript functions
Let there be the variable num both
outside the function and inside. In this
case, any changes to the local variable
num do not affect the global
variable num:
let num = 1; // the global variable
function func() {
let num = 2; // the local variable
console.log(num);
}
func(); // call the function, 2 will be output
console.log(num); // shows 1 - the global variable hasn't changed
But, if we forget to declare the local variable
num through let, then the local
variable num will not be created inside
the function, but the global variable will
simply change:
let num = 1;
function func() {
num = 2; // we forgot to write let - it changes the external variable
console.log(num);
}
func(); // call the function, 2 will be output
console.log(num); // shows 2 - the variable has changed
There can be two situations here: either we
really wanted to change the global variable
(then everything is OK), or we forgot let
and accidentally changed the global variable.
The second case is a subtle error leading to
unpredictable script behavior. Therefore,
always, when introducing a new variable,
declare it through let.
Determine what will be output to the console without running the code:
let num = 1;
function func() {
num = 2;
}
func();
console.log(num);
Determine what will be output to the console without running the code:
let num = 1;
function func() {
let num = 2;
}
func();
console.log(num);