As per my understanding variable \'a\' is a global variable. But when I check this in Chrome cons
tl;dr: Every function is technically a closure in JavaScript.
The global environment is nothing special in this regard (it is special in other ways). It is simply the first environment that gets created and as such sits at the end of every "environment chain". I.e. every environment created during the runtime of a program is created "inside" the global/first/top environment and thus available to all.
See below for more information about how environments and functions are related.
What is a closure?
A closure is a function that can access and resolve free variables. These are variables that are not parameters of the function and not defined in the function itself.
a
is a free variable in your example.
How do functions resolve free variables in JavaScript?
You can imagine an environment/scope to be a table or object that associates a value with a label. For example, the environment that contains
var a = 42;
may look like
+--------+
| a | 42 |
+--------+
Now, when you define a function, it gets a reference to the environment (i.e. this label->value association) it was created in. The environment containing
var a = 42;
function foo(bar) {
console.log(a);
}
will look like
+--------+
|a | 42| +----------------+
|foo | -+---------> FunctionObject |
+--------+ +----------------+
^ |name | "foo" |
| |[[env]] | ---+ -+
| +----------------+ |
| |
+---------------------------------+
Now when foo
is execute, a new environment is created, whose parent environment is the environment the function was created in. I.e. when foo(21)
happens, our state is:
+-----------------+
|bar | 21 |
|[[parent]] | ---+--+
+-----------------+ |
|
+---------------+
|
v
+--------+
|a | 42| +----------------+
|foo | -+---------> FunctionObject |
+--------+ +----------------+
^ |name | "foo" |
| |[[env]] | ---+--+
| +----------------+ |
| |
+---------------------------------+
Now when we try to access a
, it is not found in the current environment, so we look at its parent, where it is defined.
Again, the global environment is nothing special in this regard. It's simply the first environment that gets created, so every function has a reference to it (directly or indirectly in case of nested functions). That's what makes it "global".
Yes it shows in Chrome but not in Mozilla.
First you need to understand lexical scoping in JavaScript. It means that the inner functions have access to the variables and other resources of their parent scope. Here the parent scope is global scope.
This is how the function adds a variable defined outside the function, inside it using closure. In order to execute the function, it will look for the variables it need. Variable 'a' in not defined inside so it will look at scope outside the function till it finds it.
This is a closure.