I have a fair bit of understanding about JavaScript scoping -- that the language has function-level scope and the variable and function declarations are hoisted to the top of their containing scope. However, I can't figure out why the following two pieces of code log different values:
This logs the value 1 to the console:
var a = 1;
function b() {
a = 10;
return;
function a() {}
}
b();
console.log(a);
And mysteriously, this logs 10:
var a = 1;
function b() {
a = 10;
return;
}
b();
console.log(a);
So what's going on underneath the hood?
I find the first example more mysterious...
In the second example, you do not declare a variable a
inside of the function. So when you assign to a
, it targets the a
on the outside. Pretty straight-forward.
In the first example, you declare a variable a
inside of the function, but in an unusual way: By declaring a function called a
. So assigning to a
will use that local "variable".
Two things to take away here:
a) Variable and function declarations are "hoisted" to the top of their scope. While function a(){}
is written near the end, the variable a
to hold it is already created and visible at the top of the scope.
b) Functions can be used as variables as well. You can pass functions around, you can re-assign function definitions. They share the same namespace with other variables.
Its because when you use a declared function
it is hoisted up and turned into a function expression, ie var a = function() {};
This is creating a clash with your a
variable.
You can use Visual-Studio for coding:
Programming the code in a TypeScript-File will enable you to see the variable Types by hovering the variable.
It will also warn you, when you try to apply the numerical-value 10 to the variable "a", that was first declared to be a function. That's what I love about TypeScript, you can get more Information about it here: http://www.typescriptlang.org/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With