I was reading about hoisting in mozilla, and noticed an example explaining how a variable can leak outside of the function scope: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#Initialization_of_several_variables
The example says,
var x = 0;
function f(){
var x = y = 1; // x is declared locally. y is not!
}
f();
console.log(x, y); // 0, 1
// x is the global one as expected
// y leaked outside of the function, though!
I don't understand what is happening here. I am looking for a technical explanation more than anything. How is y accessible outside at this point?
Edit: I understand how this function is behaving, and I should clarify and say I wanted an understanding of what is happening in the code and memory (ex, pointers, etc..).
you have var x = y = 1
which means that x is declared inside but y is not, var
doesn't apply to y in this case, that's why it's leaked outside the function
This is breakdown of the statement:
var x = y = 1;
\___/ \____/
identifier initializer
\____________/
variable declaration
In this case the initializer is another assignment. Due to variable hoisting, this statement is evaluated as follows:
var x;
x = y = 1;
As you can see, y
is not declared. Assigning to an undeclared variable creates a global variable (implicitly).
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