Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript error because of global scope variables

Tags:

javascript

var x = 3;
(function (){
  console.log('before', x);
  var x = 7;
  console.log('after', x);
  return ;
})();

In the above code var X is initialized globally. So inside the function the first console.log should print "before 3" but i don't get it. The reason is that i am trying to re-declare the global variable.

Can somebody explain why this is happening?

like image 335
harikrish Avatar asked Jan 30 '26 18:01

harikrish


1 Answers

In the above code var X is initialized globally. so inside the function the first console.log should print "before 3".

No, it should print before undefined, because var takes effect from the beginning of the function regardless of where you write it.

Your code is exactly the same as this:

var x = 3;
(function (){
 var x;

 console.log('before', x);
 x = 7;
 console.log('after', x);
 return ;
})();

And of course, variables start with the value undefined.

Details: Poor misunderstood var

like image 149
T.J. Crowder Avatar answered Feb 01 '26 08:02

T.J. Crowder



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!