Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the variable inside this function global?

I thought any variable defined in a function would be local but I can easily access variable 'e' outside of its function.

function change() {
 var d = 6; 
  e = 7;
}

change();
alert(e); //> alerts 7
like image 346
David G Avatar asked Feb 28 '26 04:02

David G


2 Answers

Because new variables will enter the global scope by default. var prevents this from happening by constraining a variable's existence to be within the current scope.

like image 160
kqnr Avatar answered Mar 01 '26 17:03

kqnr


Because it was declared without var it becomes part of the global window object.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!