1
<script type="text/javascript">

  var number = "10";

  (function(){
    alert(number);    
    alert(eval('number=22'));

  })();

  var func = function() {
      alert (new Function( 'return (' + number + ')' )());
  }

  func(); // prints 22.

</script>

It first alerts 10, then alerts 22 then why is it alerting 22 again instead of 10. Does eval function overrides my variable in global scope.

Kevin
  • 23,174
  • 26
  • 81
  • 111

3 Answers3

4

No, eval isn't executed in the global scope but you don't have a variable named number in your local scope. So you're changing the global one.

You may see it with this little change :

(function(){
  var number; // this will ensure the global number isn't changed
  alert(number);  // this will print "undefined"
  alert(eval('number=22')); // this won't change the global variable
})();

Note that alert(eval('number=22')); returns the result of the evaluation and number=22 returns 22. That's why the second alert gives 22.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

Since you don't have a variable in your local scope, its changing the global one. Try this one below. It would print 100 instead of 22.

<script type="text/javascript">


  var number = 100;

  (function(){
    var number;
    alert(number);    
    alert(eval('number=22'));

  })();

  function func() {
      alert (new Function( 'return (' + number + ')' )());
  }

  func();

</script>
Thalaivar
  • 23,282
  • 5
  • 60
  • 71
0

eval is evil

don't use it.

If you remove the use of eval what is happening is maybe more obvious - you are redefining the value of the global variable number inside the first anonymous function:

var number = "10";

(function(){
    number = 22; // this is a reference to the global variable `number`
})();

var func = function() {
    alert (new Function( 'return (' + number + ')' )()); // this is another use of eval - don't do this
}

func(); // prints 22 - expected.
Community
  • 1
  • 1
AD7six
  • 63,116
  • 12
  • 91
  • 123
  • This is fine... it would change the global one, but in the case above i am using eval... does that too do the same thing. – Kevin Dec 29 '12 at 20:08
  • @Kevin er.. yes. that's the point. eval just executes the evaluated code wherever you've put it. It is not a magic execution sandbox. – AD7six Dec 29 '12 at 20:09
  • and since its not able to find any variable in its scope, it changes the global scope which also gets reflected in other function... sorry for the trouble... – Kevin Dec 29 '12 at 20:11