<html> <head> <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> <script> function incrementby(start, numberofiterations) { var s = start var n = numberofiterations; return function(){ for (var i = s; i < n; i++) result++; alert('variable "result" equals ' + result); } } var incrementtest = incrementby(0, 10); </script> </head> <body> <div>Why does the alert in incrementby() above say that variable "result" equals 20 instead of 10?</div> <div><button id="run" >Run</button></div> <script> $(function(){ $("#run").click(incrementtest); }); result = 10; </script> </body> </html>
When the page is loaded result is initialized with 10. After that, when the you click the "run" button you call incrementtest and, increment it with additional 10.
result
10
incrementtest
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)