hisoka Posted February 21, 2015 Share Posted February 21, 2015 (edited) in this link : http://stackoverflow.com/questions/3684923/javascript-variables-declare-outside-or-inside-loop someone answered : There is absolutely no difference in meaning or performance, in JavaScript or ActionScript. var is a directive for the parser, and not a command executed at run-time. If a particular identifier has been declared var once or more anywhere in a function body(*), then all use of that identifier in the block will be referring to the local variable. It makes no difference whether value is declared to be var inside the loop, outside the loop, or both. "There is absolutely no difference in meaning or performance" "It makes no difference whether value is declared to be var inside the loop, outside the loop, or both" I see that he is totally wrong because if there is no difference in meaning or performance how comes that : var hunter = 0; for(i=0; i<4;i++){hunter = hunter+i;}document.write(hunter); gives 6 as output meanwhile this : for(i=0; i<4;i++){var hunter = 0;hunter = hunter+i;}document.write(hunter); gives 3 as an output ??? Edited February 21, 2015 by hisoka Link to comment Share on other sites More sharing options...
Ingolme Posted February 21, 2015 Share Posted February 21, 2015 You seem to have misunderstood. What makes no difference is where the var keyword is, but what does make a difference is where the assignment is. That means these two blocks of code should behave the same: var hunter;hunter = 0;for(i=0; i<4;i++){hunter = hunter+i;}document.write(hunter); hunter = 0;for(i=0; i<4;i++){var hunter;hunter = hunter+i;}document.write(hunter); 2 Link to comment Share on other sites More sharing options...
Jonathanks Posted February 21, 2015 Share Posted February 21, 2015 Yea. Ingolme has explained it.In your first loop, the assignment was done outside the loop so each time the loop is run, the value of the variable 'hunter' is updated outside and is stored.In the second loop, the value is updated inside of the loop, stored and output with the document.write() function. But each time the loop is run, the variable 'hunter' is reassigned to 0. Hence you have 3 instead of 6. Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now