I was reading this article and I have some questions please:
considering this code :
1: var a = 1;
2: function b () {
3: a = 10;
4: return;
5: function a() {}
6: }
7: b();
8: alert(a);
this will alert 1. ( my question is why ? )
the article states its related to Name resolution.
Name resolutions (according to the article ) is being determined by this order:
1. Internal mechanisms of language: for example, in all scopes are available “this” and “arguments”.
2. Formal parameters: the functions can be named as the formal parameters, which scope is limited to the function body.
3. Function declarations: declared in the form of function foo() {}.
4. Variable declarations: for example, var foo;.
line #3 suppose to change the value of the global a.
but the function a(){…} have a priorty over the inside a declaration ( If i understood correctly)
and thats why is alerts 1
p.s. if i remove line #5 , it will alert 10.
In general, if a name is already defined, it will never be redefined
by another entity with the same name. That is the function declaration
has a priority over the declarations of the variable with the same
name. But this does not mean that the value of a variable assignment
does not replace the function, just its definition will be ignored.
I dont understand that part :
But this does not mean that the value of a variable assignment does
not replace the function
so 2 questions please :
-
Did I understand correctly the reason for alerting 1
-
What does the above line means ? (the misunderstood part)
thanks.
Yes
It just means that although a function with name
ais already defined,a = 10is still going to be executed, i.e. after that lineadoes not refer to a function anymore but to10.I assume they wanted to relax the previous statement a bit and avoid that people incorrectly think that because the function declaration is executed first, the assignment would not take place anymore.
Function and variable declarations are hoisted to the top of the scope. So the code is equivalent to:
function a() {...}creates a symbol (variable)ain the local scope and its value is the very same function. The next line,a = 10;, then assigns a new value to that symbol, namely a number.