Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation of how is the variable "leaking"?

Tags:

javascript

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..).

like image 617
Strawberry Avatar asked Jan 23 '15 03:01

Strawberry


2 Answers

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

like image 171
Soufiane Hassou Avatar answered Oct 09 '22 03:10

Soufiane Hassou


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).

like image 30
Felix Kling Avatar answered Oct 09 '22 04:10

Felix Kling