var name = "Michael";
// the blocks in this if statement do not create a local context for the name variable
if (name) {
name = "barack"; // this name is the global name variable and it is being changed to "Jack" here
console.log (name); // barack: still the global variable
}
// Here, the name variable is the same global name variable, but it was changed in the if statement
console.log (name); // Barack
But the above doesn’t look like to be a local variable but seems to be behaving like a global variable.
can we please discuss more about the scope of the variable here?
I don’t blame you for being confused. The code has “Michael” and “barack” values being assigned, yet the comments refer to “Jack” which is not in the code.
let is the descendant of var in modern JavaScript. Its scope is not only limited to the enclosing function, but also to its enclosing block statement. A block statement is everything inside { and }, (e.g. an if condition or loop).
Should we conclude:
It is accessible anywhere in the block
It is accessible anywhere in the function.
I think the above two points can also be termed as closure. Right?
What I learned yesterday I think it is not wise to declare variables globally, but look here in the above-mentioned code many variables are declared outside the functions. Is it ok? or there is a better way? or there was no other way?
If your interest is instead about why it has to be global, it doesn’t have to be global at all.
A common practice is to protect the global namespace by placing all of your code inside of an IIFE (immediately invoked function expression) so that you can define whatever you like in there, without them becoming global variables.
There is only closure when a function is returned out of its parent function. That returned function retains knowledge of its parents scope, via a technique called closure.