Monday, February 18, 2019

scope - Confusion with JavaScript scoping




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?


Answer



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.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...